如何使用共享首选项保存布尔值

时间:2020-07-03 17:28:33

标签: flutter sharedpreferences

因此,我在应用程序中创建了一个类别部分,您可以通过单击容器来选择多个类别。您选择的容器会更改颜色。我要做的是保存使用共享首选项选择的选项,并在用户希望查看其所选类别时再次显示。

return GestureDetector(
  onTap: () {
    setState(() {
      if (isSelected == false) {
        isSelected = !isSelected;
        color = widget.color;
        print('Coming here');
      } else {
        isSelected = false;
        color = Colors.white;
      }
      prefs.setBool(_key, isSelected);
    });
  },
  child: AnimatedContainer(
    padding: EdgeInsets.all(widget.padding),
    decoration: BoxDecoration(
      color: color,
      shape: BoxShape.circle,
    ),
    duration: Duration(milliseconds: 500),
    child: Container(
      child: Text(
        widget.labelText,
        style: TextStyle(
            color: kLightBlue,
            fontFamily: 'clanproBold',
            fontSize: SizeConfig.blockSizeHorizontal * 3),
      ),
    ),
  ),
);

这是创建多个容器的代码。 如何保存选项?

2 个答案:

答案 0 :(得分:2)

首先,必须在shared preferences文件中添加pubspec.yaml的依存关系,如下所示:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: "<newest version>"

此后,您必须将包导入到您的班级:

import 'package:shared_preferences/shared_preferences.dart';

然后在该状态下,要保存选项,请添加以下代码:

_saveOptions() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setBool('option', true);
}

您可以使用以下代码读取在SharedPreferences中保存的数据:

  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool boolValue = prefs.getBool('option');

重要:您只能保存 int 字符串 double bool 使用SharedPreferences的变量。

因此,如果要保存用户提供的选项,则只能使用上面的类型。 您可以通过将选项的值作为 String int 传递给SharedPrefrences并再次将它们转换回去来使其工作。

示例:

Color color = new Color(0x#BD452C);
int colorValue = color.value;
String colorString = color.toString();
Color newColor = new Color(colorValue);

答案 1 :(得分:0)

仅检查该示例,我创建了一个示例,该示例将告诉您如何保存共享的首选项值,然后重新获取它。

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



void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Users'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isSelected = false;
  String stringValue = "No value";

  @override
  void initState() {
    super.initState();
    getAllSavedData();
    // You can use the initState where you can get all the saved categories and the assign it based on it.

    
  }

  getAllSavedData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    bool value = prefs.getBool("youKey");

    // For first time you get null data so no value 
    // is assigned so it will not assign anything
    if (value != null) stringValue = value.toString();

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: <Widget>[
            GestureDetector(
              onTap: () async {
                if (isSelected == false) {
                  isSelected = !isSelected;
                  //color = Colors.pink;
                  print('Coming here');
                } else {
                  isSelected = false;
                  // color = Colors.white;
                }

                SharedPreferences prefs = await SharedPreferences.getInstance();
                prefs.setBool("youKey", isSelected);

                // This is where you save the data and then when the user second time opens  he will get the stoared data
                setState(() {});
              },
              child: AnimatedContainer(
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Colors.red,
                  shape: BoxShape.circle,
                ),
                duration: Duration(milliseconds: 500),
                child: Container(
                  child: Text(
                    'S',
                    style: TextStyle(
                        color: Colors.blue,
                        fontFamily: 'clanproBold',
                        fontSize: 20),
                  ),
                ),
              ),
            ),
            // This is when you open the screen for second time you get the value as true
            Text('This is the value you saved $stringValue'),
          ],
        ),
      ),
    );
  }
}

让我知道它是否有效。