FLUTH,如何将字体大小选项保存到共享首选项中? [英] Flutter, How to save font size options into sharedpreference?

查看:23
本文介绍了FLUTH,如何将字体大小选项保存到共享首选项中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮帮忙,师父。关于我的问题,我已经找了几天了,但到目前为止还没有找到。

我有一个文本小工具,该小工具上方有一个用于选择FontSize、20、30和40的下拉列表。

我的问题是:

  1. 如何将默认的FontSize设置为20
  2. 如何将所选字体大小保存到共享首选项

这是我的代码

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

我只想提一下,如果您要在您的应用程序中使用字体大小,我强烈建议您使用提供程序包,以便轻松访问您的应用程序周围的字体大小。

希望能有所帮助!

这篇关于FLUTH,如何将字体大小选项保存到共享首选项中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆