TL;DR - Getting providerInfo = null from Consumer<ProviderInfo>(
builder: (context, providerInfo, child),
我有一个使用scoped_model的Flutter应用程序,该应用程序运行正常,但我想对其进行重构,以便使用Provider
具有scoped_model的代码:
//imports...
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
final MainModel _model = MainModel();// The data class, extends scoped_model.Model class, with all of other models...
bool _isAuthenticated = false;
@override
void initState() {
_model.init();
super.initState();
}
@override
Widget build(BuildContext context) {
return ScopedModel<MainModel>(
model: _model,
child: MaterialApp(
title: "MyApp",
routes: {
'/': (BuildContext context) => _isAuthenticated == false ? AuthenticationPage() : HomePage(_model),
'/admin': (BuildContext context) =>
_isAuthenticated == false ? AuthenticationPage() : AdminPage(_model),
},
// the rest of build...
}
以及我尝试重构以使用提供程序的代码:
//@lib/main.dart
//imports...
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<ProviderInfo>(
builder: (context) {
ProviderInfo(); // the data model.
},
child: Consumer<ProviderInfo>(
builder: (context, providerInfo, child) => MaterialApp(
title: "MyApp",
routes: {
'/': (BuildContext context) {
providerInfo.isAuthenticated == false ? AuthenticationPage() : HomePage(providerInfo);
},
'/admin': (BuildContext context) {
providerInfo.isAuthenticated == false ? AuthenticationPage() : AdminPage(_model);
},
//the rest of build...
},
//@ProviderInfo
class ProviderInfo extends CombinedModel with ProductModel, UserModel, UtilityModel {
ProviderInfo() {
this.init();
}
}
此代码的问题是在Consumer<ProviderInfo>
的构建器函数中,providerInfo
为null(当然,在路由等之后也是如此)。
我做错了什么? 我该如何重构它才能正常工作?
答案 0 :(得分:0)
您忘了在提供者的builder
中退还一些东西。
更改
ProviderInfo()
收件人
return ProviderInfo()