gpt4 book ai didi

flutter - 如何在 Flutter 应用程序的 initState 期间使用来自 Provider 的数据

转载 作者:行者123 更新时间:2023-12-03 16:29:26 24 4
gpt4 key购买 nike

我通过添加 Provider 作为状态管理来重构我的 Flutter 应用程序代码。

期望的行为:当主屏幕打开时,应用程序应检查用户的电子邮件是否已验证,如果未验证,则应显示对话框弹出窗口。

问题:当我通过构造函数为 EmailVerified 传递数据时,它工作正常,但如果我想使用 Provider,我无法在 initState() 获取此数据。生命周期。

您能否为我推荐这种用例的正确方法?

import 'package:myapp/services/authentication.dart';
import 'package:myapp/screens/settings_screen.dart';
import 'package:flutter/material.dart';
import 'package:myapp/services/authentication.dart';
import 'package:provider/provider.dart';

class HomeScreen extends StatefulWidget {

@override
State<StatefulWidget> createState() => new _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
bool _isEmailVerified = false;

@override
void initState() {
super.initState();
_checkEmailVerification(); // <=== Method which should show Dialog box if email is not verified which is coming from "Auth" Provider
}

@override
Widget build(BuildContext context) {
final auth = Provider.of<Auth>(context, listen: false); // <==== Service from Provider, which contains data for _isEmailVerified
auth.isEmailVerified().then((value) => _isEmailVerified = value);

return new Scaffold(
appBar: new AppBar(
title: new Text('My App'),
),
body: Center(
child: Column(
children: <Widget>[
Text(
'Welcome to my app',
),
],
),
),
);
}

void _checkEmailVerification() async {
_isEmailVerified = auth.isEmailVerified(); // <=== How can I use "auth" from Provider to get isEmailVerified data ????
if (!_isEmailVerified) {
_showVerifyEmailDialog();
}
}

void _showVerifyEmailDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
// return object of type Dialog
return AlertDialog(
title: new Text("Verify your account"),
content: new Text("Please verify account in the link sent to email"),
actions: <Widget>[
new FlatButton(
child: new Text("Resend link"),
onPressed: () {
Navigator.of(context).pop();
_resentVerifyEmail();
},
),
new FlatButton(
child: new Text("Dismiss"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}

void _resentVerifyEmail() {
// Logic to send email
}
}

最佳答案

您需要使用上下文来调用 Provider.of()所以你可以添加 addPostFrameCallback()在第一次构建之后调用,在那里你可以使用上下文

@override
void initState() {
super.initState();

WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
auth = Provider.of<Auth>(context, listen: false);
});
}

关于flutter - 如何在 Flutter 应用程序的 initState 期间使用来自 Provider 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60343605/

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