gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:40:39 24 4
gpt4 key购买 nike

我创建了一个服务文件夹并在其中创建了一个名为 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);
}
}

最佳答案

首先,创建一个类

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

}
}
在您的 main.dart 文件中。
 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");

关于flutter - 在没有上下文的情况下导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63324364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com