fluttersharedpreferencesdropdowntext-widget

Flutter, How to save font size options into sharedpreference?


Please help, master. I've been a few days looking for the solution about my problem, but until now I have not found it.

I have a text widget, above the widget there is a dropdown to select the fontsize, 20, 30 and 40.

My question is:

  1. How do I set the default fontsize to 20?
  2. How do I save the selected fontsize into sharedpreferences?

This is my code

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

void main() {
  runApp(MaterialApp(
    home: MyTextApp(),
  ));
}

class MyTextApp extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<MyTextApp> {
  SharedPreferences prefs;

  List<double> _fontSizeList = [20, 30, 40];
  double _changeFontSize;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My Text Widget'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Card(
              margin: EdgeInsets.only(bottom: 3),
              child: ListTile(
                title: Text("Font Size"),
                trailing: DropdownButtonHideUnderline(
                  child: DropdownButton(
                    isExpanded: false,
                    value: _changeFontSize,
                    items: _fontSizeList.map((myFontSize) {
                      return DropdownMenuItem(
                        child: Text(myFontSize.toString()),
                        value: myFontSize,
                      );
                    }).toList(),
                    onChanged: (value) {
                      setState(() {
                        _changeFontSize = value;
                      });
                    },
                    hint: Text("Select FontSize"),
                  ),
                ),
              ),
            ),
            Center(
              child: Padding(
                padding: const EdgeInsets.all(20),
                child: Text(
                  'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
                  style: TextStyle(fontSize: _changeFontSize),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

I am very grateful for the help


Solution

  • This is quite a simple task.

    Firstly, you should have a function which is only called once to add the default fontsize:

    void addDefaultValueToSharedPreferences() async {
      final sharedPreferences = await SharedPreferences.getInstance();
      await sharedPreferences.setInt('fontsize', 20.0);
    }
    

    Secondly, you want to have another two functions which allow you to update and retrieve the fontsize:

    Retrieving function:

      Future<double> getFontSize() async {
        final sharedPreferences = await SharedPreferences.getInstance();
        return sharedPreferences.getDouble('fontsize');
      }
    

    Updating function:

      Future<void> updateFontSize(double updatedSize) async {
        final sharedPreferences = await SharedPreferences.getInstance();
        return await sharedPreferences.setDouble('fontsize', updatedSize);
      }
    

    Lastly, you want to update your UI like so:

    void main() async {
      runApp(MaterialApp(
        home: MyApp(),
      ));
    }
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      double _changeFontSize;
      List<double> _fontSizeList = [20.0, 30.0, 40.0];
    
      @override
      void initState() {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          //Retrieving font size
          getFontSize().then((value) => setState(() {
                _changeFontSize = value;
           }));
        });
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.blue,
              centerTitle: true,
              title: Text('Dropdown app'),
            ),
            body: SingleChildScrollView(
              child: Column(
                children: [
                  Card(
                    margin: EdgeInsets.only(bottom: 3),
                    child: ListTile(
                      title: Text("Font Size"),
                      trailing: DropdownButtonHideUnderline(
                        child: DropdownButton(
                          isExpanded: false,
                          value: _changeFontSize,
                          items: _fontSizeList.map((myFontSize) {
                            return DropdownMenuItem(
                              child: Text(myFontSize.toString()),
                              value: myFontSize,
                            );
                          }).toList(),
                          onChanged: (value) async {
                            setState(() {
                              _changeFontSize = value;
                            });
                            //Updating font size
                            await updateFontSize(value);
                          },
                          hint: Text("Select FontSize"),
                        ),
                      ),
                    ),
                  ),
                  Center(
                    child: Padding(
                      padding: const EdgeInsets.all(20),
                      child: Text(
                        'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
                        style: TextStyle(fontSize: _changeFontSize),
                      ),
                    ),
                  ),
                ],
              ),
            ));
      }
    }
    

    I would just like to mention if you want to use the font size through out your app I would highly suggest using the Provider package to allow easy access to the font size around your app.

    Hope that helps!