Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära JSON Serialization in Dart for Flutter | Writing Clean Dart for Scalable Flutter Apps
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
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

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 2

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

bookJSON Serialization in Dart for Flutter

Svep för att visa menyn

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

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 2
some-alt