Flutter 将字符串转换为数组

VEl*_*dız 9 string json flutter

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

Nik*_*las 20

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

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

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

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

代码示例

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
        )
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • static List&lt;String&gt; Calories=name.split(" "); 最终食物=List&lt;String&gt;.generate(15,(i)=&gt; "${Myarray[i]} ${Calories[i]}"); body: ListView.builder( itemCount: foods.length, itemBuilder: (context,index){ return ListTile( title: Text('${foods[index]}'), (2认同)