使用build方法使用changeNotifier提供商对象的最佳方法是什么?
我有一个 flutter 应用程序,并且不断收到错误,其中指出:
The following assertion was thrown while dispatching notifications for UserData:
setState() or markNeedsBuild() called during build.
UserData 是扩展 ChangeNotifier 的类,并且当我调用 notifyListeners()
方法时会引发此异常。
我的视图
class MyViewextends StatefulWidget {
@override
_MyViewState createState() => _MyViewState();
}
class _MyViewState extends State<MyView> {
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: UserService().getUser(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done)
{
var userData = Provider.of<UserData>(context, listen: false);
var user = (snapshot.data as ApiResponseModel)?.entity;
userData.set(user); //this is where the error gets thrown
}
return Container();
//shortened for question purposes. Ideally, I will be printing the User objects to the container.
//It containers String properties like firstName, lastName.
});
}
}
UserData
class UserData extends ChangeNotifier{
UserDto user;
void set(UserDto userDto){
user = userDto;
notifyListeners();
}
我想知道的是,有什么更好的方法可以初始化我的 UserDto 对象,这样就不会抛出此错误?
在我看来,if
块最有意义,但显然不是。
I have a flutter application and I keep getting the error which states:
The following assertion was thrown while dispatching notifications for UserData:
setState() or markNeedsBuild() called during build.
UserData is a class that extends ChangeNotifier and this exception is thrown when I call the notifyListeners()
method.
My View
class MyViewextends StatefulWidget {
@override
_MyViewState createState() => _MyViewState();
}
class _MyViewState extends State<MyView> {
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: UserService().getUser(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done)
{
var userData = Provider.of<UserData>(context, listen: false);
var user = (snapshot.data as ApiResponseModel)?.entity;
userData.set(user); //this is where the error gets thrown
}
return Container();
//shortened for question purposes. Ideally, I will be printing the User objects to the container.
//It containers String properties like firstName, lastName.
});
}
}
UserData
class UserData extends ChangeNotifier{
UserDto user;
void set(UserDto userDto){
user = userDto;
notifyListeners();
}
What I want to know is, what better way can I initialise my UserDto object so this error is not thrown?
In my head, that if
block made the most sense but apparently not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论