gpt4 book ai didi

json - Flutter 将字符串转换为数组

转载 作者:IT王子 更新时间:2023-10-29 07:12:11 70 4
gpt4 key购买 nike

我正在尝试将一个长字符串文本更改为一个数组,dart 中有一些方法作为 String.split 但它在 Flutter 中不起作用,是否有任何解决方案可以将字符串按空格转换为数组然后在 ListView 中使用数组

最佳答案

使用后String.split创建List (相当于 Dart 的数组),我们有一个 List<String> .如果你想使用 List<String>ListView 里面, 你需要一个 Widget显示文本。您可以简单地使用 Text小工具。

以下函数可以帮助您做到这一点:

  1. String.split : 分割String创建List
  2. List<String>.map : 映射String到小部件
  3. Iterable<Widget>.toList : 转换 Map回到List

下面是一个快速的独立示例:

Code Example

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
static const String example = 'The quick brown fox jumps over the lazy dog';

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: ListView(
children: example
.split(' ') // split the text into an array
.map((String text) => Text(text)) // put the text inside a widget
.toList(), // convert the iterable to a list
)
),
);
}
}

关于json - Flutter 将字符串转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55356998/

70 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com