Reputation: 35
TL;DR - Getting providerInfo = null from Consumer<ProviderInfo>(
builder: (context, providerInfo, child),
I have a flutter app that uses scoped_model that works just fine but I want to refactor it so it'll use Provider
The code with 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...
}
and the code that I tried to refactor to use 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();
}
}
The problem with this code is that in the builder function of Consumer<ProviderInfo>
the providerInfo
is null (and also after of course, in routes etc...).
what did I do wrong? how can I refactor it so it'll works fine?
Upvotes: 1
Views: 1166
Reputation: 276911
You forgot to return something in the builder
of your provider.
Change
ProviderInfo()
To
return ProviderInfo()
Upvotes: 1