Flutter 无上下文的颤振导航

Flutter 无上下文的颤振导航,flutter,dart,Flutter,Dart,我创建了一个服务文件夹,并在其中创建了一个名为request的文件。dart,这里我打算将我发出的所有请求放入一个名为AuthService的类中,使用下面的登录请求,我希望能够在响应后导航到主屏幕。statusCode==200或201,但我无法做到这一点,因为导航需要上下文,而我的类既不是有状态的小部件,也不是无状态的小部件,有没有什么方法可以在没有上下文的情况下导航 import 'dart:convert'; import 'package:http/http.dart' as http

我创建了一个服务文件夹,并在其中创建了一个名为request的文件。dart,这里我打算将我发出的所有请求放入一个名为AuthService的类中,使用下面的登录请求,我希望能够在响应后导航到主屏幕。statusCode==200或201,但我无法做到这一点,因为导航需要上下文,而我的类既不是有状态的小部件,也不是无状态的小部件,有没有什么方法可以在没有上下文的情况下导航

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';

class AuthService {

  login(email, password) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    if (email == "" && password == "") {
      return;
    }

    try {
      Map data = {'email': email, 'password': password};

      var jsonResponse;
      var response = await http
          .post('https://imyLink.com/authenticate', body: data);
      if (response.statusCode == 200 || response.statusCode == 201) {

//I want to navigate to my home screen once the request made is successful

        jsonResponse = json.decode(response.body);
        if (jsonResponse != null) {
          await sharedPreferences.setString("userToken", jsonResponse["token"]);
          var token = sharedPreferences.getString("userToken");
          print('Token: $token');
          print(jsonResponse);
          print("Login successful");
        }
      } else {
        print(response.statusCode);
        print('Login Unsuccessful');
        print(response.body);
      }
    } catch (e) {
      print(e);
    }
}
选择1

如果您将在
有状态
无状态
小部件中调用
登录
方法。您可以将
context
作为参数传递给
AuthService
类的
login
方法

我以您的代码为例添加了一个演示:

class AuthService {

  // pass context as a parameter
  login(email, password, context) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    if (email == "" && password == "") {
      return;
    }

    try {
      Map data = {'email': email, 'password': password};

      var jsonResponse;
      var response = await http
          .post('https://imyLink.com/authenticate', body: data);
      if (response.statusCode == 200 || response.statusCode == 201) {

      //I want to navigate to my home screen once the request made is successful
      Navigator.of(context).push(YOUR_ROUTE); // new line

        jsonResponse = json.decode(response.body);
        if (jsonResponse != null) {
          await sharedPreferences.setString("userToken", jsonResponse["token"]);
          var token = sharedPreferences.getString("userToken");
          print('Token: $token');
          print(jsonResponse);
          print("Login successful");
        }
      } else {
        print(response.statusCode);
        print('Login Unsuccessful');
        print(response.body);
      }
    } catch (e) {
      print(e);
    }
}
选择2

通过设置MaterialApp的navigatorKey属性,您可以在无上下文的情况下访问应用程序的导航器:

  /// A key to use when building the [Navigator].
  ///
  /// If a [navigatorKey] is specified, the [Navigator] can be directly
  /// manipulated without first obtaining it from a [BuildContext] via
  /// [Navigator.of]: from the [navigatorKey], use the [GlobalKey.currentState]
  /// getter.
  ///
  /// If this is changed, a new [Navigator] will be created, losing all the
  /// application state in the process; in that case, the [navigatorObservers]
  /// must also be changed, since the previous observers will be attached to the
  /// previous navigator.
  final GlobalKey<NavigatorState> navigatorKey;
new MaterialApp(
      title: 'MyApp',
      navigatorKey: key,
    );
推送路由(命名路由和非命名路由均有效):


通过以下github问题找到关于选项2的更多详细信息:

您可以使用flatter
Get

.

首先,创建一个类

import 'package:flutter/material.dart';

class NavigationService{
  GlobalKey<NavigatorState> navigationKey;

  static NavigationService instance = NavigationService();

   NavigationService(){
     navigationKey = GlobalKey<NavigatorState>();
   }

  Future<dynamic> navigateToReplacement(String _rn){
return navigationKey.currentState.pushReplacementNamed(_rn);
  }
 Future<dynamic> navigateTo(String _rn){
   return navigationKey.currentState.pushNamed(_rn);
  }
 Future<dynamic> navigateToRoute(MaterialPageRoute _rn){
   return navigationKey.currentState.push(_rn);
  }

 goback(){
   return navigationKey.currentState.pop();

  }
  }
然后您可以从项目中的任何位置调用该函数,如

 NavigationService.instance.navigateToReplacement("home");
 NavigationService.instance.navigateTo("home");

您可以使用此插件跳过所需的上下文


快乐的飘动:)这台
发电机是从哪里来的?@PeakGen,你是说?“仅当
onGenerateRoute
不为空时才生成导航器;如果为空,
navigatorKey
也必须为空。”谢谢,这非常有帮助
import 'package:flutter/material.dart';

class NavigationService{
  GlobalKey<NavigatorState> navigationKey;

  static NavigationService instance = NavigationService();

   NavigationService(){
     navigationKey = GlobalKey<NavigatorState>();
   }

  Future<dynamic> navigateToReplacement(String _rn){
return navigationKey.currentState.pushReplacementNamed(_rn);
  }
 Future<dynamic> navigateTo(String _rn){
   return navigationKey.currentState.pushNamed(_rn);
  }
 Future<dynamic> navigateToRoute(MaterialPageRoute _rn){
   return navigationKey.currentState.push(_rn);
  }

 goback(){
   return navigationKey.currentState.pop();

  }
  }
 MaterialApp(
  navigatorKey: NavigationService.instance.navigationKey,
  initialRoute: "login",
  routes: {
    "login":(BuildContext context) =>Login(),
    "register":(BuildContext context) =>Register(),
    "home":(BuildContext context) => Home(),

  },
);
 NavigationService.instance.navigateToReplacement("home");
 NavigationService.instance.navigateTo("home");
// go to second page using named route
OneContext().pushNamed('/second');
// go to second page using MaterialPageRoute
OneContext().push(MaterialPageRoute(builder: (_) => SecondPage()));
// go back from second page
OneContext().pop();