问题描述
我正在尝试将长字符串文本更改为数组,在dart中有一些方法,如String.split,但在Flutter中不起作用,有什么解决方案可以将空格将字符串转换为数组,然后在Listview中使用数组
I am trying to change a long string text into an array, There are some methods in dart as String.split but its not working in Flutter, is there any solution that I can convert a string by spaces into an array and then use the array in a Listview
推荐答案
在使用String.split
创建List
(等效于Array的Dart)之后,我们有了一个List<String>
.如果您想在 ListView 中使用List<String>
需要一个Widget
来显示文本.您可以简单地使用文本小部件.
After using String.split
to create the List
(the Dart equivalent of an Array), we have a List<String>
. If you wanna use the List<String>
inside a ListView, you'll need a Widget
which displays the text. You can simply use a Text Widget.
以下功能可以帮助您做到这一点:
The following functions can help you to do this:
-
String.split
:拆分String
来创建List
-
List<String>.map
:将String
映射到小部件 -
Iterable<Widget>.toList
:将Map
转换回List
String.split
: To split theString
to create theList
List<String>.map
: Map theString
to a WidgetIterable<Widget>.toList
: Convert theMap
back to aList
下面是一个简单的独立示例:
Below a quick standalone 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
)
),
);
}
}
这篇关于Flutter将字符串转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!