Reputation: 43
I am using MultiProvider in the main like the following:
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => ReadPreferences(),
),
ChangeNotifierProvider(
create: (context) => ItemsCrud(),
),
],
child: MaterialApp(
initialRoute: initialPage,
routes: {
InitialScreen.screenId: (context) => InitialScreen(),
HomeScreen.screenId: (context) => HomeScreen(),
AddItemScreen.screenId: (context) => AddItemScreen(),
},
),
);
}
But my problem is that it never read what inside ReadPreferences() class file at all, Although it reads the ItemsCrud() one normally.
My ReadPreferences() like the follwoing:
import 'package:flutter/foundation.dart'; //To use the "ChangeNotifier"
import 'package:shared_preferences/shared_preferences.dart'; //local store
class ReadPreferences extends ChangeNotifier {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
//Constructor method
ReadPreferences() {
print('Please print this');
getPreferences();
}
void getPreferences() async {
final SharedPreferences prefs = await _prefs;
print('print anything plz');
}
}
It won't print anything at all, what am I doing wrong??
Upvotes: 2
Views: 376
Reputation: 28
Is ReadPreferences being used in any of your child widgets(Screens)? You need to use it in your child widgets, otherwise the constructor won't be called. Used like this:
//your child widget build method
@override
Widget build(BuildContext context) {
ReadPreferences _dummyProvider = Provider.of<ReadPreferences>(context);
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
.....
}
Upvotes: 1
Reputation: 5595
I just tested this and created a test button like so that it creates an instance and fires the method in the onPressed:
FlatButton(
child: Text('Provider Test'),
onPressed: () {
final readProvider =
Provider.of<ReadPreferences>(context, listen: false);
readProvider.getPreferences();
},
),
At first attempt I got an error :
MissingPluginException (MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences))
Then I ran flutter clean
then flutter pub get
then cold restarted the app, and it works fine.
I see both print statements when I press the button.
Upvotes: 0