Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 如何将字体大小选项保存到SharedReference中?_Flutter_Sharedpreferences_Dropdown_Text Widget - Fatal编程技术网

Flutter 如何将字体大小选项保存到SharedReference中?

Flutter 如何将字体大小选项保存到SharedReference中?,flutter,sharedpreferences,dropdown,text-widget,Flutter,Sharedpreferences,Dropdown,Text Widget,请帮帮我,主人。我几天来一直在寻找解决我问题的办法,但直到现在我还没有找到 我有一个文本小部件,在小部件的上方有一个下拉列表来选择fontsize,20、30和40 我的问题是: 如何将默认的字体大小设置为20 如何将所选fontsize保存到SharedReferences 这是我的代码 import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; vo

请帮帮我,主人。我几天来一直在寻找解决我问题的办法,但直到现在我还没有找到

我有一个文本小部件,在小部件的上方有一个下拉列表来选择fontsize,20、30和40

我的问题是:

  • 如何将默认的字体大小设置为20
  • 如何将所选fontsize保存到SharedReferences
  • 这是我的代码

    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),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }
    
    导入“包装:颤振/材料.省道”;
    导入“package:shared_preferences/shared_preferences.dart”;
    void main(){
    runApp(材料应用程序)(
    主页:MyTextApp(),
    ));
    }
    类MyTextApp扩展StatefulWidget{
    @凌驾
    _State createState()=>_State();
    }
    类_状态扩展状态{
    共享引用优先权;
    列表_fontSizeList=[20,30,40];
    双倍尺寸;
    @凌驾
    小部件构建(构建上下文){
    返回脚手架(
    appBar:appBar(
    标题:文本(“我的文本小部件”),
    ),
    正文:SingleChildScrollView(
    子:列(
    儿童:[
    卡片(
    页边距:仅限边集(底部:3),
    孩子:ListTile(
    标题:文本(“字体大小”),
    尾部:DropdownButtonHideUnderline(
    孩子:下拉按钮(
    isExpanded:错,
    值:_changeFontSize,
    项目:_fontSizeList.map((myFontSize){
    返回下拉菜单项(
    子项:文本(myFontSize.toString()),
    值:myFontSize,
    );
    }).toList(),
    一旦更改:(值){
    设置状态(){
    _changeFontSize=值;
    });
    },
    提示:文本(“选择字体大小”),
    ),
    ),
    ),
    ),
    居中(
    孩子:填充(
    填充:常数边集。全部(20),
    子:文本(
    “Lorem ipsum dolor sit amet,是一位杰出的献身者,他是一名临时雇员,从事劳动和工作。他是一名临时雇员,他是一名普通雇员。”,
    样式:文本样式(字体大小:_changeFontSize),
    ),
    ),
    ),
    ],
    ),
    ),
    );
    }
    }
    

    非常感谢您的帮助

    这是一项非常简单的任务

    首先,您应该有一个只调用一次的函数来添加默认fontsize:

    void addDefaultValueToSharedPreferences() async {
      final sharedPreferences = await SharedPreferences.getInstance();
      await sharedPreferences.setInt('fontsize', 20.0);
    }
    
    其次,您需要另外两个函数,用于更新和检索fontsize:

    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);
      }
    
    Future getFontSize()异步{
    final SharedReferences=等待SharedReferences.getInstance();
    返回SharedReferences.getDouble('fontsize');
    }
    
    更新功能:

      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);
      }
    
    Future updateFontSize(双updatedSize)异步{
    final SharedReferences=等待SharedReferences.getInstance();
    返回wait wait 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),
                      ),
                    ),
                  ),
                ],
              ),
            ));
      }
    }
    
    void main()异步{
    runApp(材料应用程序)(
    主页:MyApp(),
    ));
    }
    类MyApp扩展了StatefulWidget{
    @凌驾
    _MyAppState createState()=>\u MyAppState();
    }
    类MyAppState扩展了状态{
    双倍尺寸;
    列表_fontSizeList=[20.0,30.0,40.0];
    @凌驾
    void initState(){
    WidgetsBinding.instance.addPostFrameCallback((){
    //检索字体大小
    getFontSize()。然后((值)=>setState(){
    _changeFontSize=值;
    }));
    });
    super.initState();
    }
    @凌驾
    小部件构建(构建上下文){
    返回脚手架(
    appBar:appBar(
    背景颜色:Colors.blue,
    标题:对,
    标题:文本(“下拉应用程序”),
    ),
    正文:SingleChildScrollView(
    子:列(
    儿童:[
    卡片(
    页边距:仅限边集(底部:3),
    孩子:ListTile(
    标题:文本(“字体大小”),
    尾部:DropdownButtonHideUnderline(
    孩子:下拉按钮(
    isExpanded:错,
    值:_changeFontSize,
    项目:_fontSizeList.map((myFontSize){
    返回下拉菜单项(
    子项:文本(myFontSize.toString()),
    值:myFontSize,
    );
    }).toList(),
    onChanged:(值)异步{
    设置状态(){
    _changeFontSize=值;
    });
    //更新字体大小
    等待updateFontSize(值);
    },
    提示:文本(“选择字体大小”),
    ),
    ),
    ),
    ),
    居中(
    孩子:填充(
    填充:常数边集。全部(20),
    子:文本(
    “Lorem ipsum dolor sit amet,是一位杰出的献身者,他是一名临时雇员,从事劳动和工作。他是一名临时雇员,他是一名普通雇员。”,
    样式:文本样式(字体大小:_changeFontSize),
    ),
    ),
    ),
    ],
    ),
    ));
    }
    }
    
    我只想提一下,如果你想在整个应用程序中使用字体大小,我强烈建议使用提供商软件包,以便轻松访问应用程序周围的字体大小

    希望有帮助

    这是q