title: Flutter: Shared Preferences, Change Notifier
body: <p>This is the code of the count up app with change notifier and shared preferences.
  I want it to save the counter in the model and show the last counter when it is opened, but it does not work.
  When it is opened, it shows 0. Once I tap the add button, it shows the last counter plus 1.
  Please tell me why it does not work and how can I fix it.</p>
  <pre><code>import 'package:flutter/material.dart';
  import 'package:provider/provider.dart';
  import 'package:shared_preferences/shared_preferences.dart';
  
  void main() {
    runApp(
      ChangeNotifierProvider&lt;MyHomePageModel&gt;(
        create: (_) =&gt; MyHomePageModel(),
        child: MyApp(),
      )
    );
  }
  
  class MyApp extends StatelessWidget {
    // This widget is the root of your application.
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: MyHomePage(),
      );
    }
  }
  
  class MyHomePage extends StatelessWidget {
  
    @override
    Widget build(BuildContext context) {
      return Consumer&lt;MyHomePageModel&gt;(builder: (context, model, child) {
        int _counter = model.getCounter();
        return Scaffold(
            appBar: AppBar(
              title: Text('FlutteR Demo Home Page'),
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: &lt;Widget&gt;[
                  Text(
                    'You have pushed the button this many times:',
                  ),
                  Text(
                    '$_counter',
                    style: Theme.of(context).textTheme.headline4,
                  ),
                ],
              ),
            ),
            floatingActionButton: Button());
      });
    }
  }
  
  class Button extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      final model = Provider.of&lt;MyHomePageModel&gt;(context, listen: false);
      return FloatingActionButton(
        onPressed: () =&gt; model.addCounter(),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      );
    }
  }
  
  class MyHomePageModel extends ChangeNotifier {
    int _counter = 0;
  
    void _setPrefItems() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setInt('counter', _counter);
    }
  
    void _getPrefItems() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      _counter = prefs.getInt('counter') ?? 0;
    }
  
    void addCounter() {
      _counter++;
      _setPrefItems();
      notifyListeners();
    }
  
    int getCounter() {
      _getPrefItems();
      return _counter;
    }
  }
  </code></pre>