如何在颤振中将 API 模型对象存储在本地存储中?

时间:2021-07-19 11:50:14

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

我在代码中使用 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);
    }
  }

1 个答案:

答案 0 :(得分:0)

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

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" />

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

这会起作用,但这不是将数据作为字符串存储在共享首选项中的最佳做法。 Shared Prefs 只负责管理像 bool 或 string 这样的小数据。对于您的用例,您可以使用 sqlite 作为本地数据库。您可以在其中根据条件获取数据。

让我知道它是否有效。

快乐编码。