我试图实现Provider,看起来它工作正常,但是我得到了这个错误消息:
由于框架已经在构建小部件的过程中了,因此无法将此_DefaultInheritedProviderScope小部件标记为需要构建。仅当其祖先中的一个当前正在构建时,才能在构建阶段期间将小部件标记为需要构建。允许此异常是因为框架在构建子级之前会先构建父级小部件,这意味着脏后代将始终被构建。否则,在此构建阶段中,框架可能不会访问此小部件。调用setState()或markNeedsBuild()的小部件是:_DefaultInheritedProviderScope 值:'UserProfile'的实例 监听值 当发生违规调用时正在构建的小部件是:FutureBuilder dirty 状态:_FutureBuilderState#bf6ec 异常抛出时,这是堆栈:
0 Element.markNeedsBuild。(package:flutter/src/widgets/framework.dart:3896:11)
1 Element.markNeedsBuild(package:flutter/src/widgets/framework.dart:3911:6)
2 _InheritedProviderScopeMixin.markNeedsNotifyDependents(package:provider/src/inherited_provider.dart:268:5)
3 ChangeNotifier.notifyListeners(package:flutter/src/foundation/change_notifier.dart:206:21)
4 UserProfile.user=(package:mdd/core/services/user_info.dart:13:5)......UserProfile
发送通知的UserProfile实例。
我的代码如下:
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final authService = Provider.of<AuthService>(context);
final userProfile = Provider.of<UserProfile>(context);
return StatefulWrapper(
onInit: () {
FirebaseNotifications().setUpFirebase();
},
child: FutureBuilder<User>(
future: authService.getUser(),
builder: (context, AsyncSnapshot<User> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.error != null) {
return Text(snapshot.error.toString());
}
userProfile.user = snapshot.data;
// FirebaseUser user = snapshot.data;
return snapshot.hasData ? ListScreen() : LoginScreen();
} else {
return Scaffold(
appBar: AppBar(),
body: Container(),
);
}
},
)
);
}
}
以下是UserProfile类:
class UserProfile with ChangeNotifier {
User _user = User();
get user {
return _user;
}
set user(User user) {
this._user = user;
notifyListeners();
}
}
以及用于获取个人资料的AuthService部分:
Future<User> getUser() async {
print('GETTING THE USER');
final fbaseUser = await _auth.currentUser();
final snapshot = await _db.collection('users')
.document(fbaseUser.uid)
.get();
if (snapshot.data != null) {
Map<dynamic, dynamic> jsres = snapshot.data;
_user = User.fromJson(jsres);
return _user;
}
}
为什么会出现这个错误?我做错了什么?有谁能帮我解决一下吗?