Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter converting a string into array

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

like image 818
VEli Yıldız Avatar asked Mar 26 '19 12:03

VEli Yıldız


1 Answers

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: 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:

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
        )
      ),
    );
  }
}
like image 50
NiklasPor Avatar answered Oct 21 '22 11:10

NiklasPor