1

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

Ary Anzh
  • 406
  • 3
  • 15

1 Answers1

0

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!

dotmp3
  • 494
  • 4
  • 13
  • Thank you so much Sir, it's work.. :) can you tell me, what is the difference between sharedpreference and provider? – Ary Anzh Sep 22 '20 at 05:47
  • Shared preferences allows you to store data locally(on the device) in key value pairs whereas the Provider package is a state management solution. For example: Where it says MaterialApp() you would surround this with a MultiProvider and under the providers parameter do as follows "providers:[ FutureProvider.value(value:getFontSize())]" and now you are able to use "double _fontSize = Provider.of(context)" to access the font size anywhere in your app. Heres further information on provider with examples: [Provider Package](https://pub.dev/packages/provider) – dotmp3 Sep 22 '20 at 10:39
  • thank you very much for the explanation, sir. if in case I want to use the provider to change the font size globally, what code do I add? I was just learning to use Flutter. If you do not mind, I beg your help to modify my little codes above become provider. or if you don't have time to modify my code, please send me a link containing an example of using change fontsize using provider that can be set on drawer or etc. thank you before and after.. – Ary Anzh Sep 22 '20 at 18:10
  • I would highly recommend watching this video. [Flutter Provider](https://www.youtube.com/watch?v=vFxk_KJCqgk) It explains how you would use Provider package with Firebase but the same principles apply when you are using it with Font size. So instead of using a Streamprovider, you would use a FutureProvider where you would call the getFontSize function inside of. – dotmp3 Sep 22 '20 at 18:39
  • Thank you Sir, it is very help me :) – Ary Anzh Sep 22 '20 at 23:16