This problem generally occurs when operating routes directly in the main.dart file.
The above situation prompts that the routing controller needs a context but the current navigator does not contain it. Generally speaking, the routing (Navigator) should be used, and the root control cannot be directly a MaterialApp.
Solution: Wrap the MaterialApp content with StatelessWeight or 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;
},
);
}