【问题标题】:How to Navigate without context in flutter?如何在没有上下文的情况下导航?
【发布时间】:2020-10-28 13:01:58
【问题描述】:

我最终使用了一个静态函数,但我需要进行导航,它给了我一个错误,即没有为上下文找到 getter,所以我寻找解决方案并找到了 GET 包,但是当我尝试使用它时它给出了我的另一个错误:

E/flutter ( 6078): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] 
Unhandled Exception: NoSuchMethodError: The method 'push' was called on null.

我的代码:

    void main() {
      runApp(MyApp());
      _MyAppState.autologin();
    }
    
    class _MyAppState extends State<MyApp> {
      static autologin() async {
        var userType;
        var store = Firestore.instance;
        var auth = FirebaseAuth.instance;
        final FirebaseUser user = await auth.currentUser();
        store.collection('Users').document(user.uid).get().then((value) {
          userType = (value.data)['userType'];
          if (userType == 'Student') {
            Get.to(StudentsPage());
          } else if (userType == 'Teacher') {
          } else if (userType == 'Admin') {}
        });
      }

【问题讨论】:

    标签: flutter navigation android-context


    【解决方案1】:

    创建导航键

    final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
    

    将其分配给 MaterialApp

    MaterialApp(
        home: Home(),
        navigatorKey: navigatorKey
    ),
    

    然后通过下面的 navigatorKey 推送你的路线

    navigatorKey.currentState.push(MaterialPageRoute(
        builder: (context) => AnotherPage(),
    ));
    

    navigatorKey.currentState.pushNamed(routeName);
    

    【讨论】:

    • 它告诉我 navigatorKey 没有被定义为 getter。
    • 我们如何传递多个参数并在另一个屏幕上获取/使用设置参数?请建议。谢谢。
    • 这个答案来自github.com/brianegan/flutter_redux/issues/…。因不包括来源而被否决。
    • 在发送 firebase 推送通知并尝试在没有上下文的情况下从 main.dart 启动产品页面时,在 navigatorkey.currentstate 上为空。你有什么解决办法吗?
    • 一定要将navigatorkey添加到materialapp
    【解决方案2】:

    如果您想使用 globalKey 导航或显示没有上下文的对话框,尤其是使用 Bloc 或当您的逻辑与 UI 部分分离时,此解决方案是通用的。

    首先安装这个包:

    注意:我使用的是空安全版本

      get_it: ^7.2.0
    

    然后为您的服务定位器创建一个单独的文件:

    service_location.dart

        import 'package:get_it/get_it.dart';
        
        GetIt locator = GetIt.instance;
        
        class NavigationService {
          final GlobalKey<NavigatorState> navigatorKey =
              new GlobalKey<NavigatorState>();
          Future<dynamic> navigateTo(String routeName) {
            return navigatorKey.currentState!.pushNamed(routeName);
          }
        
          void setupLocator() {
            locator.registerLazySingleton(() => NavigationService());
          }
    
      void showMyDialog() {
        showDialog(
            context: navigatorKey.currentContext!,
            builder: (context) => Center(
                  child: Material(
                    color: Colors.transparent,
                    child: Text('Hello'),
                  ),
                ));
      }
        }
    

    ma​​in.dart 上:

    void main() {
      WidgetsFlutterBinding.ensureInitialized();
      NavigationService().setupLocator();
      runApp(MyApp());
    }
    // add navigatorKey for MaterialApp
    
     MaterialApp(
            navigatorKey: locator<NavigationService>().navigatorKey,
          ),
    

    在您的业务逻辑文件 bloc.dart 在 bloc 类中定义它,或者在你想在里面使用导航的任何类中定义它 然后开始在里面任意函数里面导航。

    class Cubit extends Cubit<CubitState> {
      final NavigationService _navigationService = locator<NavigationService>();
      void sampleFunction(){
           _navigationService.navigateTo('/home_screen'); // to navigate
           _navigationService.showMyDialog(); // to show dialog
    
        }
    }
    

    不是:我正在使用 generateRoute 进行路由。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 2017-11-06
      • 1970-01-01
      • 2013-05-18
      相关资源
      最近更新 更多