Flutter - 无法在此 ChangeLocation Widget 上方找到正确的 Provider<Provider>

Flutter - Could not find the correct Provider<Provider> above this ChangeLocation Widget

提问人:Subhangi Pawar 提问时间:4/22/2021 最后编辑:General GrievanceSubhangi Pawar 更新时间:2/11/2022 访问量:388

问:

我在我的应用程序中同时使用 BlocProvider 和 ChangeNotifierProvider。应用程序的流程如下:-

  1. 用户首次打开应用: InstructionPage() -> WelcomePage() -> HomePage() //获取错误
  2. 第二次用户打开应用程序: 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.飞镖

class LocationServiceProvider extends ChangeNotifier {
  void toogleLocation(LocationService location) {
    location.isLocationUpdated = !location.isLocationUpdated;
    notifyListeners();
  }
}

class LocationService {
  bool isLocationUpdated = false;
}

welcome_page.飞镖 - 按下按钮,调用以下方法

 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() 的 bloc。

提前致谢!!

flutter-provider flutter-bloc flutter-change-notifier

评论


答:

0赞 Younss AIT MOU 4/29/2021 #1

若要确保 bloc 向新路由公开,需要按照文档操作并添加 BlocProvider.value() 以向新路由提供 bloc 的值。这将承载集团的状态,让你的生活更轻松。

查看官方文档以获取清晰的分步指南;)。