Search code examples
fluttersharedpreferences

trying Shared-preferences with bool


It’s the first time I’m using Shared-preferences but I can’t switch between true and false when I click on the icon and save the value when I leave the program, does anyone know what’s wrong?

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Shared preferences demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Shared preferences demo'),
    );
  }
}
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  bool select = true;
  @override
  void initState() {
    super.initState();
    _loadCounter();
  }
  _loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('select', true);
  }
  _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    //Return bool
    bool boolValue = prefs.getBool('select');
    return boolValue;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title),),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '$select',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          child: Icon(Icons.add),
      ),);}}

Solution

  • Modify _incrementCounter method to get bool value which is Future vaue which gets from the shared preference

    class _MyHomePageState extends State<MyHomePage> {
      bool select;
    
      @override
      void initState() {
        super.initState();
        setInitialValue();
      }
    
      setInitialValue() async {
        final value = await _incrementCounter();
        setState(() {
          select = value?? true;
        });
      }
    
      _loadCounter(bool value) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setBool('select', value);
      }
    
      Future<bool> _incrementCounter() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        //Return bool
        bool boolValue = prefs.getBool('select');
        return boolValue;
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  '$select',
                  style: Theme.of(context).textTheme.headline4,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () async {
              _loadCounter(!select);
              final value = await _incrementCounter();
              setState(() {
                select = value;
              });
            },
            child: Icon(Icons.add),
          ),
        );
      }
    }