Display a list of integers as a String

2020-04-29 00:40发布

问题:

I have a list of integers like:

List<int> list = [1,2,3,4,5];

I would like to display this list inside a Text widget, having as a result: 1,2,3,4,5

What happens instead, is that it shows me the numbers inside the parenthesis: (1,2,3,4,5)

This is my code:

final String textToDisplay = list.map((value) {
  String numbers = '';
  return numbers + value.toString() + ',';
}).toString()

and then inside the widget:

Text(textToDisplay);

回答1:

This seems like a perfect use of List.join, as follows:

  var list = <int>[1, 2, 3, 4, 5];
  var textToDisplay = list.join(',');


回答2:

Why not just add

String newText = textToDisplay.substring(1,textToDisplay.length-1);

and use this newText?

UPDATE:

Consider use this instead:

String newList = list.toString();

print(newList.substring(1,newList.length-1));


回答3:

try using this regex,

RegExp(r'([)(]*)')

final String textToDisplay = list.map((value) {
      String numbers = '';
      return numbers + value.toString() ;
    }).toString().replaceAll(RegExp(r'([)(]*)'), "");

Output 1,2,3,4,5