我对 Flutter Provider 模式有疑问。将用户重定向到新屏幕后,找不到提供程序。
根据我之前的问题(在此小部件上方找不到正确的提供者),我编写了以下代码:
class NewRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'Tap to select';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: NewRouteBody()
));
}
}
class NewRouteBody extends StatelessWidget {
@override
Widget build(BuildContext context) {
var user = Provider.of<UserRepository>(context);
return ListView(...)
我做了同样的事情,但我再次收到错误消息,指出它无法在此小部件 ( NewRouteBody
) 上方找到正确的提供程序。
试图以某种方式修复它,谷歌搜索了几个小时的答案,但没有成功......
任何帮助表示赞赏。
编辑
这是UserRepository
包含模式:
class UserRepository with ChangeNotifier {
User user;
Status _status = Status.Uninitialized;
Status get status => _status;
User get getUser => user;
...}
编辑2:
带有 ChangeNotifier 的代码片段:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.red,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<UserRepository>(
builder: (context) => UserRepository.instance(),
child: Consumer<UserRepository>(
builder: (context, UserRepository userRepository, _) {
switch (userRepository.status) {
case Status.Uninitialized:
return Login();
case Status.Unauthenticated:
return Login();
case Status.Authenticating:
case Status.Authenticated:
if(userRepository.getUser.isPrefSet == 0){
return Selection();
}
return Dashboard();
}
},
),
);
}
}