Norbert
Norbert

Reputation: 7710

Flutter State management with Provider using multiple screens

I have Two pages, Page_A and Page_B in my app. I have two other classes which update a _votes variable(default = 0) in my Privider Class then display this variable in Page_A and this works fine as espected.

I am trying to access this variable (_votes) which is now updated to say 23 in a new page Page_B. But when ever the new page gets Pushes unto the screen, it seems the variable gets reset to 0 instead of 23. How can I achieve what am trying to do.

Upvotes: 3

Views: 2403

Answers (1)

Daniel
Daniel

Reputation: 486

Let say this is your provider class

class AppState with ChangeNotifier {
  int _votes = 0;

  getVotes() => _votes;

  setVotes(votes) {
    _votes = votes;
    notifyListeners();
 }}

//to access

appState = Provider.of<AppState>(context);

//to get the current value

appState.getVotes();

//to set the value

v = 23;
appState.setVotes(v);

make sure the root class should look like this:

void main() {
   runApp(new MyApp());}


 class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
       return ChangeNotifierProvider<AppState>(
         create: (_) => AppState(),
         child: MaterialApp(
           home: HomePage(),
           debugShowCheckedModeBanner: false));
      }
   }

Upvotes: 5

Related Questions