乐趣区

关于flutter:Flutter学习第四课SharedPreferences本地存储的简单使用

一:第一步:Main.dart 界面

import 'package:flutter/material.dart';
import 'package:flutter_first/storage/storage_sp.dart';

void main() {runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "SharedPreferences 示例",
      theme: ThemeData(primarySwatch: Colors.blue),
      home: StorageSp(),);
  }
}

第二步:SharePrefences 数据存储界面

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

class StorageSp extends StatefulWidget {const StorageSp({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _StorageSpState();
}

class _StorageSpState extends State<StorageSp> {
  // 第一步:实例化本地存储对象
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  // 昵称及抉择语言的值 文本输出的控制器
  var controller = TextEditingController();

  // 定义变量 value_dart,value_js,value_java
  bool value_dart = false;
  bool value_js = false;
  bool value_java = false;

  @override
  void initState() {super.initState();
    initFromCache();}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("SharedPreferences 示例"),
      ),
      body: Container(padding: EdgeInsets.all(15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            TextField(
              controller: controller, // 一个自定义控制器,可实现相似 TextEditingController
              decoration: InputDecoration(
                  // 一个输入框
                  labelText: "昵称:",
                  hintText: "请输出名称"),
            ),
            Text("你喜爱的编程语言"),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[Text("Dart"),
                //Switch 示意开关组件  value 选中的值,onChanged 扭转时触发的事件
                Switch(
                    value: value_dart,
                    onChanged: (isChanged) {
                      // 设置状态扭转要存储的值
                      setState(() {this.value_dart = isChanged;});
                    })
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[Text("JavaScript"),
                Switch(
                    value: value_js,
                    onChanged: (isChanged){
                      // 设置状态扭转要存储的值
                      setState(() {this.value_js=isChanged;});
                    })

              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[Text("Java"),
                Switch(
                    value: value_java,
                    onChanged: (isChanged){
                      // 设置状态扭转要存储的值
                      setState(() {this.value_java=isChanged;});
                    })

              ],
            ),

            MaterialButton(child: Text("保留"),
                onPressed: (){saveInfo(controller.text);
                })


          ],
        ),
      ),
    );
  }

  // 从缓存中获取信息填充
  void initFromCache() async {
    // 获取 SharedPreferences 对象
    final SharedPreferences prefs = await _prefs;
    // 依据键(key)获取本地存储的值(value)final value_nickname = prefs.getString("key_nickname");
    final value_dart = prefs.getBool("key_dart");
    final value_js = prefs.getBool("key_js");
    final value_java = prefs.getBool("key_java");
    // 获取到缓存中的值后,应用 setState 更新界面信息
    setState(() {controller.text = (value_nickname == null ? "" : value_nickname);
      this.value_dart = (value_dart == null ? false : value_dart);
      this.value_js = (value_js == null ? false : value_js);
      this.value_java = (value_java == null ? false : value_java);
    });


  }
  // 保留界面的输出抉择信息
  void saveInfo(String value_nickname)  async{
    final SharedPreferences prefs=await _prefs;
    prefs.setString("key_nickname", value_nickname);
    prefs.setBool("key_dart", value_dart);
    prefs.setBool("key_js", value_js);
    prefs.setBool("key_java", value_java);


  }


}

在 Android 下的数据 data/data/ 包名 /shared_prefs

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="flutter.key_nickname">Rocky</string>
    <boolean name="flutter.key_js" value="true" />
    <boolean name="flutter.key_java" value="true" />
    <boolean name="flutter.key_dart" value="true" />
</map>
退出移动版