Dart| Flutter: Convert List of Dynamic into List of String examples
In Dart and flutter, this tutorial explains how to convert List<Dynamic>
to List<String>
and vice versa.
A dynamic type is a primitive type that may hold any dynamic value, such as an integer, a string, or a double.
Because a string is a primitive type that stores a collection of characters, automated conversion to/from dynamic is not possible.
You can check on How to convert dynamic to string and vice versa or vice versa in Dart and flutter.
How to Convert List of String into List of Dynamic type in Dart
In dart and flutter, this example converts a list of strings to a list of dynamics.
List has an array of strings.
List. from()
has a named constructor that takes a list of strings. It is a shallow copy of a list.
void main() {
List<String> numbers = <String>['one', 'two', "four"];
print(numbers.runtimeType);
List<dynamic> dynamicValues = List<dynamic>.from(numbers);
print(dynamicValues.runtimeType);
print(dynamicValues);
}
Output:
JSArray<String>
JSArray<dynamic>
[one, two, four]
How to parse List of Dynamic into List of String type in Dart
In dart and flutter, this example converts a list of dynamic types to a list of Strings.
map()
is used to iterate over a list of dynamic strings. To convert each element in the map to a String, toString()
is used. Finally, use the toList()
method to return a list.
void main() {
List<dynamic> numbers = <dynamic>['one', 'two', "four"];
print(numbers.runtimeType);
final List<String> strs = numbers.map((e) => e.toString()).toList();
print(strs.runtimeType);
print(strs);
}
Output:
JSArray<dynamic>
JSArray<String>
[one, two, four]
Conclusion
Learned how to parse and convert a list of strings into a list of dynamic and vice versa.