Smart HO
Smart HO

Reputation: 169

Flutter: Save ToggleButton selection in Shared preferences

I have ToggleButton with three selections to select a font, only one selection at a time can be accepted, which is working fine now. But My issue with shared preferences, I am not able to save and get the selection. it is a bit confusing as the outcome of the selection is a list of bools, e.g [true, false, false].

I need your help please to fix the shared preference code so that I can save and get the final selection.

this is my code for shared preferences:

  void initState() {
    super.initState();
    getisSelectedFont();
    isSelectedFont = [true, false, false];
  }

  saveisSelectedFont(bool value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      prefs.setBool("isSelectedFont", value);
    });
  }

  getisSelectedFont() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      isSelectedFont =
          (prefs.getBool('isSelectedFont') ?? [true, false, false]);
    });
  }

  List<bool> isSelectedFont;

and this the code for the ToggleButton:

                            child: ToggleButtons(
                              borderRadius: BorderRadius.circular(6),
                              children: <Widget>[
                                // first toggle button
                                Padding(
                                  padding: const EdgeInsets.only(
                                      right: 15, left: 15),
                                  child: Text(
                                    'font-1',
                                    style: TextStyle(fontSize: 15),
                                  ),
                                ),
                                // second toggle button
                                Padding(
                                  padding: const EdgeInsets.only(
                                      right: 15, left: 15),
                                  child: Text(
                                    'font-2',
                                    style: TextStyle(fontSize: 15),
                                  ),
                                ),
                                // third toggle button
                                Padding(
                                  padding: const EdgeInsets.only(
                                      right: 15, left: 15),
                                  child: Text(
                                    'font-3',
                                    style: TextStyle(fontSize: 15),
                                  ),
                                ),
                              ],
                              // logic for button selection below

                              onPressed: (int index) {
                                setState(() {
                                  for (int i = 0;
                                      i < isSelectedFont.length;
                                      i++) {
                                    isSelectedFont[i] = i == index;
                                  }
                                });

                                print(isSelectedFont);
                              },
                              isSelected: isSelectedFont,
                            ),

Upvotes: 0

Views: 1218

Answers (3)

Mohamed Anushath
Mohamed Anushath

Reputation: 131

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ToggleButtonTest extends StatefulWidget {
  @override
  _ToggleButtonTestState createState() => _ToggleButtonTestState();
}

class _ToggleButtonTestState extends State<ToggleButtonTest> {
  List<bool> isSelectedFont;
  int _currentFontFamily = 0;
  List<String> _fontFamily = [
    'SansitaSwashed',
    'DancingScript',
    'AmanticSC',
  ];
  void initState() {
    super.initState();
    getisSelectedFont();
    isSelectedFont = [true, false, false];
  }

  saveisSelectedFont() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      prefs.setStringList(
        "isSelectedFont",
        isSelectedFont.map((e) => e ? 'true' : 'false').toList(),
      );
      prefs.setInt('currentFontFamily', _currentFontFamily);
    });
  }

  getisSelectedFont() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      isSelectedFont = (prefs
              .getStringList('isSelectedFont')
              ?.map((e) => e == 'true' ? true : false)
              ?.toList() ??
          [true, false, false]);
      _currentFontFamily = prefs.getInt('currentFontFamily') ?? 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Toggle Button Test'),
      ),
      body: Column(
        children: [
          Container(
            margin: EdgeInsets.all(20),
            child: ToggleButtons(
              borderRadius: BorderRadius.circular(6),
              children: <Widget>[
                // first toggle button
                Padding(
                  padding: const EdgeInsets.only(right: 15, left: 15),
                  child: Text(
                    'font-1',
                    style: TextStyle(fontSize: 15),
                  ),
                ),
                // second toggle button
                Padding(
                  padding: const EdgeInsets.only(right: 15, left: 15),
                  child: Text(
                    'font-2',
                    style: TextStyle(fontSize: 15),
                  ),
                ),
                // third toggle button
                Padding(
                  padding: const EdgeInsets.only(right: 15, left: 15),
                  child: Text(
                    'font-3',
                    style: TextStyle(fontSize: 15),
                  ),
                ),
              ],
              // logic for button selection below
              onPressed: (int index) {
                setState(() {
                  for (int i = 0; i < isSelectedFont.length; i++) {
                    isSelectedFont[i] = i == index;
                  }
                  _currentFontFamily = index;
                  saveisSelectedFont();
                });
              },
              isSelected: isSelectedFont,
            ),
          ),
          Expanded(
            child: Center(
              child: Text(
                'This is the answer..',
                style: TextStyle(
                  fontSize: 30,
                  fontFamily: _fontFamily[_currentFontFamily],
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

Upvotes: 1

Mohamed Anushath
Mohamed Anushath

Reputation: 131

  saveisSelectedFont() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      prefs.setStringList(
        "isSelectedFont",
        isSelectedFont.map((e) => e ? 'true' : 'false').toList(),
      );
    });
  }

  getisSelectedFont() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      isSelectedFont = (prefs
              .getStringList('isSelectedFont')
              ?.map((e) => e == 'true' ? true : false)
              ?.toList() ??
          [true, false, false]);
    });
  }

  onPressed: (int index) {
    setState(() {
      for (int i = 0; i < isSelectedFont.length; i++) {
        isSelectedFont[i] = i == index;
      }
      saveisSelectedFont();
    });
    
  },

Upvotes: 0

M Alkhatib
M Alkhatib

Reputation: 727

change saveisSelectedFont , getisSelectedFont to this

  saveisSelectedFont() async {
   SharedPreferences prefs = await SharedPreferences.getInstance();
   setState(() {
     prefs.setStringList("isSelectedFont",
         isSelectedFont.map((e) => e ? 'true' : 'false').toList());
   });
}




  getisSelectedFont() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      isSelectedFont = (prefs?.getStringList('isSelectedFont')?.map((e) => e == 'true' ? true : false)?.toList() ?? [true, false, false]);
    });
  }

Upvotes: 1

Related Questions