Dmitry Bubnenkov
Dmitry Bubnenkov

Reputation: 9859

Convert List<dynamic> to List<String>

I am getting data from server. The run runtimeType shows that they have type List. Currently I am using cast<String>() to get List<String>.

But is it's only\right way?

   var value = await http.get('http://127.0.0.1:5001/regions');

   if(value.statusCode == 200) {  
      return jsonDecode(value.body)['data'].cast<String>();
    }

Upvotes: 0

Views: 60

Answers (1)

lrn
lrn

Reputation: 71693

There are multiple ways, depending on how soon you want an error if the list contains a non-string, and how you're going to use the list.

  • list.cast<String>() creates a lazy wrapper around the original list. It checks on each read that the value is actually a String. If you plan to read often, all that type checking might be expensive, and if you want an early error if the last element of the list is not a string, it won't do that for you.

  • List<String>.from(list) creates a new list of String and copies each element from list into the new list, checking along the way that it's actually a String. This approach errs early if a value isn't actually a string. After creation, there are no further type checks. On the other hand, creating a new list costs extra memory.

  • [for (var s in list) s as String],

  • [... list.cast<String>()],

  • <String>[for (var s in list) s],

  • <String>[... list] are all other ways to create a new list of strings. The last two relies on implicit downcast from dynamic, the first two uses explicit casts.

I recommend using list literals where possible. Here, I'd probably go for the smallest version <String>[...list], if you want a new list. Otherwise .cast<String>() is fine.

Upvotes: 1

Related Questions