gpt4 book ai didi

flutter - 如何在 flutter 中使用提供者功能后导航到另一个页面?

转载 作者:行者123 更新时间:2023-12-05 04:31:10 27 4
gpt4 key购买 nike

我在我的登录提供商中创建了一个函数来验证我的应用程序的 OTP,如下所示。

Future<bool> verifyOtp(String otp) async {
final _loginData = await SharedPreferences.getInstance();

_isLoading = true;
notifyListeners();
_status = await AuthApi.verifyOtp(otp);
_isLoading = false;
_name = _loginData.getString('name');
notifyListeners();
return _status;
}

现在每当我尝试在我的代码中使用它时,如下所示,

final bool status = await Provider.of<LoginProvider>(context, listen: false).verifyOtp(verificationCode);

// ignore: avoid_print
print("STATUS ==== " + status.toString());
if (status) {
Navigator.of(context).pushReplacementNamed('/discover');
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("Incorrect OTP!!!")));
}

它给了我一个异常(exception),如下所示 -

Exception has occurred.
FlutterError (This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.)

任何人都请指导我,从提供商导航的实际方式是什么。我是 Provider 的新手。非常感谢:)

----- 完整的提供者代码在下面 -----

class LoginProvider with ChangeNotifier {
bool _status = false;
bool _isLoading = false;
bool _isOtpScreen = false;
String? _name;

bool get isLoading => _isLoading;
bool get isOtpScreen => _isOtpScreen;
String? get name => _name;

void sendOtp(String phone) async {
_isLoading = true;
notifyListeners();
_status = await AuthApi.sendOtp(phone);
_isLoading = false;
_isOtpScreen = true;
notifyListeners();
}

Future<bool> verifyOtp(String otp) async {
final _loginData = await SharedPreferences.getInstance();

_isLoading = true;
notifyListeners();
_status = await AuthApi.verifyOtp(otp);
_isLoading = false;
_name = _loginData.getString('name');
notifyListeners();
return _status;
}
}

最佳答案

使用您可以从任何地方访问的 GlobalKey 进行导航

创建 key

final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}

将其传递给您的应用:

new MaterialApp(
title: 'MyApp',
onGenerateRoute: generateRoute,
navigatorKey: navigatorKey,
);

在您的 route 使用:

    print("STATUS ==== " + status.toString());
if (status) {
Navigator.of(navigatorKey.currentContext).pushReplacementNamed('/discover');
} else {
ScaffoldMessenger.of(navigatorKey.currentContext).showSnackBar(const SnackBar(content:
Text("Incorrect OTP!!!")));
}

关于flutter - 如何在 flutter 中使用提供者功能后导航到另一个页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71882587/

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