【问题标题】:How to access "main" Navigator (of MaterialApp) after it's created?创建后如何访问(MaterialApp的)“主”导航器?
【发布时间】:2021-01-26 14:09:46
【问题描述】:

我有以下代码:

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

class MyApp extends StatelessWidget {

  final GlobalKey<NavigatorState> _navigatorKey = new GlobalKey<NavigatorState>();

  _mustBeCalledWhenNavigatorIsReady() {
    FirebaseAuth.instance
      .authStateChanges()
      .listen((User user) {
        if (user == null) {
          // the problem is that this happens before navigator is created and _navigatorKey.currentState == null
          // I need to call _mustBeCalledWhenNavigatorIsReady when the navigator instance is already created
          _navigatorKey.currentState.pushReplacementNamed('auth/login');
        } else {
          _navigatorKey.currentState.pushReplacementNamed('/');
        }
      });
  }

  MyApp() {
    _mustBeCalledWhenNavigatorIsReady();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'MyApp',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      // navigatorObservers: [],
      navigatorKey: _navigatorKey,
      onGenerateRoute: router.getRouteGenerator(), // uses router from package fluro internally - so its just a route generator
      initialRoute: 'auth/login',
    );
  }
}

我需要在代码 cmets 中描述的是在创建路由器后初始化一些侦听器并且只执行一次。但是我只能在路由小部件中访问路由器。有什么简单的方法可以知道 MaterialApp 的“主”导航器何时创建?

【问题讨论】:

  • 检查MaterialApp.builder
  • 已检查 - 导航器尚未在“builder” func 中创建
  • 奇怪:在传递给它的构建器“child”参数中实际上是“Navigator-[LabeledGlobalKey#252cd”,但 _navigatorKey.currentState 仍然为 null...
  • 因为 Navigator 已创建但未附加到小部件树 - 例如,这使您有机会分配自定义 Navigator - 您需要等待下一帧 State要有效 - 简单的 Future(() {stuff to execute}) 会做到这一点
  • 或者您可以使用SchedulerBinding.scheduleFrameCallbackSchedulerBinding mixin 中的任何其他类似方法

标签: flutter


【解决方案1】:
MaterialApp(
 //....
 initialRoute: initialRoutes(),
 //....
)

string initialRoutes() {

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

  FirebaseAuth.instance
   .authStateChanges()
   .listen((User user) {
   if (user == null) {
     // the problem is that this happens before navigator is created and 
     // _navigatorKey.currentState == null
     // I need to call _mustBeCalledWhenNavigatorIsReady when the navigator 
     // instance 
     // is already created
     return 'auth/login';
   } else {
     return '/';
   }
  });
 }
}

【讨论】:

    猜你喜欢
    • 2020-02-07
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 2021-06-20
    • 2018-04-28
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多