我正在通过添加Provider作为状态管理来重构我的Flutter 应用程序代码.
Desired behavior:当主屏幕打开时,应用程序应该判断用户的邮箱是否经过验证,如果没有验证,则应该显示对话框弹出窗口.
Problem:当我通过构造函数为EmailVerify传递数据时,它工作得很好,但是如果我想使用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
}
}