我在我的应用程序中同时使用了 BlocProvider 和 ChangeNotifierProvider。应用程序的流程在这里: -
- 第一次用户打开应用程序: InstructionPage() -> WelcomePage() -> HomePage() //得到错误
- 第二次用户打开应用程序: HomePage() //工作正常
我使用 sharedPreference 来存储 isInstructionPageLoaded 的值。但是从 WelcomePage() 导航到 HomePage() 出现错误找不到此 ChangeLocation 小部件上方的正确提供程序
这是我的代码:-
//main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await StorageUtil.getInstance();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: Theme.of(context).copyWith(primaryColor: kBgColorGreen),
home: MultiBlocProvider(
providers: [
BlocProvider(
create: (context) =>
RestaurantBloc()..add(RestaurantPageFetched())),
],
child: MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => LocationServiceProvider()),
],
child: StorageUtil.getBoolValue(
SharedPrefsKeys.isInstructionPageLoaded)
? HomePage()
: InstructionScreen(),
)),
routes: Routes.getRoutes(),
);
}
}
//routes.dart
class Routes {
static const String instruction = '/instruction';
static const String welcome = '/welcome';
static const String home = '/home';
static const String change_location = '/change_location';
static Map<String, WidgetBuilder> getRoutes() {
return {
Routes.instruction: (context) => InstructionScreen(),
Routes.welcome: (context) => WelcomePage(),
Routes.home: (context) => HomePage(),
Routes.change_location: (context) => ChangeLocation(),
};
}
}
//location_service.dart
class LocationServiceProvider extends ChangeNotifier {
void toogleLocation(LocationService location) {
location.isLocationUpdated = !location.isLocationUpdated;
notifyListeners();
}
}
class LocationService {
bool isLocationUpdated = false;
}
//welcome_page.dart - 按下按钮调用下面的方法
void _navigateToHomePage() async {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return BlocProvider(
create: (context) => RestaurantBloc()..add(RestaurantPageFetched()),
child: ChangeNotifierProvider(create: (context) => LocationServiceProvider(),
child: HomePage(),),
);
}));
}
我在上面的方法becoz中添加了BlocProvider,然后它给我错误 blocprovider.of()调用的上下文不包含从其他屏幕导航的块,从WelcomePage()导航到HomePage()。
提前致谢!!!