flutter报错Navigator operation requested with a context that does not include a Navigator

此问题一般情况出现在直接在main.dart文件中操作路由。

如上情况提示路由控制器需要一个context但是当前navigator并不包含,通俗的讲要使用路由(Navigator),根控件不能直接是 MaterialApp.

解决方法:将 MaterialApp 内容再使用 StatelessWeight 或 StatefulWeight 包裹一层

void main() async{
  await setupServiceLocator();
  /// 微信、QQ注册
  runApp(MultiProvider(
    // 状态管理
    providers: [
      ChangeNotifierProvider(create: (_) => UserProvider()),
    ],
    child: MyAppPrepare(),//解决MaterialApp中的跳转路由的context问题
  ));
}


///解决MaterialApp中的跳转路由的context问题
class MyAppPrepare extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      builder: (context, widget) {
        return MediaQuery(
          ///设置文字大小不随系统设置改变
          data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
          child: FlutterEasyLoading(child: widget),
        );
      },
      home: GestureDetector(
        /// 全局键盘关闭
        onTap: () {
          FocusScopeNode focusScopeNode = FocusScope.of(context);
          if (!focusScopeNode.hasPrimaryFocus &&
              focusScopeNode.focusedChild != null) {
            FocusManager.instance.primaryFocus?.unfocus();
          }
        },
        child: MyApp(),
      ),
      theme: ThemeData(primarySwatch: ColorTool.white),
      localizationsDelegates: [
        RefreshLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        CupertinoLocalizationsDelegate(),
      ],
      supportedLocales: [Locale('zh', 'CN')],
    );
  }
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }

  static BuildContext getContext() {
    return _MyAppState.getContext();
  }
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver{
  RouteManager _routeDelegate = RouteManager();
static BuildContext appContext;


  static BuildContext getContext() {
    return appContext;
  }

  @override
  void initState() {
    super.initState();
    //添加观察者,检测页面生命周期
    WidgetsBinding.instance.addObserver(this);
    EventBusUtils _event = EventBusUtils.instance;
    if (CacheManager.shared.prefs != null && CacheManager.shared.getString("isShowAgreement") != null) {
      _prepareInitIM();
    }
  }

  @override
  void dispose() {
    super.dispose();
    //页面销毁时,移出页面生命周期监听者
    WidgetsBinding.instance?.removeObserver(this);
  }


  @override
  Widget build(BuildContext context) {
    appContext = context;
    return FutureBuilder<CacheManager>(
      future: CacheManager.preInit(context),//进行初始化
      builder: (BuildContext context, AsyncSnapshot<CacheManager> snapshot) {
        //定义route
        var _widget = (snapshot.connectionState == ConnectionState.done && 
                 snapshot.data != null)
            ? Router(routerDelegate: _routeDelegate)
            : snapshot.connectionState != ConnectionState.done
            ? Scaffold(
                    body: Center(
                      child: CircularProgressIndicator(color: ColorTool.red),
                    ),
                  )
                :_showAgreementWindow(appContext);
        return _widget;
      },
    );
  }

猜你喜欢

转载自blog.csdn.net/LoveShadowing/article/details/123332729
今日推荐