flutter - 将列表转换为 Json 字符串,然后将此字符串转换回 Dart 中的列表

标签 flutter dart converters typeconverter

我想转换列表List<Word> myListString并将其放入sharedPreference,稍后我还想将该字符串(从sharedPreference)转换回List<Word> .

这是我的模型类 Word

class Word {
  int id;
  String word;
  String meaning;
  String fillInTheGapSentence;

  Word.empty();

  Word(int id, String word, String meaning, String fillInTheGapSentence){
    this.id = id;
    this.word = word;
    this.meaning = meaning;
    this.fillInTheGapSentence = fillInTheGapSentence;
  }
}

我可以转换List<Word> myList像这样的字符串

var myListString = myList.toString();

但无法制作List<Word> myListFromString来自myListString .

谢谢。

最佳答案

首先,myList.toString() 不是 JSON 格式,除非您重写 toString() 方法。您要做的就是手动将对象转换为字典,然后将其编码为 JSON 字符串。相反,您需要将字符串转换为字典,然后将其转换为对象。像这样的事情:

import 'dart:convert';

class Word {
  int id;
  String word;
  String meaning;
  String fillInTheGapSentence;

  Word.empty();

  Word(int id, String word, String meaning, String fillInTheGapSentence) {
    this.id = id;
    this.word = word;
    this.meaning = meaning;
    this.fillInTheGapSentence = fillInTheGapSentence;
  }

  Map<String, dynamic> toMap() {
    return {
      'id': this.id,
      'word': this.word,
      'meaning': this.meaning,
      'fillInTheGapSentence': this.fillInTheGapSentence,
    };
  }

  factory Word.fromMap(Map<String, dynamic> map) {
    return new Word(
      map['id'] as int,
      map['word'] as String,
      map['meaning'] as String,
      map['fillInTheGapSentence'] as String,
    );
  }
}

String convertToJson(List<Word> words) {
  List<Map<String, dynamic>> jsonData =
      words.map((word) => word.toMap()).toList();
  return jsonEncode(jsonData);
}

List<Word> fromJSon(String json) {
  List<Map<String, dynamic>> jsonData = jsonDecode(json);
  return jsonData.map((map) => Word.fromMap(map)).toList();
}

关于flutter - 将列表转换为 Json 字符串,然后将此字符串转换回 Dart 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143173/

相关文章:

flutter - 抖动图像转换

flutter - Flutter:列表滚动上的sliverAppBar调整大小问题

flutter - 如何限制 flutter Textfield 或 TextFormField 只接受英语?

Flutter 中特定设备的 Firebase 消息通知

c# - 具有依赖属性的转换器

android - Dart/Flutter - 调用/执行存储在属性的字符串变量中的方法

flutter - 'Future<Uint8List>'类型不是 'Widget'类型的子类型

firebase - 在 Flutter Firestore 中等待 Future<DocumentSnapshot> 的结果

java - 使用 Java 将 docx/ODT 转换为图像

html - CloudConvert html 到 docx 分页符