在使用Dio的时候,发现不容易获取context。如果每次传个context参数有时候会不方便。所以查找资料找到了如何实现获取公共context。
首先在创建一个如下class
import 'package:flutter/material.dart';
/// 用于提供全局的 navigatorContext
class NavigatorProvider {
static GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();
}
然后在应用的MaterialApp下注册此navigatorKey。此对应应用启动main
方法调用的启动App的Class。如下图LoginAppApplication()就是对应的下面的class LoginAppApplication
注册之后使用方法,跳转路由的话先获取navigatorState,然后通过navigatorState设置路由进行跳转。否则直接传递Navigator传递context跳转无效。
NavigatorState? navigatorState = NavigatorProvider.navigatorKey.currentState;
if (navigatorState != null) {
navigatorState.pushAndRemoveUntil(MaterialPageRoute(builder: (context) => LoginApp()), (route) => route == false);
}