Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære JSON Serialization in Dart for Flutter | Writing Clean Dart for Scalable Flutter Apps
Dart for Flutter Developers

bookJSON Serialization in Dart for Flutter

JSON serialization is the process of converting Dart objects into JSON format and vice versa. This is essential in Flutter apps because most APIs and network services communicate using JSON. By serializing and deserializing data, you can easily send and receive structured information between your app and backend services. Clean and reliable JSON handling is critical for scalable, maintainable Flutter code.

Note
Note

Always check for the presence and type of fields in your JSON data to avoid runtime errors. Defensive parsing ensures your Flutter app remains robust even when backend data changes or is incomplete.

main.dart

main.dart

copy
123456789101112131415161718192021222324252627282930313233
class User { final String name; final int age; User({required this.name, required this.age}); // Deserialize from JSON factory User.fromJson(Map<String, dynamic> json) { return User( name: json['name'] as String, age: json['age'] as int, ); } // Serialize to JSON Map<String, dynamic> toJson() { return { 'name': name, 'age': age, }; } } void main() { // Example: Serialize User user = User(name: 'Alice', age: 30); Map<String, dynamic> json = user.toJson(); print(json); // Example: Deserialize User anotherUser = User.fromJson({'name': 'Bob', 'age': 25}); print('${anotherUser.name}, ${anotherUser.age}'); }

When working with JSON from network sources, you may encounter null or missing fields. Dart's null safety helps, but you should always handle these cases explicitly. Use default values or null-aware operators to avoid runtime errors when fields are absent or have unexpected types.

main.dart

main.dart

copy
1234567891011121314151617181920212223242526272829303132333435363738
import 'package:flutter/material.dart'; class Product { final String title; final double price; Product({required this.title, required this.price}); factory Product.fromJson(Map<String, dynamic> json) { return Product( title: json['title'] as String? ?? 'Unknown', price: (json['price'] is num) ? (json['price'] as num).toDouble() : 0.0, ); } } class ProductWidget extends StatelessWidget { final Map<String, dynamic> jsonData; const ProductWidget({super.key, required this.jsonData}); @override Widget build(BuildContext context) { final product = Product.fromJson(jsonData); return ListTile( title: Text(product.title), subtitle: Text('Price: \$${product.price}'), ); } } void main() { runApp(MaterialApp( home: Scaffold( body: ProductWidget(jsonData: {'title': null, 'price': 'not a number'}), ), )); }
question mark

Which of the following is the best practice for JSON deserialization in Dart?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 2

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

bookJSON Serialization in Dart for Flutter

Sveip for å vise menyen

JSON serialization is the process of converting Dart objects into JSON format and vice versa. This is essential in Flutter apps because most APIs and network services communicate using JSON. By serializing and deserializing data, you can easily send and receive structured information between your app and backend services. Clean and reliable JSON handling is critical for scalable, maintainable Flutter code.

Note
Note

Always check for the presence and type of fields in your JSON data to avoid runtime errors. Defensive parsing ensures your Flutter app remains robust even when backend data changes or is incomplete.

main.dart

main.dart

copy
123456789101112131415161718192021222324252627282930313233
class User { final String name; final int age; User({required this.name, required this.age}); // Deserialize from JSON factory User.fromJson(Map<String, dynamic> json) { return User( name: json['name'] as String, age: json['age'] as int, ); } // Serialize to JSON Map<String, dynamic> toJson() { return { 'name': name, 'age': age, }; } } void main() { // Example: Serialize User user = User(name: 'Alice', age: 30); Map<String, dynamic> json = user.toJson(); print(json); // Example: Deserialize User anotherUser = User.fromJson({'name': 'Bob', 'age': 25}); print('${anotherUser.name}, ${anotherUser.age}'); }

When working with JSON from network sources, you may encounter null or missing fields. Dart's null safety helps, but you should always handle these cases explicitly. Use default values or null-aware operators to avoid runtime errors when fields are absent or have unexpected types.

main.dart

main.dart

copy
1234567891011121314151617181920212223242526272829303132333435363738
import 'package:flutter/material.dart'; class Product { final String title; final double price; Product({required this.title, required this.price}); factory Product.fromJson(Map<String, dynamic> json) { return Product( title: json['title'] as String? ?? 'Unknown', price: (json['price'] is num) ? (json['price'] as num).toDouble() : 0.0, ); } } class ProductWidget extends StatelessWidget { final Map<String, dynamic> jsonData; const ProductWidget({super.key, required this.jsonData}); @override Widget build(BuildContext context) { final product = Product.fromJson(jsonData); return ListTile( title: Text(product.title), subtitle: Text('Price: \$${product.price}'), ); } } void main() { runApp(MaterialApp( home: Scaffold( body: ProductWidget(jsonData: {'title': null, 'price': 'not a number'}), ), )); }
question mark

Which of the following is the best practice for JSON deserialization in Dart?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 2
some-alt