本文介绍了Flutter:如何使用sharedPreferences设置交换机的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何读取sharedPreference并设置结果开关?

How do I read the sharedPreference and set the switch with the result?

我正在尝试开发可以检查的项目列表,并使用sharedPreferences保存每个开关的状态.

I am trying to deveop a list of items that can be checked off, and save the state of each switch using sharedPreferences.

我想我正在存储值,但是我无法获取代码来读取sharedPreference文件并设置开关

I think I am storing the values, but I cannot get the code to read the sharedPreference file and set the switch

我已经搜索过,但是我的问题很独特,我找不到解决方法.

I have searched but my problem is quite unique and I cannot find a solution.

class CheckList extends StatefulWidget {
  @override
  _CheckListState createState() => _CheckListState();
}
bool isSwitched = false;

class _CheckListState extends State<CheckList> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Card(
        margin: EdgeInsets.symmetric(vertical: 15.0, horizontal: 35.0),
        child: ListView(
              children: <Widget>[
                SizedBox(height: 20,),
                Text('Check List', style: TextStyle(fontSize: 25,     color: Colors.green), textAlign: TextAlign.center,),
                SizedBox(height: 10),
                CheckItem('Deposit Paid', 'Deposit'),
                SizedBox(height: 10),
                CheckItem('Balance Paid', 'Balance'),
                SizedBox(height: 10),
                CheckItem('Uploaded Team Name','Team'),
                SizedBox(height: 10),
                CheckItem('Uploaded Charity','Charity'),
                SizedBox(height: 10),
                CheckItem('Sent Copy of Leader Passport','Passport'),
                SizedBox(height: 10),
                CheckItem('Log book in Team Members name','LogBook'),
                SizedBox(height: 10),
                CheckItem('Rally Insurance Printed out','Insurance'),
                SizedBox(height: 10),
                CheckItem('MOT printed out', 'Mot'),
                SizedBox(height: 10),
                CheckItem('Fueled up and Ready to go', 'Ready'),
                SizedBox(height: 10),

              ],
            )
        ),
    );
  }
}



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

class CheckItem extends StatefulWidget {
  CheckItem(this.txt, this.checkKey);
  final String txt;
  final String checkKey;


  @override
  _CheckItemState createState() => _CheckItemState();
}

bool isSwitched = false;


class _CheckItemState extends State<CheckItem> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 25),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(
              child: Text(
            widget.txt,
            style: TextStyle(
              fontFamily: 'sans pro',
              color: Colors.white,
              letterSpacing: 2.0,
              fontWeight: FontWeight.bold,
              fontSize: 15.0,
            ),
          )),
          SizedBox(
            width: 20.0,
          ),
          Switch(
            value: isSwitched,
            onChanged: (value) {
              setState(() {
                isSwitched = value;

                putShared(widget.checkKey, value);
              });
        },
        activeTrackColor: Colors.lightGreenAccent,
        activeColor: Colors.green,
          ),
        ],
      ),
    );
  }
}

void putShared(String key, bool val) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setBool(key, val);
}

Future getShared(String key) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool val = prefs.getBool(key);
  return val;
}

该代码似乎可以正常工作,但是由于无法读取共享的首选项并设置开关,因此我不确定.

The code seems to work, however I cannot be sure as I am unable to read the shared preferences and set the switchs.

推荐答案

考虑您的代码.您每次使用setState时都需要加载记录的值,因此由于SharePreference是异步的,因此有必要将Switch的结构更改为Futurebuilder.并更改getShared()以返回默认值"false"(如果还没有sharePreferences的话).

Considering your code.You need to load the recorded value every time you use setState, so it was necessary to change the construction of Switch to Futurebuilder because of SharePreference to be async. And change getShared() to return a default value 'false' if there isn't sharePreferences yet.

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

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

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

class CheckList extends StatefulWidget {
  @override
  _CheckListState createState() => _CheckListState();
}

class _CheckListState extends State<CheckList> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Card(
          color: Colors.redAccent,
          margin: EdgeInsets.symmetric(vertical: 15.0, horizontal: 35.0),
          child: ListView(
            children: <Widget>[
              SizedBox(
                height: 20,
              ),
              Text(
                'Check List',
                style: TextStyle(fontSize: 25, color: Colors.green),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 10),
              CheckItem('Deposit Paid', 'Deposit'),
              SizedBox(height: 10),
              CheckItem('Balance Paid', 'Balance'),
              SizedBox(height: 10),
              CheckItem('Uploaded Team Name', 'Team'),
              SizedBox(height: 10),
              CheckItem('Uploaded Charity', 'Charity'),
              SizedBox(height: 10),
              CheckItem('Sent Copy of Leader Passport', 'Passport'),
              SizedBox(height: 10),
              CheckItem('Log book in Team Members name', 'LogBook'),
              SizedBox(height: 10),
              CheckItem('Rally Insurance Printed out', 'Insurance'),
              SizedBox(height: 10),
              CheckItem('MOT printed out', 'Mot'),
              SizedBox(height: 10),
              CheckItem('Fueled up and Ready to go', 'Ready'),
              SizedBox(height: 10),
            ],
          )),
    );
  }
}

class CheckItem extends StatefulWidget {
  CheckItem(this.txt, this.checkKey);
  final String txt;
  final String checkKey;

  @override
  _CheckItemState createState() => _CheckItemState();
}

class _CheckItemState extends State<CheckItem> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 25),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(
              child: Text(
            widget.txt,
            style: TextStyle(
              fontFamily: 'sans pro',
              color: Colors.white,
              letterSpacing: 2.0,
              fontWeight: FontWeight.bold,
              fontSize: 15.0,
            ),
          )),
          SizedBox(
            width: 20.0,
          ),

          ///////// CHANGES HERE
          FutureBuilder(
              future: getShared(widget.checkKey),
              initialData: false,
              builder: (context, snapshot) {
                return Switch(
                  value: snapshot.data,
                  onChanged: (value) {
                    setState(() {
                      putShared(widget.checkKey, value);
                    });
                  },
                  activeTrackColor: Colors.lightGreenAccent,
                  activeColor: Colors.green,
                );
              })
        ],
      ),
    );
  }
}

void putShared(String key, bool val) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setBool(key, val);
}

Future getShared(String key) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();

  ///////// CHANGES HERE
  bool val = prefs.getBool(key) == null ? false : (prefs.getBool(key));
  return val;
}

这篇关于Flutter:如何使用sharedPreferences设置交换机的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 13:36