如何在没有上下文的情况下导航? [英] How to Navigate without context in flutter?

查看:84
本文介绍了如何在没有上下文的情况下导航?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I ended up with using a static function but I need to do navigation and It gave me an error that no getter was found for context so I looked for a solution and found the GET package but when I tried to use it It gave me another error :

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') {}
        });
      }

推荐答案

创建导航键

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

将其分配给MaterialApp

Assign it to MaterialApp

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

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

Then push your routes by navigatorKey below

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

navigatorKey.currentState.pushNamed(routeName);

这篇关于如何在没有上下文的情况下导航?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆