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
3 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:
String.split: To split theStringto create theListList<String>.map: Map theStringto a WidgetIterable<Widget>.toList: Convert theMapback 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
)
),
);
}
}
6 Comments
Wali Seddiqi
Thanks I will try that it is bit short and seems easier , I wrote it a little different
Wali Seddiqi
static List<String> Calories=name.split(" "); final foods=List<String>.generate(15,(i)=> "${Myarray[i]} ${Calories[i]}"); body: ListView.builder( itemCount: foods.length, itemBuilder: (context,index){ return ListTile( title: Text('${foods[index]}'),
NiklasPor
You may wanna add the code to your question, to clarify your goal and what you have tried!
Wali Seddiqi
Okay thank you very much, I wasnt aware of being able to add code into question cuz I am new in here, I will try to add in future
NiklasPor
You could use RegEx and allMatches for splitting it every 2 characters. Or a simple for loop. I'd suggest you search google / whatever for some regex based solution. If you can't find any tell me again @JohnSmithly .
|
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

splitis working in flutter - it uses dart after allsplit()is aStringmethod, what does Convert has to do with it?