Flutter获取全局context(诸如一些工具类使用)

1创建一个全局的GlobalKey

  class Global{
     static GlobalKey navigatorKey = GlobalKey();
  }

2MaterialApp中设置navigatorKey

 return MaterialApp(
    title: 'Flutter Demo',
    theme: ThemeData(
    primarySwatch: Colors.blue,
  ),
  navigatorKey: Global.navigatorKey,
  routes: {
    "login": (context) => MyApp1(),
   );

3诸如工具类需要context获取context

    BuildContext? context = Global.navigatorKey.currentState!.context;

你可能感兴趣的:(Flutter获取全局context(诸如一些工具类使用))