How to convert a list to a JSON string in Dart

Overview

The library dart:convert provides a built-in top-level function called jsonEncode() that can convert a List/Object to a JSON string.

The following are the steps involved in converting a List to a JSON object:

  1. Create a List
  2. Using the jsonEncode() function, extract a JSON string from the List.

Implementation

Create a list named colors.

List<String> colors = ['Blue', 'Red', 'Black', 'Yellow', 'White', 'Pink'];

Then, convert the List colors to a JSON string using the dart:convert library’s built-in jsonEncode() function.

String jsonColors = jsonEncode(colors);

Let’s bring the pieces of code together to view the result.

import 'dart:convert';
main()
{
//Create a list
List<String> colors = ['Blue', 'Red', 'Black', 'Yellow', 'White', 'Pink'];
//Use jsonEncode method
String jsonColors = jsonEncode(colors);
print(jsonColors);
}

Free Resources