Flutter,如何将字体大小选项保存到共享首选项中?

Flutter, How to save font size options into sharedpreference?

请高手帮忙。几天来我一直在寻找解决我的问题的方法,但直到现在我还没有找到它。

我有一个文本小部件,在该小部件上方有一个下拉菜单 select 字体大小,20、30 和 40。

我的问题是:

  1. 如何将默认 字体大小设置为 20
  2. 如何将 selected 字体大小保存到 sharedpreferences

这是我的代码

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),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

非常感谢您的帮助

这是一项非常简单的任务。

首先,你应该有一个只调用一次的函数来添加默认字体大小:

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

其次,您想要另外两个函数来更新和检索字体大小:

检索函数:

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

更新函数:

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

最后,您想像这样更新 UI:

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),
                  ),
                ),
              ),
            ],
          ),
        ));
  }
}

我想提一下,如果您想在整个应用程序中使用字体大小,我强烈建议您使用 Provider 包来轻松访问应用程序周围的字体大小。

希望对您有所帮助!