gpt4 book ai didi

flutter - 在构建期间更新值时使用 Flutter Provider 时出现问题

转载 作者:行者123 更新时间:2023-12-04 14:15:17 28 4
gpt4 key购买 nike

我正在尝试在检查用户是否已登录后更新我在提供商中的 uid。当我这样做时,即使应用程序没有崩溃,也会在构建小部件时引发错误。这是代码:

class HandleAuth extends StatelessWidget {
@override
Widget build(BuildContext context) {
var user = Provider.of<FirebaseUser>(context);
if (user != null) {
print('user.uid is ${user.uid}');
final loggedUserInfo = Provider.of<LoggedUserInfo>(context, listen: false);
loggedUserInfo.updateUserInfo(user.uid);
print('first scan screen user: ${loggedUserInfo.userUid}');

}
return (user == null)
? WelcomeNewUserScreen()
: ServicesAroundMe();
}
}

这是提供者:

class LoggedUserInfo with ChangeNotifier {
String _uid;

String get userUid {
return _uid;
}

void updateUserInfo(String updatedUid) {
_uid = updatedUid;
print('updated uid is $_uid');
notifyListeners();
}

}

它抛出这个错误:

This ListenableProvider widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase. The widget on which setState() or markNeedsBuild() was called was: ListenableProvider

最佳答案

您必须记住,每次调用 updateUserInfo 方法时,都会触发 notifyListeners() 以尝试重建脏部件。 Provider.of<T>(context)没有参数 listen: false也做同样的事情。因此调用了导致错误的 2 个重建触发器。

与提供者合作时,建议使用流。

为了使您的代码更具可扩展性,请为您的用户创建一个自定义类,并使用 ChangeNotifier 或提供程序和流。

例如;

class User {
final String uid;
final String displayName;
User({ @required this.uid, this.displayName });
}

class Auth {

User _firebaseUserMapper( FirebaseUser user) {
if(user == null){
return null;
}
return User(uid: user.uid, displayName: user.displayName);
}

Stream<User> get onAuthStateChange {
return Firebase.instance.onAuthStateChanged.map(_firebaseUserMapper);
}


}

在您的页面屏幕中,您可以像下面这样使用

class HandleAuth extends StatelessWidget {
@override
Widget build(BuildContext context) {
final auth = Provider.of<Auth>(context, listen: false);
return StreamBuilder<User>(
stream: auth.onAuthStateChanged,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if( snapshot.connectionState == ConnectionState.active) {
User user = snapshot.data;
if (user == null ){
return WelcomeNewUserScreen();
}
return Provider<User>.value(
value: user,
child: ServicesAroundMe(),
);
}
return Scaffold(
body: Center(
child: CircularProgressIndicator();
),
);
}
);
}

流将永远监听 currentUser/newUser 并导航到适当的页面。

关于flutter - 在构建期间更新值时使用 Flutter Provider 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60820387/

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