问题描述
我通过将Provider添加为状态管理来重构Flutter应用程序代码.
I am refactoring my Flutter application code by adding Provider as a state management.
所需的行为:打开主屏幕时,应用应检查用户是否已通过电子邮件验证,如果未通过验证,则应显示对话框弹出窗口.
Desired behavior: When Home screen opens, app should check if users email verified, if it's not then should show dialog popup.
问题:,当我通过构造函数传递EmailVerified数据时,它运行良好,但是如果我想使用Provider,则无法在 initState()处获得此数据代码>生命周期.
Problem: It worked fine when I was passing data for EmailVerified through the constructor, but if I want to use Provider, I can't get this data at initState()
lifecycle.
您能为我推荐这种用例的正确方法吗?
Can you please recommend me correct approach for such use case?
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()
在首次构建后即被调用,您可以在其中使用上下文
You need to use the context to call Provider.of()
so you can add addPostFrameCallback()
which is called after the first build, there you can use the context
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
auth = Provider.of<Auth>(context, listen: false);
});
}
这篇关于如何在Flutter应用程序的initState期间使用提供者的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!