我在我的应用程序中同时使用了BlocProvider和ChangeNotifierProvider。应用程序的流程如下:-
我使用sharedPreference来存储isInstructionPageLoaded的值。但是,在从WelcomePage()导航到HomePage()获取错误时,ChangeLocation Widget上找不到正确的提供程序
这是我的密码:-
//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(),
);
}
}//常规。
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;
}//迎宾_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(),),
);
}));}
我在上述方法中添加了BlocProvider,因为在调用blocprovider.of()之前,它给我提供了一个上下文,该上下文不包含从其他屏幕导航的区域,从WelcomePage()导航到HomePage()。
提前谢谢!
发布于 2021-04-28 21:40:53
为了确保块暴露在新的路由中,您需要遵循文档并添加BlocProvider.value()来向新路由提供该块的值。这将承载欧盟的状态,使你的生活更轻松。
检查官方文件以获得一步一步的清晰指南;)
https://stackoverflow.com/questions/67212745
复制相似问题