Home > Back-end >  I can't assign array to string variable in flutter
I can't assign array to string variable in flutter

Time:08-04

 for (i = 0; i < arr1.length - 1; i  ) {
  msg  = arr1[i]   ",";
}
msg  = arr1[i];

I want to throw the data from the above array into a string variable named msg with a comma between them. But I am getting an error as below. How can I fix.

_TypeError (type 'String' is not a subtype of type 'num' of 'other')

CodePudding user response:

It depends of what type of data is store in the array. If integers, or whatever else, you need to tranform to a string, with the toString() method

So:

msg  = arr1[i].tostring()   ",";

If mixed types, you can check type with something like this:

if (arr1[i] is int) {
  msg  = arr1[i].tostring()   ",";
}

if (arr1[i] is bool) {
  if (arr1[i]) { 
    msg  = "1,";
  } else {
    msg  = "0,";
}
 // And so on...

CodePudding user response:

The error indicates that your arr1 are List<num>. The function on num does not take a String which are the error you are getting.

I would recommend doing the following for creating your String since it will automatically call toString() on your num element and does also make the code smaller:

for (i = 0; i < arr1.length - 1; i  ) {
  msg  = '${arr1[i]},';
}
msg  = '${arr1[i]}';
  •  Tags:  
  • dart
  • Related