CodeBlanks Logo Icon CodeBlanks

List<dynamic>

Read JSON arrays as List<dynamic>.

Turning a JSON array into List<dynamic>

A JSON array (with square brackets) is turned into a List<dynamic> by jsonDecode. You access items by index.

const s = '["a", "b", "c"]';
final liste = jsonDecode(s) as List<dynamic>;
print(liste[0]);  // a
print(liste.length);  // 3

Element types are dynamic; for safe use you cast them with as.

Casting the list with cast

To make the list type-safe you use cast<String>() or .map. cast<String>() treats every element as a String and throws otherwise.

final liste = jsonDecode('["x","y"]') as List<dynamic>;
final kelimeler = liste.cast<String>();
print(kelimeler[1]);  // y

Now kelimeler is a List<String> and you can access items safely.

Practice Print the second element of the list

Decode the string s with jsonDecode, cast it with as List, and print the second element with print.

Starter code

main.dart
import 'dart:convert';

void main() {
  const s = '["elma", "armut", "kiraz"]';
  // JSON dizisini çöz ve ikinci elemanı yazdır
}

Sample solution

main.dart
import 'dart:convert';

void main() {
  const s = '["elma", "armut", "kiraz"]';
  final liste = jsonDecode(s) as List;
  print(liste[1]);
}

Expected output

armut

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does jsonDecode('[1,2,3]') return?

  • String
  • List<dynamic> Correct answer
  • A Future
  • Map<String, dynamic>

Explanation: jsonDecode turns a JSON array into a List<dynamic>. An object input would return a Map; but a square-bracketed input is a list.

2 Access the first element

Question
import 'dart:convert';

void main() {
  const s = '[10, 20, 30]';
  final liste = jsonDecode(s) as List;
  final ilk = liste[____];
  print(ilk);
}
Answer
import 'dart:convert';

void main() {
  const s = '[10, 20, 30]';
  final liste = jsonDecode(s) as List;
  final ilk = liste[0];
  print(ilk);
}

Explanation: The first element of a list has index 0; liste[0] gives 10.

3 JSON array parts

Term Meaning
List<dynamic> Dart equivalent of a JSON array
liste[0] Access to the first element
cast<String>() Casts the list to a list of Strings
liste.length Gives the number of elements

All lessons in Intermediate