您的问题描述并未完全满足您的要求,但您可以使用
shared_preferences库来存储数据列表,如下所示:
添加以下行pubspec.yaml
dependencies: flutter: sdk: flutter shared_preferences:
您可以使用此示例,并根据需要添加更多实用程序方法。
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<String, dynamic> json) { return CustomModel(id: json["id"], name: json["name"]); } Map<String, dynamic> 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<bool> putStringList(String key, List<String> list) async { return prefs.setStringList(key, list); } static List<String> getStringList(String key) { return prefs.getStringList(key); } static Future<bool> putObjectList(String key, List<Object> list) async { if (prefs == null) return null; List<String> _dataList = list?.map((value) { return json.enpre(value); })?.toList(); return prefs.setStringList(key, _dataList); } static List<T> getObjList<T>(String key, T f(Map v), {List<T> defValue = const []}) { if (prefs == null) return null; List<Map> dataList = getObjectList(key); List<T> list = dataList?.map((value) { return f(value); })?.toList(); return list ?? defValue; } static List<Map> getObjectList(String key) { if (prefs == null) return null; List<String> dataList = prefs.getStringList(key); return dataList?.map((value) { Map _dataMap = json.depre(value); return _dataMap; })?.toList(); }}class _MyAppState extends State<MyApp> { @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: <Widget>[ Text(SharedPreferenceUtils.getStringList("m_list").toString()), Text(SharedPreferenceUtils.getObjList<CustomModel>( "data", (v) => CustomModel.fromJson(v)).toString()), ], ), ), ), ); }}在
init()此示例中,您无需将列表存储在其中。您还可以通过多种方式将数据从一个窗口小部件传递给其他窗口小部件,如果您正在寻找状态管理,则可以使用BLOC或提供程序。



