Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter remove whitespace, commas, and brackets from List when going to display as a String

Tags:

flutter

dart

I want to go through my list of strings, and add it to a text element for display, but I want to remove the commas and remove the [] as well as the whitespace, but leave the symbols except the commas and brackets.

So if the List is.

[1,2,#3,*4,+5]

In the text field I want it to show - "12#3*4+5"

I can figure out how to display it, but Im using

Text(myList.tostring().replaceAll('[\\]\\,\\', '')

Is there a way to do this?

like image 625
Bnd10706 Avatar asked Oct 18 '25 13:10

Bnd10706


2 Answers

You should use the reduce method on your list.

List<String> myList = ["1", "2", "#3", "*4", "+5"];
String finalStr = myList.reduce((value, element) {
  return value + element;
});
print(finalStr);
# output: "12#3*4+5"

This method reduces a collection to a single value by iteratively combining elements of the collection using the provided function.

The method takes a function that receives two parameters: one is the current concatenated value, which starts out with the value of the first element of your list, and the second parameter is the next element on your list. So you can do something with those two values, and return it for the next iterations. At last, a single reduced value is returned. In this case, using strings, the code in my answer will concatenate the values. If those were numbers, the result would be a sum of the elements.

If you want to add anything in between elements, simply use the return value. For instance, to separate the elements by comma and whitespace, it should look like return value + " ," + element;.

like image 185
George Avatar answered Oct 20 '25 03:10

George


Unless I'm misunderstanding the question, the most obvious solution would be to use List.join().

List<String> myList = ["1", "2", "#3", "*4", "+5"];
print( myList.join() ); 

// Result
// 12#3*4+5

You could also specify a separator

print( myList.join(' ') ); 

// Result
// 1 2 #3 *4 +5
like image 38
Magnus Avatar answered Oct 20 '25 02:10

Magnus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!