Reputation: 466
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
Upvotes: 18
Views: 53404
Reputation: 21
List<String> list = "Hello Word".split("");
print(list);
//[H,e,l,l,o, ,W,o,r,l,d]
List<String> list = "Hello World".split(" ");
print(list);
//["Hello", "World"]
Upvotes: 1
Reputation: 427
For those who want to convert each character of string into list item, we can
String username = "John Doe";
List<String> searchKeywords = List<String>.generate(
username.length,
(index) => username[index]); // ['J','o','h','n',' ','D','o','e']
Morever you can remove white spaces using trim() method
Upvotes: 4
Reputation: 9785
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
: To split the String
to create the List
List<String>.map
: Map the String
to a WidgetIterable<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
)
),
);
}
}
Upvotes: 30