Convert String representation of List to a List in Flutter

Updated: February 15, 2023 By: A Goodman Post a comment
Convert String to List in Flutter

In order to convert a string representation of a list to an actual list in Flutter, just import dart:convert and call json.decode().

Sample code:

import 'dart:convert';

// This function will convert a valid input to a list
// In case the input is invalid, it will print out a message
List? convert(String input) {
  List output;
  try {
    output = json.decode(input);
    return output;
  } catch (err) {
    print('The input is not a string representation of a list');
    return null;
  }
}

// Try it
void main() {
  const String text1 = "[1, 2, 3, 4, 5]";
  const String text2 = '''[
      {
        "userId": 1,
        "title": "delectus aut autem",
        "completed": false
      },
      {
        "userId": 1,
        "id": 2,
        "title": "quis ut nam facilis et officia qui",
        "completed": false
      }
    ]''';

  final List? list1 = convert(text1);
  print(list1.runtimeType);
  final List? list2 = convert(text2);
  print(list2.runtimeType);
}

If you try the code in a Flutter project, the output should look like this:

List<dynamic>
List<dynamic>

If you run the code with some online IED, you may see the following:

JSArray<dynamic>
JSArray<dynamic>

Further reading:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles