Flutter 导航状态上下文

时间:2021-05-04 09:01:42

标签: flutter

我搜索了一种在通知中导航的方法,我必须找到使用小部件范围之外的上下文的解决方案,因此我创建了全局变量和导航器状态并使用了它,它工作正常。 现在我在想为什么我必须通过每个路由推送小部件的上下文,为什么不在每个路由推送上使用导航器状态。

import 'package:flutter/material.dart';

/// Global variables
/// * [GlobalKey<NavigatorState>]
class GlobalVariable {
  /// This global key is used in material app for navigation through firebase notifications.
  /// [navState] usage can be found in [notification_notifier.dart] file.
  static final GlobalKey<NavigatorState> navState = GlobalKey<NavigatorState>();
}

添加到 MaterialApp

MaterialApp(
        title: 'myapp',
        navigatorKey: GlobalVariable.navState,



Navigator.push(GlobalVariable.navState.currentContext, MaterialPageRoute(builder: (BuildContext context) => RoutePage(child: ContactForm())));

代替

(context) => Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) => RoutePage(child: ContactForm())));

0 个答案:

没有答案