在flutter中将数据作为对象存储在共享首选项中

jdgnovmf  于 2022-12-24  发布在  Flutter
关注(0)|答案(7)|浏览(178)

我想存储一个对象在共享的首选项,其中包含一些字段,如姓名,年龄,电话号码等,我不知道如何存储一个对象在共享的首选项在flutter。

dgsult0t

dgsult0t1#

您可以将对象存储在共享首选项中,如下所示:

SharedPreferences shared_User = await SharedPreferences.getInstance();
Map decode_options = jsonDecode(jsonString);
String user = jsonEncode(User.fromJson(decode_options));
shared_User.setString('user', user);
            
SharedPreferences shared_User = await SharedPreferences.getInstance();
Map userMap = jsonDecode(shared_User.getString('user'));
var user = User.fromJson(userMap);
        
class User {
  final String name;
  final String age;
        
  User({this.name, this.age});
        
  factory User.fromJson(Map<String, dynamic> parsedJson) {
    return new User(
      name: parsedJson['name'] ?? "",
      age: parsedJson['age'] ?? "");
  }
        
  Map<String, dynamic> toJson() {
    return {
      "name": this.name,
      "age": this.age
    };
  }
}
ac1kyiln

ac1kyiln2#

搜索了很多文章后,你在这里
要将数据保存到SharedPreferences示例,必须将对象转换为JSON:

SharedPreferences prefs = await SharedPreferences.getInstance();

 Map<String, dynamic> user = {'Username':'tom','Password':'pass@123'};

 bool result = await prefs.setString('user', jsonEncode(user));

要从SharedPreferences示例获取数据,对象必须从JSON转换:

String userPref = prefs.getString('user');
     
Map<String,dynamic> userMap = jsonDecode(userPref) as Map<String, dynamic>;
fcg9iug3

fcg9iug33#

将对象保存到共享首选项

SharedPreferences pref = await SharedPreferences.getInstance();
Map json = jsonDecode(jsonString);
String user = jsonEncode(UserModel.fromJson(json));
pref.setString('userData', user);

从共享首选项中获取对象

SharedPreferences pref = await SharedPreferences.getInstance();
Map json = jsonDecode(pref.getString('userData'));
var user = UserModel.fromJson(json);

您将需要导入下面提到的包

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

创建模型的最简单方法按照此答案-〉https://stackoverflow.com/a/58708634/9236994

zi8p0yeb

zi8p0yeb4#

保存前需要将其序列化为JSON,阅读后需要反序列化
详情请参见https://flutter.io/docs/development/data-and-backend/json

iqih9akk

iqih9akk5#

从API获取数据并将其保存到Shareperference时

Future<UserDetails> UserInfo({String sesscode, regno}) async{
await Future.delayed(Duration(seconds: 1));
SharedPreferences preferences = await SharedPreferences.getInstance();
 var map = new Map<String, String>();
map["sesscode"] = sesscode;
map["regno"] = regno;

 var response = await http.post(Base_URL().user_info, body: map);
 Map decodedata = json.decode(response.body);
 if(decodedata != null){
  String user = jsonEncode(UserDetails.fromJson(decodedata));
  preferences.setString(SharePrefName.infoPref, user);
  return UserDetails.fromJson(decodedata);
}
  return null;
 }

我创建了一个用于获取详细信息的函数*您可以在应用程序中的任何位置调用此函数 *

Future<UserDetails> getSavedInfo()async{
 SharedPreferences preferences = await SharedPreferences.getInstance();
 Map userMap = jsonDecode(preferences.getString(SharePrefName.infoPref));
  UserDetails user = UserDetails.fromJson(userMap);
  return user;
 }

现在,我在类中调用它以获取用户名

Future<UserDetails> usd = getSavedInfo();
       usd.then((value){
         print(value.surname);
       });
piwo6bdm

piwo6bdm6#

共享首选项处理程序

我创建了一个LocalStorageRepository类,它负责使用SharedPreferences处理本地数据。
该类是动态的,可以使用泛型和JSON解码和编码处理任何类型的数据(int、double、bool、String和Object)。
为了防止pron错误,我添加了LocalStorageKeys枚举来处理支持的键。

enum LocalStorageKeys { tutorialCompleted, user }

@singleton
class LocalStorageRepository {
  const LocalStorageRepository(SharedPreferences prefs) : _prefs = prefs;

  final SharedPreferences _prefs;

  bool keyExists(String key) => _prefs.containsKey(key);

  T? getValue<T>(
    LocalStorageKeys key, [
    T Function(Map<String, dynamic>)? fromJson,
  ]) {
    switch (T) {
      case int:
        return _prefs.getInt(key.name) as T?;
      case double:
        return _prefs.getDouble(key.name) as T?;
      case String:
        return _prefs.getString(key.name) as T?;
      case bool:
        return _prefs.getBool(key.name) as T?;
      default:
        assert(fromJson != null, 'fromJson must be provided for Object values');
        if (fromJson != null) {
          final stringObject = _prefs.getString(key.name);
          if (stringObject == null) return null;
          final jsonObject = jsonDecode(stringObject) as Map<String, dynamic>;
          return fromJson(jsonObject);
        }
    }
    return null;
  }

  void setValue<T>(LocalStorageKeys key, T value) {
    switch (T) {
      case int:
        _prefs.setInt(key.name, value as int);
        break;
      case double:
        _prefs.setDouble(key.name, value as double);
        break;
      case String:
        _prefs.setString(key.name, value as String);
        break;
      case bool:
        _prefs.setBool(key.name, value as bool);
        break;
      default:
        assert(
          value is Map<String, dynamic>,
          'value must be int, double, String, bool or Map<String, dynamic>',
        );
        final stringObject = jsonEncode(value);
        _prefs.setString(key.name, stringObject);
    }
  }
}

如果您想从LocalStorageRepository获取Object值,则需要提供其fromJson解码器。

final user = _localStorage.getValue(LocalStorageKeys.user, User.fromJson);

希望这个例子能对其他人有所帮助。
请随意编辑此问题并提出更改建议。

qxgroojn

qxgroojn7#

如果从API获取数据,则最初从API端点获取的是字符串,因此可以将数据存储为原始字符串,并且在需要时可以对其进行反序列化并在需要使用它的位置使用
https://gist.github.com/k1ycee/33bb7e51dac81093f949bbd30d7d0dc9
类似这样的东西,我觉得缺点是,如果JSON字符串数据太多,可能不建议存储所有的字符串,而是将其反序列化,并采取您认为必要的。

相关问题