本教程介绍如何在Flutter中使用shared-preferences存储小量数据。

可随意转载!

前言

一些小的用户数据,比如简单配置,在Android中存储在shared-preferences中。在iOS中用NSUserDefaults存储在plist文件中。本教程介绍如何在Flutter中使用此特性。

下文有些步骤不清楚的,请看Chapter01。一些细节不再重复。

创建项目

命令行执行以下命令:

flutter create -a java -i objc ability_shared_preferences

创建flutter项目,并且指定Android平台的编程语言为Java,iOS平台的编程语言为Objective-C。

配置项目

编辑flutter配置文件pubspec.yaml ,如下图:

点击Package get链接,执行命令, 获取到pub.dev上的官方插件包

编写代码main.dart

1. import依赖包

import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';

2. 定义类变量

  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  Future<int> _counter;

我们定义了私有变量_counter,依赖Android和iOS的本地小存储。我们期望它在关闭App后重新打开能够保存之前的计数值。

3. 定义stateful widget初始化函数

  @override
  void initState() {
    super.initState();
    _counter = _prefs.then((SharedPreferences prefs) {
      return (prefs.getInt('counter') ?? 0);
    });
  }

4. 定义操作shared-preferences函数

  Future<void> _incrementCounter() async {
    final SharedPreferences prefs = await _prefs;
    final int counter = (prefs.getInt('counter') ?? 0) + 1;

    setState(() {
      _counter = prefs.setInt("counter", counter).then((bool success) {
        return counter;
      });
    });
  }

5. 定义Flutter的UI函数

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("SharedPreferences Demo"),
      ),
      body: Center(
          child: FutureBuilder<int>(
              future: _counter,
              builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting:
                    return const CircularProgressIndicator();
                  default:
                    if (snapshot.hasError) {
                      return Text('Error: ${snapshot.error}');
                    } else {
                      return Text(
                        '持久化点击 ${snapshot.data} 次数${snapshot.data == 1 ? '' : 's'}.\n\n'
                        '你可以尝试结束App进程重新打开。',
                      );
                    }
                }
              })),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: '点击',
        child: const Icon(Icons.add),
      ),
    );
  }

真机调试

用数据线连接Android手机,点击右上角运行按钮。

Launching lib/main.dart on NX563J in debug mode...
Running Gradle task 'assembleDebug'...
✓ Built build/app/outputs/apk/debug/app-debug.apk.
Installing build/app/outputs/apk/app.apk...
D/FlutterActivity( 1257): Using the launch theme as normal theme.
D/FlutterActivityAndFragmentDelegate( 1257): Setting up FlutterEngine.
D/FlutterActivityAndFragmentDelegate( 1257): No preferred FlutterEngine was provided. Creating a new FlutterEngine for this FlutterFragment.
D/FlutterActivityAndFragmentDelegate( 1257): Attaching FlutterEngine to the Activity that owns this Fragment.
D/FlutterView( 1257): Attaching to a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@e39e46f
D/FlutterActivityAndFragmentDelegate( 1257): Executing Dart entrypoint: main, and sending initial route: /
Syncing files to device NX563J...

打开App,点击2次,结束App进程,再次打开。如下图:

机型适配问题

无,适配所有Android和iOS机型

示例源代码

源码地址