在没有上下文的情况下导航

Zaz*_*des 5 dart flutter

我创建了一个服务文件夹并在其中创建了一个名为 request.txt 的文件。dart,在这里我打算将我提出的所有请求放入一个名为 AuthService 的类中,下面的登录请求我希望能够在 response.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);
    }
}
Run Code Online (Sandbox Code Playgroud)

S.R*_*hav 15

首先,创建一个类

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();

  }
  }
Run Code Online (Sandbox Code Playgroud)

在您的 main.dart 文件中。

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

  },
);
Run Code Online (Sandbox Code Playgroud)

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

 NavigationService.instance.navigateToReplacement("home");
 NavigationService.instance.navigateTo("home");
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这非常有帮助 (2认同)

voi*_*oid 5

选项1

如果您将login在 aStatefulStateless小部件中调用该方法。您可以将context参数作为参数传递给类的login方法AuthService

我使用您的代码添加了一个演示作为示例:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

选项 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;
Run Code Online (Sandbox Code Playgroud)

创建密钥:

final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();
Run Code Online (Sandbox Code Playgroud)

将其传递给 MaterialApp:

new MaterialApp(
      title: 'MyApp',
      navigatorKey: key,
    );
Run Code Online (Sandbox Code Playgroud)

推送路由(命名和非命名路由都有效):

navigatorKey.currentState.pushNamed('/someRoute');
Run Code Online (Sandbox Code Playgroud)

按照以下 github 问题查找有关选项 2 的更多详细信息:https : //github.com/brianegan/flutter_redux/issues/5#issuecomment-361215074