本文介绍了Flutter将字符串转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将长字符串文本更改为数组,在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:

  1. String.split:拆分String来创建List
  2. List<String>.map:将String映射到小部件
  3. Iterable<Widget>.toList:将Map转换回List
  1. String.split: To split the String to create the List
  2. List<String>.map: Map the String to a Widget
  3. Iterable<Widget>.toList: Convert the Map back to a List

下面是一个简单的独立示例:

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将字符串转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 14:31