Cache two Lists in flutter

后端 未结 1 1574
傲寒
傲寒 2021-01-15 17:26

I want to cache two lists that got from Firebase to use to later when the user is offline

This is the full code for my list display screen -

import          


        
1条回答
  •  情书的邮戳
    2021-01-15 18:17

    I didn't get complete requirement by your question description but you can use shared_preferences library to store the data list as following
    Add following line pubspec.yaml

    dependencies:
      flutter:
        sdk: flutter
      shared_preferences:
    

    You can use this example and add more utility methods as per you requirement.

    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    
    void main() async {
      AppConfig.init(() {
        runApp(MyApp());
      });
    }
    
    class CustomModel {
      int id;
      String name;
    
      CustomModel({this.id, this.name});
    
      factory CustomModel.fromJson(Map json) {
        return CustomModel(id: json["id"], name: json["name"]);
      }
    
      Map toJson() => {"id": id, "name": name};
    
      @override
      String toString() {
        return "id: $id, name: $name";
      }
    }
    
    class AppConfig {
      static Future init(VoidCallback callback) async {
        WidgetsFlutterBinding.ensureInitialized();
        await SharedPreferenceUtils.init();
        callback();
      }
    }
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class SharedPreferenceUtils {
      static SharedPreferences prefs;
    
      static init() async {
        prefs = await SharedPreferences.getInstance();
        // storing lists
        await putStringList("m_list", ["abc", "def"]);
        await putObjectList("data",
            [CustomModel(id: 1, name: "Bob"), CustomModel(id: 2, name: "Alice")]);
      }
    
      static Future putStringList(String key, List list) async {
        return prefs.setStringList(key, list);
      }
    
      static List getStringList(String key) {
        return prefs.getStringList(key);
      }
    
      static Future putObjectList(String key, List list) async {
        if (prefs == null) return null;
        List _dataList = list?.map((value) {
          return json.encode(value);
        })?.toList();
        return prefs.setStringList(key, _dataList);
      }
    
      static List getObjList(String key, T f(Map v),
          {List defValue = const []}) {
        if (prefs == null) return null;
        List dataList = getObjectList(key);
        List list = dataList?.map((value) {
          return f(value);
        })?.toList();
        return list ?? defValue;
      }
    
      static List getObjectList(String key) {
        if (prefs == null) return null;
        List dataList = prefs.getStringList(key);
        return dataList?.map((value) {
          Map _dataMap = json.decode(value);
          return _dataMap;
        })?.toList();
      }
    }
    
    class _MyAppState extends State {
      @override
      void initState() {
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(SharedPreferenceUtils.getStringList("m_list").toString()),
                  Text(SharedPreferenceUtils.getObjList(
                      "data", (v) => CustomModel.fromJson(v)).toString()),
                ],
              ),
            ),
          ),
        );
      }
    }
    
    
    
    

    You don't need to store the lists in init() as it's done for this example. You can also pass data from one widget to others in multiple ways and if you are looking for state management then you can use BLOC or providers.

    0 讨论(0)
    提交回复
    热议问题