Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save bool value using shared preferences

So I created a categories section in my app where you can select multiple categories by clicking on the container. The container you select changes colour. What I want to do is save the choices selected using shared preferences and display it again whenever user wants to see his selected categories.

return GestureDetector(
  onTap: () {
    setState(() {
      if (isSelected == false) {
        isSelected = !isSelected;
        color = widget.color;
        print('Coming here');
      } else {
        isSelected = false;
        color = Colors.white;
      }
      prefs.setBool(_key, isSelected);
    });
  },
  child: AnimatedContainer(
    padding: EdgeInsets.all(widget.padding),
    decoration: BoxDecoration(
      color: color,
      shape: BoxShape.circle,
    ),
    duration: Duration(milliseconds: 500),
    child: Container(
      child: Text(
        widget.labelText,
        style: TextStyle(
            color: kLightBlue,
            fontFamily: 'clanproBold',
            fontSize: SizeConfig.blockSizeHorizontal * 3),
      ),
    ),
  ),
);

This is the code to create multiple containers. How can I save the options?

like image 235
sheen404 Avatar asked Aug 31 '25 17:08

sheen404


1 Answers

First of all, you have to add the dependency of shared preferences at your pubspec.yaml file as follows:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: "<newest version>"

After that you have to import to your class the package:

import 'package:shared_preferences/shared_preferences.dart';

Then at the state, you want to save the options add the following code:

_saveOptions() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setBool('option', true);
}

You can read the data you saved at SharedPreferences using the following code:

  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool boolValue = prefs.getBool('option');

Important: You can only save int, String, double or bool variables using SharedPreferences.

So if you want to save the options the user gives, you can use only the types above. You can make it work by passing the values of the options as String or int to SharedPrefrences and convert them back again.

Example:

Color color = new Color(0x#BD452C);
int colorValue = color.value;
String colorString = color.toString();
Color newColor = new Color(colorValue);
like image 184
John Arnok Avatar answered Sep 02 '25 06:09

John Arnok