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...
}
以及我尝试重构以使用Provider的代码:
//@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
为空(也当然后,在路线等)。
我做错了什么?我该如何重构它才能正常工作?
您忘记退还builder
您提供者的。
更改
ProviderInfo()
至
return ProviderInfo()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句