flutter-实现本地存储(sharePreference)

1.导包

pubspec.yaml中dependencies节点下

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  shared_preferences: ^0.5.3+4

2.封装

import 'package:shared_preferences/shared_preferences.dart';

class SaveUtil {
  //读取数据
  static Future getSavedByKey(String keyName) async {
    print('进入到读取数据');
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String data = await sharedPreferences.getString(keyName);
    print('进入到读取数据-返回数据');
    return data;
  }

//保存数据
  static Future saveBydate(String keyName, String value) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    bool isOk = await sharedPreferences.setString(keyName, value);
    return isOk;
  }
}

3.使用

  //调用保存
    Future hadInsert=  SaveUtil.saveBydate("isFirset", 'value');
    hadInsert.then((onValue){
      print("存储成功");
      //调用读取
      Future data=SaveUtil.getSavedByKey('isFirset');
      data.then((String data){
        print("获取是否是第一次使用"+data);
      }).catchError((onError){
        print("获取是否是第一次使用===异常"+onError.toString());
      });
    }).catchError((onError){
      //存储异常
      print('存储失败'+onError.toString());
    });

 

你可能感兴趣的:(Flutter)