flutter 插件shared_preferences


封装iOS上的NSUserDefaults和Android上的SharedPreferences,为简单数据提供持久存储。数据以异步方式持久保存到磁盘。这两个平台都不能保证在返回后写入将持久保存到磁盘,并且此插件不能用于存储关键数据。

添加依赖

dependencies:
  shared_preferences: ^0.5.1+1

安装

flutter packages get

导入

import 'package:shared_preferences/shared_preferences.dart';

实例

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

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
      child: RaisedButton(
        onPressed: _incrementCounter,
        child: Text('Increment Counter'),
        ),
      ),
    ),
  ));
}

_incrementCounter() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  int counter = (prefs.getInt('counter') ?? 0) + 1;
  print('Pressed $counter times.');
  await prefs.setInt('counter', counter);
}

测试

const MethodChannel('plugins.flutter.io/shared_preferences')
  .setMockMethodCallHandler((MethodCall methodCall) async {
    if (methodCall.method == 'getAll') {
      return <String, dynamic>{}; // set initial values here if desired
    }
    return null;
  });