【发布时间】:2021-07-16 15:30:07
【问题描述】:
我在我的应用程序中同时使用了 BlocProvider 和 ChangeNotifierProvider。应用程序的流程在这里:-
- 第一次用户打开应用:InstructionPage() -> WelcomePage() -> HomePage() //getting error
- 用户第二次打开应用:HomePage() //工作正常
我使用 sharedPreference 来存储 isInstructionPageLoaded 的值。 但是从 WelcomePage() 导航到 HomePage() 时出现错误在此 ChangeLocation 小部件上方找不到正确的 Provider
这是我的代码:-
//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(),),
);
}));
}
我已经在上面的方法中添加了 BlocProvider ,因为它给了我错误 blocprovider.of() 调用的上下文不包含从其他屏幕导航的块,从 WelcomePage() 导航到 HomePage()。
提前致谢!!!
【问题讨论】:
标签: flutter provider flutter-provider flutter-bloc flutter-change-notifier