如何保存 List<List<Object>> 列表到 Shared Preferences Flutter

How to save List<List<Object>> list to Shared Preferences Flutter

我有这个列表:

List<List<GraphInfo>> list = [
  [
    GraphInfo(title: 'Graph 1', xAxis: "10", yAxis: "15"),
    GraphInfo(title: 'Graph 1', xAxis: "15", yAxis: "20"),
  ],
  [
    GraphInfo(title: 'Graph 2', xAxis: "20", yAxis: "20"),
    GraphInfo(title: 'Graph 2', xAxis: "25", yAxis: "25"),
  ],
];

我需要在我的应用程序中显示一个图表(它必须是列表中的列表)。

而且我需要找到一种在本地保存列表的方法。

我曾尝试使用 Sqlite、Hive 和共享首选项,但没有成功,因为很难用自定义对象持久化列表。

图形信息 class:

class GraphInfo {
  int? id;
  String title;
  String xAxis;
  String yAxis;

  GraphInfo({
    this.id,
    required this.title,
    required this.xAxis,
    required this.yAxis,
  });

  factory GraphInfo.fromJson(Map<String, dynamic> json) {
    return GraphInfo(
        id: json["id"],
        title: json["title"],
        xAxis: json["xAxis"],
        yAxis: json["yAxis"]);
  }

  factory GraphInfo.fromMap(Map<String, dynamic> map) => GraphInfo(
        id: map["id"]?.toInt() ?? 0,
        title: map["title"] ?? '',
        xAxis: map["xAxis"] ?? '',
        yAxis: map["yAxis"] ?? '',
      );
  Map<String, dynamic> toJson() {
    return {
      "id": id,
      "title": title,
      "xAxis": xAxis,
      "yAxis": yAxis,
    };
  }

  @override
  String toString() => '{name: $title, x: $xAxis, y: $yAxis}';
}

有没有人有保存此列表的想法? (它们可以包括 Sqlite、Hive 和共享首选项)。

请随时咨询。 谢谢!

我认为您拥有serialize/deserialize您的数据所需的一切。

序列化

Future<void> addToSP(List<List<GraphInfo>> tList) async {
  final prefs = await SharedPreferences.getInstance();
  prefs.setString('graphLists', jsonEncode(tList));
}

反序列化

void getSP() async {
  final prefs = await SharedPreferences.getInstance();
  final List<dynamic> jsonData =
      jsonDecode(prefs.getString('graphLists') ?? '[]');
  list = jsonData.map<List<GraphInfo>>((jsonList) {
    return jsonList.map<GraphInfo>((jsonItem) {
      return GraphInfo.fromJson(jsonItem);
    }).toList();
  }).toList();
  setState(() {});
}

完整代码示例

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

void main() {
  runApp(const MyApp());
}

// PRESENTATION LAYER

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData.dark().copyWith(
        textTheme: const TextTheme(
          bodyText2: TextStyle(fontSize: 40.0),
        ),
      ),
      home: const Scaffold(
        body: HomePage(),
      ),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<List<GraphInfo>> list = [];

  @override
  void initState() {
    addToSP(defaultList).then((_) => getSP());
    super.initState();
  }

  Future<void> addToSP(List<List<GraphInfo>> tList) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString('graphLists', jsonEncode(tList));
  }

  void getSP() async {
    final prefs = await SharedPreferences.getInstance();
    final List<dynamic> jsonData =
        jsonDecode(prefs.getString('graphLists') ?? '[]');
    list = jsonData.map<List<GraphInfo>>((jsonList) {
      return jsonList.map<GraphInfo>((jsonItem) {
        return GraphInfo.fromJson(jsonItem);
      }).toList();
    }).toList();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return list.isNotEmpty
        ? Center(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: list.map((subList) {
                return subList.isNotEmpty
                    ? Column(
                        mainAxisSize: MainAxisSize.min,
                        children: subList.map((x) => Text(x.title)).toList(),
                      )
                    : const Text('Empty subList');
              }).toList(),
            ),
          )
        : const Text('NOTHING');
  }
}

// MODEL

class GraphInfo {
  int? id;
  String title;
  String xAxis;
  String yAxis;

  GraphInfo({
    this.id,
    required this.title,
    required this.xAxis,
    required this.yAxis,
  });

  factory GraphInfo.fromJson(Map<String, dynamic> json) {
    return GraphInfo(
        id: json["id"],
        title: json["title"],
        xAxis: json["xAxis"],
        yAxis: json["yAxis"]);
  }

  Map<String, dynamic> toJson() {
    return {
      "id": id,
      "title": title,
      "xAxis": xAxis,
      "yAxis": yAxis,
    };
  }

  @override
  String toString() => '{name: $title, x: $xAxis, y: $yAxis}';
}

// DATA

final List<List<GraphInfo>> defaultList = [
  [
    GraphInfo(title: 'Graph 1', xAxis: "10", yAxis: "15"),
    GraphInfo(title: 'Graph 1', xAxis: "15", yAxis: "20"),
  ],
  [
    GraphInfo(title: 'Graph 2', xAxis: "20", yAxis: "20"),
    GraphInfo(title: 'Graph 2', xAxis: "25", yAxis: "25"),
  ],
];