Dart| Flutter:将`List<String>`转换成字符串的例子

2,815 阅读1分钟

本教程展示了创建一个不可变的列表的多种方法。

有时,你需要将List<String> ,转换成一个单一的字符串。

如何在Dart中把列表转换为字符串?

我们有多种方法可以做到

  • 使用join()方法

List 有一个 方法,返回带有可选的分隔符的字符串。默认的可选参数为空。join

它遍历每个元素并调用元素.toString()将结果附加上分隔符。

List.join(optionalSeparator)

下面是一个程序。

void main() {
  List<String> words = ["one", "two", "three"];
  print(words);
  print(words.join());
  print(words.join(" "));
  print(words.join("-"));
}

输出:

[one, two, three]
onetwothree
one two three
one-two-three
  • 使用reduce()方法

列表中有reduce()函数,它将列表中的元素减少为一个元素。

迭代列表中的元素并应用一个函数,函数append字符串,返回字符串。

String reduce(String Function(String, String) combine)

下面是一个例子

void main() {
  List<String> words = ["one", "two", "three"];
  print(words);
  String result = words.reduce((value, element) => value + '-' + element);
  print(result);
}

输出:

[one, two, three]
one-two-three
  • 使用for index循环

这是另一个使用for index循环迭代元素的列表,附加到一个已经声明的变量上,最后将该变量打印到控制台。

下面是一个例子

void main() {
  List<String> words = ["one", "two", "three"];
  print(words);
  var result = "";
  for (int i = 0; i < words.length; i++) {
    result = result + words[i].toString();
  }
  print(result);
}

输出:

[one, two, three]
onetwothree

结论

通过实例学习了在dart或flutter中连接和转换列表为单个字符串的多种方法:

  • 连接
  • 减少方法
  • 为索引循环

对于字符串连接,join很简单,容易实现。