【问题标题】:How to Store API model object in Local Storage in flutter?如何在 Flutter 中将 API 模型对象存储在本地存储中?
【发布时间】:2021-09-27 02:08:20
【问题描述】:

我在代码中使用 Local Storage(shared_preferences: ^2.0.6) 期间发现了这个问题....但是我无法将 api 模型对象存储在本地存储中...我该怎么办?

 storeModelInPrefs() async {
    http.Response response =
        await http.get(Uri.parse('http://18.191.193.64/api/view_categories'));
    
    String encodeData = jsonEncode(response.body);
    ///Write Data in local Storage 
    GetStorageUtility.prefs!.write('key', encodeData);
    ///Read Data from local Storage 
    String data = GetStorageUtility.prefs!.read('key');

    if (data == null) {
      print('no data in GetStorage');
    } else {
      Map<String, dynamic> map = jsonDecode(data);
      print(map);
    }
  }

【问题讨论】:

  • 你能展示一下 GetStorageUtility 类吗?

标签: flutter dart local-storage sharedpreferences flutter-test


【解决方案1】:

这是我根据您提供的代码创建的示例示例。

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_app/utilities.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    GetStorageUtility.init();
    super.initState();
    getRemoteData();
  }

  getRemoteData() async {
    /// This is where the api is fetching the data
    var response =
        await http.get(Uri.parse('http://18.191.193.64/api/view_categories'));

    /// This is where the string getting
    String encodeData = jsonEncode(response.body);
    GetStorageUtility.write("key", encodeData);

    /// this is where you fetch the data
    String data = GetStorageUtility.read("key");

    if (data == null) {
      print('no data in GetStorage');
    } else {
      Map<String, dynamic> jsonData = json.decode(data);
      jsonData.forEach((key, value) {
        print("$key :  $value\n");
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(" Page"),
      ),
    );
  }
}

SharadPrefs 单例,

import 'dart:async';

import 'package:shared_preferences/shared_preferences.dart';

class GetStorageUtility {
  static Future<SharedPreferences> get _instance async =>
      _prefsInstance ??= await SharedPreferences.getInstance();
  static SharedPreferences _prefsInstance;

  static Future<SharedPreferences> init() async {
    _prefsInstance = await _instance;
    return _prefsInstance;
  }

  static String read(String key, [String defValue]) {
    return _prefsInstance.getString(key) ?? defValue ?? "";
  }

  static Future<bool> write(String key, String value) async {
    var prefs = await _instance;
    return prefs?.setString(key, value) ?? Future.value(false);
  }
}

现在你已经看到你在你的 android 清单文件中添加了一些东西

<application android:usesCleartextTraffic="true" />

这个应该在那里,互联网权限应该在调试和主文件夹清单文件中。

这可行,但这不是将数据作为字符串存储在 sharedprefs 中的最佳做法。 Shared Prefs 只负责管理布尔或字符串等小数据。对于您的用例,您可以使用 sqlite 作为本地数据库。您可以在其中根据条件获取数据。

让我知道它是否有效。

快乐编码。

【讨论】:

  • 我收到此错误...未处理的异常:类型“字符串”不是类型“地图”的子类型 -------------- ---------------------------------------------- 来自以下代码: Map jsonData = json.decode(data); jsonData.forEach((key, value) { print("$key : $value\n"); });
  • 你能检查一下这个 print encodeData 并让我知道字符串中是否有 /。
  • 我收到了这个,"{\"status\":1,\"statuscode\":200,\"msg\":\"Displaying Category List\",\"category\": [{\"id\":1,\"name\":\"游乐园、游乐设施和拱廊\",\"created_at\":\....
  • 好的,我会告诉你的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
  • 2011-08-21
  • 2021-07-18
  • 2011-11-24
  • 2023-03-14
相关资源
最近更新 更多