How to Use jsonDecode in Flutter: Simple Guide
In Flutter, use
jsonDecode from the dart:convert library to convert a JSON string into a Dart object like a Map or List. Simply pass the JSON string to jsonDecode, and it returns the decoded data you can use in your app.Syntax
The jsonDecode function takes a JSON formatted string and converts it into a Dart object, usually a Map<String, dynamic> or a List. You must import dart:convert to use it.
jsonDecode(String source): Takes a JSON stringsource.- Returns a Dart object representing the JSON data.
dart
import 'dart:convert'; var decoded = jsonDecode(jsonString);
Example
This example shows how to decode a JSON string representing a user with a name and age into a Dart Map, then access its values.
dart
import 'dart:convert'; void main() { String jsonString = '{"name": "Alice", "age": 30}'; Map<String, dynamic> user = jsonDecode(jsonString); print('Name: ${user["name"]}'); print('Age: ${user["age"]}'); }
Output
Name: Alice
Age: 30
Common Pitfalls
Common mistakes when using jsonDecode include:
- Passing a non-JSON string or malformed JSON causes a
FormatException. - Not importing
dart:convertbefore usingjsonDecode. - Assuming the decoded object is always a Map; it can also be a List if the JSON starts with
[.
dart
import 'dart:convert'; void main() { // Wrong: malformed JSON string try { var data = jsonDecode('{name: Alice}'); // Missing quotes around key } catch (e) { print('Error: $e'); } // Right: properly formatted JSON var correctData = jsonDecode('{"name": "Alice"}'); print(correctData['name']); }
Output
Error: FormatException: Unexpected character (at character 2)
{name: Alice}
^
Alice
Quick Reference
Remember these tips when using jsonDecode:
- Always import
dart:convert. - Ensure your JSON string is valid and properly formatted.
- Check if the decoded result is a Map or List before using it.
- Use try-catch to handle possible format errors gracefully.
Key Takeaways
Use jsonDecode from dart:convert to convert JSON strings to Dart objects.
Always ensure your JSON string is valid to avoid runtime errors.
The decoded object can be a Map or List depending on the JSON structure.
Import dart:convert before using jsonDecode.
Use try-catch to handle JSON parsing errors safely.