【问题标题】:Dart/ Flutter reading and writing list of lists - Why am I unable to access objects in my list of lists with an index number?Dart/Flutter 读写列表列表 - 为什么我无法使用索引号访问列表列表中的对象?
【发布时间】:2018-08-09 17:17:17
【问题描述】:

我是飞镖的新手,我正在做我的第一个项目。我目前正在研究项目的存储方面,在尝试访问以 .txt 格式编写的文件时遇到了困难。我正在尝试以 .txt 格式保存一个包含列表列表的文件。我使用 .writeAsString() 方法写入文件以将列表转换为字符串,以便可以将其保存为 .txt 文件。我使用以下代码读取文件并将其转换回列表列表。

    widget.storage.readData().then((String value) {
    setState(() {
    _state = value;
    final regExp = new RegExp(r'(?:\[)?(\[[^\]]*?\])(?:\])?');

    List<List<String>> result = regExp
        .allMatches(_state)
        .map((m) => m.group(1))
        .map((String item) => item.replaceAll(new RegExp(r'[\[\],]'), ''))
        .map((m) => [m])
        .toList();

    gamesList = result;       

当我打印 gamesList 的值时,我得到以下信息:

    [[75.00% 75.00% No shots 75.00% No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots 75.00% 75.00% No shots 75.00% No shots No shots No shots No shots No shots], [100.00% No shots 100.00% No shots No shots No shots 100.00% No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots No shots 100.00% No shots 100.00% No shots No shots No shots 100.00% No shots No shots]]

虽然此列表似乎包含我最初保存的相同值,但我无法使用索引号访问这些值中的任何一个。例如,我想说:

    print(gamesList[0][1]);

理论上这应该返回对象“75.00%”(参考上面打印语句的输出)。我注意到列表中缺少逗号,这可能就是我的代码无法按我希望的方式执行的原因。

【问题讨论】:

  • 这可能是您的正则表达式代码的问题,您有示例 txt 文件吗?您是否考虑过使用 json 序列化程序?这是一个防弹的选择......
  • 非常感谢!我使用了 JSON 序列化,效果很好。

标签: regex dart storage flutter nested-lists


【解决方案1】:

您应该使用序列化库将 Dart 对象(列表列表)转换为字符串,然后再将其转换回来。

达特森是一个选项:https://pub.dartlang.org/packages/dartson

例子:

import 'dart:io';
import 'package:dartson/dartson.dart';

void main() {

  List<String> l1 = new List<String>();
  l1.add("A");
  l1.add("B");

  List<String> l2 = new List<String>();
  l2.add("X");
  l2.add("Y");

  List<List<String>> ll = new List<List<String>>();
  ll.add(l1);
  ll.add(l2);

  var dson = new Dartson.JSON();

  String filename = 'lists.txt';
  new File(filename).writeAsStringSync(dson.encode(ll));

  String s = new File(filename).readAsStringSync();
  List<List<String>> deserializedLists = dson.decode(s, new List<List<String>>(), true);

}

【讨论】:

  • 非常感谢!使用序列化完美无缺。
  • dartson 一年未更新,“pub”评分较低。还有其他可以使用,例如 Dart 团队维护的 json_serializable。
猜你喜欢
  • 1970-01-01
  • 2020-04-21
  • 2021-05-24
  • 2012-02-18
  • 2017-06-19
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
相关资源
最近更新 更多