Skip to main content

24 posts tagged with "Flutter"

View All Tags

Hướng Dẫn Parse JSON Trong Flutter Bằng Model + Factory Constructor

· 11 min read

Parse JSON là một kỹ năng cơ bản nhưng quan trọng trong Flutter. Bài viết này sẽ hướng dẫn bạn cách parse JSON chuyên nghiệp bằng cách sử dụng model class với factory constructor.


1️⃣ Tại Sao Sử Dụng Model Class?

1.1 Vấn Đề Khi Parse JSON Thủ Công

// ❌ Không tốt: Parse trực tiếp
void fetchUser() async {
final response = await http.get(Uri.parse('https://api.example.com/user'));
final json = jsonDecode(response.body);

// Truy cập trực tiếp - dễ lỗi, không type-safe
String name = json['name'];
int age = json['age'];
// Nếu API thay đổi, code sẽ lỗi runtime
}

Vấn đề:

  • ❌ Không type-safe
  • ❌ Dễ lỗi khi API thay đổi
  • ❌ Khó maintain
  • ❌ Không có autocomplete

1.2 Giải Pháp: Model Class

// ✅ Tốt: Sử dụng model class
class User {
final String name;
final int age;

User({required this.name, required this.age});

factory User.fromJson(Map<String, dynamic> json) {
return User(
name: json['name'] as String,
age: json['age'] as int,
);
}

Map<String, dynamic> toJson() {
return {
'name': name,
'age': age,
};
}
}

// Sử dụng
void fetchUser() async {
final response = await http.get(Uri.parse('https://api.example.com/user'));
final json = jsonDecode(response.body);
final user = User.fromJson(json);

// Type-safe, có autocomplete
print(user.name);
print(user.age);
}

Lợi ích:

  • ✅ Type-safe
  • ✅ Dễ maintain
  • ✅ Có autocomplete
  • ✅ Dễ test
  • ✅ Có thể validate data

2️⃣ Model Class Cơ Bản

2.1 Model Đơn Giản

class User {
final int id;
final String name;
final String email;
final bool isActive;

User({
required this.id,
required this.name,
required this.email,
required this.isActive,
});

// Factory constructor để parse từ JSON
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as int,
name: json['name'] as String,
email: json['email'] as String,
isActive: json['is_active'] as bool? ?? true, // Default value
);
}

// Method để convert sang JSON
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'email': email,
'is_active': isActive,
};
}

// Copy method để tạo instance mới với một số thay đổi
User copyWith({
int? id,
String? name,
String? email,
bool? isActive,
}) {
return User(
id: id ?? this.id,
name: name ?? this.name,
email: email ?? this.email,
isActive: isActive ?? this.isActive,
);
}

@override
String toString() {
return 'User(id: $id, name: $name, email: $email, isActive: $isActive)';
}
}

2.2 Sử Dụng Model

// Parse từ JSON string
String jsonString = '''
{
"id": 1,
"name": "Nguyễn Văn A",
"email": "nguyenvana@example.com",
"is_active": true
}
''';

final json = jsonDecode(jsonString) as Map<String, dynamic>;
final user = User.fromJson(json);

print(user.name); // Nguyễn Văn A
print(user.email); // nguyenvana@example.com

// Convert sang JSON
final userJson = user.toJson();
print(jsonEncode(userJson));

3️⃣ Xử Lý Các Trường Hợp Đặc Biệt

3.1 Nullable Fields

class User {
final int id;
final String name;
final String? phone; // Nullable
final String? avatar; // Nullable

User({
required this.id,
required this.name,
this.phone,
this.avatar,
});

factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as int,
name: json['name'] as String,
phone: json['phone'] as String?,
avatar: json['avatar'] as String?,
);
}

Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'phone': phone,
'avatar': avatar,
};
}
}

3.2 Default Values

factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as int,
name: json['name'] as String,
phone: json['phone'] as String? ?? '', // Default empty string
isActive: json['is_active'] as bool? ?? true, // Default true
createdAt: json['created_at'] != null
? DateTime.parse(json['created_at'] as String)
: DateTime.now(), // Default now
);
}

3.3 Type Conversion

class Product {
final int id;
final String name;
final double price;
final DateTime createdAt;

Product({
required this.id,
required this.name,
required this.price,
required this.createdAt,
});

factory Product.fromJson(Map<String, dynamic> json) {
return Product(
id: json['id'] as int,
name: json['name'] as String,
// Convert string to double
price: (json['price'] as num).toDouble(),
// Convert string to DateTime
createdAt: DateTime.parse(json['created_at'] as String),
);
}

Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'price': price,
'created_at': createdAt.toIso8601String(),
};
}
}

4️⃣ Nested Objects

4.1 Object Trong Object

// Address model
class Address {
final String street;
final String city;
final String country;

Address({
required this.street,
required this.city,
required this.country,
});

factory Address.fromJson(Map<String, dynamic> json) {
return Address(
street: json['street'] as String,
city: json['city'] as String,
country: json['country'] as String,
);
}

Map<String, dynamic> toJson() {
return {
'street': street,
'city': city,
'country': country,
};
}
}

// User model với Address
class User {
final int id;
final String name;
final Address address; // Nested object

User({
required this.id,
required this.name,
required this.address,
});

factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as int,
name: json['name'] as String,
address: Address.fromJson(json['address'] as Map<String, dynamic>),
);
}

Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'address': address.toJson(),
};
}
}

// JSON example
String jsonString = '''
{
"id": 1,
"name": "Nguyễn Văn A",
"address": {
"street": "123 Đường ABC",
"city": "Hà Nội",
"country": "Việt Nam"
}
}
''';

final user = User.fromJson(jsonDecode(jsonString) as Map<String, dynamic>);
print(user.address.city); // Hà Nội

4.2 Nullable Nested Object

class User {
final int id;
final String name;
final Address? address; // Nullable nested object

User({
required this.id,
required this.name,
this.address,
});

factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as int,
name: json['name'] as String,
address: json['address'] != null
? Address.fromJson(json['address'] as Map<String, dynamic>)
: null,
);
}

Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'address': address?.toJson(),
};
}
}

5️⃣ Lists và Arrays

5.1 List of Primitives

class User {
final int id;
final String name;
final List<String> tags; // List of strings

User({
required this.id,
required this.name,
required this.tags,
});

factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as int,
name: json['name'] as String,
tags: (json['tags'] as List<dynamic>)
.map((tag) => tag as String)
.toList(),
);
}

Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'tags': tags,
};
}
}

5.2 List of Objects

class User {
final int id;
final String name;
final List<Address> addresses; // List of Address objects

User({
required this.id,
required this.name,
required this.addresses,
});

factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as int,
name: json['name'] as String,
addresses: (json['addresses'] as List<dynamic>)
.map((address) => Address.fromJson(address as Map<String, dynamic>))
.toList(),
);
}

Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'addresses': addresses.map((address) => address.toJson()).toList(),
};
}
}

5.3 Nullable List

factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as int,
name: json['name'] as String,
addresses: json['addresses'] != null
? (json['addresses'] as List<dynamic>)
.map((address) => Address.fromJson(address as Map<String, dynamic>))
.toList()
: [], // Default empty list
);
}

6️⃣ Enum Parsing

6.1 Parse Enum Từ String

enum UserStatus {
active,
inactive,
suspended,
}

class User {
final int id;
final String name;
final UserStatus status;

User({
required this.id,
required this.name,
required this.status,
});

factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as int,
name: json['name'] as String,
status: UserStatus.values.firstWhere(
(e) => e.name == json['status'],
orElse: () => UserStatus.inactive, // Default
),
);
}

Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'status': status.name,
};
}
}

6.2 Enum Với Custom Values

enum UserStatus {
active('active'),
inactive('inactive'),
suspended('suspended');

final String value;
const UserStatus(this.value);

static UserStatus fromString(String value) {
return UserStatus.values.firstWhere(
(e) => e.value == value,
orElse: () => UserStatus.inactive,
);
}
}

class User {
final int id;
final String name;
final UserStatus status;

User({
required this.id,
required this.name,
required this.status,
});

factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as int,
name: json['name'] as String,
status: UserStatus.fromString(json['status'] as String),
);
}

Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'status': status.value,
};
}
}

7️⃣ Ví Dụ Hoàn Chỉnh: Complex Model

class User {
final int id;
final String name;
final String email;
final String? phone;
final Address? address;
final List<String> tags;
final List<Order> orders;
final UserStatus status;
final DateTime createdAt;
final DateTime? updatedAt;

User({
required this.id,
required this.name,
required this.email,
this.phone,
this.address,
required this.tags,
required this.orders,
required this.status,
required this.createdAt,
this.updatedAt,
});

factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as int,
name: json['name'] as String,
email: json['email'] as String,
phone: json['phone'] as String?,
address: json['address'] != null
? Address.fromJson(json['address'] as Map<String, dynamic>)
: null,
tags: json['tags'] != null
? (json['tags'] as List<dynamic>).map((e) => e as String).toList()
: [],
orders: json['orders'] != null
? (json['orders'] as List<dynamic>)
.map((e) => Order.fromJson(e as Map<String, dynamic>))
.toList()
: [],
status: UserStatus.fromString(json['status'] as String? ?? 'inactive'),
createdAt: DateTime.parse(json['created_at'] as String),
updatedAt: json['updated_at'] != null
? DateTime.parse(json['updated_at'] as String)
: null,
);
}

Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'email': email,
'phone': phone,
'address': address?.toJson(),
'tags': tags,
'orders': orders.map((e) => e.toJson()).toList(),
'status': status.value,
'created_at': createdAt.toIso8601String(),
'updated_at': updatedAt?.toIso8601String(),
};
}

User copyWith({
int? id,
String? name,
String? email,
String? phone,
Address? address,
List<String>? tags,
List<Order>? orders,
UserStatus? status,
DateTime? createdAt,
DateTime? updatedAt,
}) {
return User(
id: id ?? this.id,
name: name ?? this.name,
email: email ?? this.email,
phone: phone ?? this.phone,
address: address ?? this.address,
tags: tags ?? this.tags,
orders: orders ?? this.orders,
status: status ?? this.status,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
);
}

@override
String toString() {
return 'User(id: $id, name: $name, email: $email)';
}
}

class Address {
final String street;
final String city;
final String country;

Address({
required this.street,
required this.city,
required this.country,
});

factory Address.fromJson(Map<String, dynamic> json) {
return Address(
street: json['street'] as String,
city: json['city'] as String,
country: json['country'] as String,
);
}

Map<String, dynamic> toJson() {
return {
'street': street,
'city': city,
'country': country,
};
}
}

class Order {
final int id;
final double total;
final DateTime orderDate;

Order({
required this.id,
required this.total,
required this.orderDate,
});

factory Order.fromJson(Map<String, dynamic> json) {
return Order(
id: json['id'] as int,
total: (json['total'] as num).toDouble(),
orderDate: DateTime.parse(json['order_date'] as String),
);
}

Map<String, dynamic> toJson() {
return {
'id': id,
'total': total,
'order_date': orderDate.toIso8601String(),
};
}
}

enum UserStatus {
active('active'),
inactive('inactive'),
suspended('suspended');

final String value;
const UserStatus(this.value);

static UserStatus fromString(String value) {
return UserStatus.values.firstWhere(
(e) => e.value == value,
orElse: () => UserStatus.inactive,
);
}
}

8️⃣ Sử Dụng Với API

import 'package:dio/dio.dart';
import 'dart:convert';

class UserRepository {
final Dio dio = Dio();

Future<User> getUser(int id) async {
try {
final response = await dio.get('/users/$id');
return User.fromJson(response.data as Map<String, dynamic>);
} catch (e) {
throw Exception('Failed to get user: $e');
}
}

Future<List<User>> getUsers() async {
try {
final response = await dio.get('/users');
return (response.data as List<dynamic>)
.map((json) => User.fromJson(json as Map<String, dynamic>))
.toList();
} catch (e) {
throw Exception('Failed to get users: $e');
}
}

Future<User> createUser(User user) async {
try {
final response = await dio.post(
'/users',
data: user.toJson(),
);
return User.fromJson(response.data as Map<String, dynamic>);
} catch (e) {
throw Exception('Failed to create user: $e');
}
}
}

9️⃣ Best Practices

9.1 Error Handling

factory User.fromJson(Map<String, dynamic> json) {
try {
return User(
id: json['id'] as int,
name: json['name'] as String,
email: json['email'] as String,
);
} catch (e) {
throw FormatException('Failed to parse User: $e');
}
}

9.2 Validation

factory User.fromJson(Map<String, dynamic> json) {
// Validate required fields
if (json['id'] == null || json['name'] == null) {
throw FormatException('Missing required fields');
}

// Validate email format
final email = json['email'] as String;
if (!email.contains('@')) {
throw FormatException('Invalid email format');
}

return User(
id: json['id'] as int,
name: json['name'] as String,
email: email,
);
}

9.3 Sử Dụng json_serializable (Optional)

Để tự động generate code, bạn có thể sử dụng json_serializable:

dependencies:
json_annotation: ^4.8.1

dev_dependencies:
build_runner: ^2.4.7
json_serializable: ^6.7.1
import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
final int id;
final String name;
final String email;

User({required this.id, required this.name, required this.email});

factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}

🔟 Kết Luận

Parse JSON với model class và factory constructor giúp bạn:

Type-safe: Tránh lỗi runtime
Dễ maintain: Code rõ ràng, dễ đọc
Có autocomplete: IDE hỗ trợ tốt
Dễ test: Có thể test parsing logic
Validation: Có thể validate data

💡 Lời khuyên: Luôn sử dụng model class cho JSON parsing. Đừng parse trực tiếp từ Map<String, dynamic> trong business logic.


🎓 Học Sâu Hơn Về Flutter

Muốn master Flutter, JSON Parsing, và các best practices? Tham gia các khóa học tại Hướng Nghiệp Dữ Liệu:

📚 Khóa Học Liên Quan:


📝 Bài viết này được biên soạn bởi đội ngũ Hướng Nghiệp Dữ Liệu. Để cập nhật thêm về Flutter, JSON parsing và các best practices trong phát triển ứng dụng di động, hãy theo dõi blog của chúng tôi.

Hướng Dẫn Sử Dụng Riverpod/Provider Cho Quản Lý State Khi Gọi API

· 10 min read

Quản lý state khi gọi API là một thách thức trong Flutter. Bài viết này sẽ hướng dẫn bạn cách sử dụng Riverpod hoặc Provider để quản lý state một cách hiệu quả khi gọi API.


1️⃣ Tại Sao Cần State Management Cho API?

1.1 Vấn Đề Khi Không Dùng State Management

// ❌ Không tốt: State management thủ công
class UserScreen extends StatefulWidget {
@override
_UserScreenState createState() => _UserScreenState();
}

class _UserScreenState extends State<UserScreen> {
User? user;
bool isLoading = false;
String? error;

@override
void initState() {
super.initState();
_loadUser();
}

Future<void> _loadUser() async {
setState(() => isLoading = true);
try {
final response = await api.getUser(1);
setState(() {
user = response;
isLoading = false;
});
} catch (e) {
setState(() {
error = e.toString();
isLoading = false;
});
}
}

@override
Widget build(BuildContext context) {
// Phải xử lý loading, error, data trong mọi widget
if (isLoading) return CircularProgressIndicator();
if (error != null) return Text('Error: $error');
if (user == null) return Text('No data');
return UserWidget(user: user!);
}
}

Vấn đề:

  • ❌ Code lặp lại nhiều
  • ❌ Khó test
  • ❌ Khó share state giữa các widget
  • ❌ Không có caching

1.2 Giải Pháp: State Management

Với Riverpod/Provider:

  • ✅ Code sạch hơn
  • ✅ Dễ test
  • ✅ Share state dễ dàng
  • ✅ Có caching
  • ✅ Auto dispose

2️⃣ Sử Dụng Riverpod

2.1 Cài Đặt

dependencies:
flutter_riverpod: ^2.4.9
riverpod_annotation: ^2.3.3

dev_dependencies:
build_runner: ^2.4.7
riverpod_generator: ^2.3.9

2.2 Tạo API Provider

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:dio/dio.dart';

// API Service
final apiServiceProvider = Provider<Dio>((ref) {
return Dio(BaseOptions(
baseUrl: 'https://api.example.com',
));
});

// User Repository
final userRepositoryProvider = Provider<UserRepository>((ref) {
final dio = ref.watch(apiServiceProvider);
return UserRepository(dio);
});

2.3 Tạo Async State Provider

import 'package:flutter_riverpod/flutter_riverpod.dart';

// User Provider với async state
final userProvider = FutureProvider.family<User, int>((ref, userId) async {
final repository = ref.watch(userRepositoryProvider);
return await repository.getUser(userId);
});

// Users List Provider
final usersProvider = FutureProvider<List<User>>((ref) async {
final repository = ref.watch(userRepositoryProvider);
return await repository.getUsers();
});

2.4 Sử Dụng Trong Widget

import 'package:flutter_riverpod/flutter_riverpod.dart';

class UserScreen extends ConsumerWidget {
final int userId;

const UserScreen({Key? key, required this.userId}) : super(key: key);

@override
Widget build(BuildContext context, WidgetRef ref) {
final userAsync = ref.watch(userProvider(userId));

return Scaffold(
appBar: AppBar(title: Text('User')),
body: userAsync.when(
data: (user) => UserDetailsWidget(user: user),
loading: () => Center(child: CircularProgressIndicator()),
error: (error, stack) => ErrorWidget(
error: error,
onRetry: () => ref.refresh(userProvider(userId)),
),
),
);
}
}

3️⃣ StateNotifier Cho Complex State

3.1 Tạo State Class

// User State
class UserState {
final User? user;
final bool isLoading;
final String? error;

UserState({
this.user,
this.isLoading = false,
this.error,
});

UserState copyWith({
User? user,
bool? isLoading,
String? error,
}) {
return UserState(
user: user ?? this.user,
isLoading: isLoading ?? this.isLoading,
error: error,
);
}
}

3.2 Tạo StateNotifier

import 'package:flutter_riverpod/flutter_riverpod.dart';

class UserNotifier extends StateNotifier<UserState> {
final UserRepository repository;

UserNotifier(this.repository) : super(UserState());

Future<void> loadUser(int userId) async {
state = state.copyWith(isLoading: true, error: null);

try {
final user = await repository.getUser(userId);
state = state.copyWith(user: user, isLoading: false);
} catch (e) {
state = state.copyWith(
error: e.toString(),
isLoading: false,
);
}
}

Future<void> updateUser(User user) async {
state = state.copyWith(isLoading: true, error: null);

try {
final updatedUser = await repository.updateUser(user);
state = state.copyWith(user: updatedUser, isLoading: false);
} catch (e) {
state = state.copyWith(
error: e.toString(),
isLoading: false,
);
}
}

void clearError() {
state = state.copyWith(error: null);
}
}

// Provider
final userNotifierProvider = StateNotifierProvider<UserNotifier, UserState>((ref) {
final repository = ref.watch(userRepositoryProvider);
return UserNotifier(repository);
});

3.3 Sử Dụng StateNotifier

class UserScreen extends ConsumerWidget {
final int userId;

const UserScreen({Key? key, required this.userId}) : super(key: key);

@override
Widget build(BuildContext context, WidgetRef ref) {
final userState = ref.watch(userNotifierProvider);

// Load user khi widget được build
ref.listen(userNotifierProvider.notifier, (previous, next) {
next.loadUser(userId);
});

if (userState.isLoading) {
return Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}

if (userState.error != null) {
return Scaffold(
body: ErrorWidget(
error: userState.error!,
onRetry: () => ref.read(userNotifierProvider.notifier).loadUser(userId),
),
);
}

if (userState.user == null) {
return Scaffold(
body: Center(child: Text('No data')),
);
}

return Scaffold(
appBar: AppBar(title: Text('User')),
body: UserDetailsWidget(user: userState.user!),
);
}
}

4️⃣ AsyncNotifier (Riverpod 2.0+)

4.1 Tạo AsyncNotifier

import 'package:flutter_riverpod/flutter_riverpod.dart';

class UserAsyncNotifier extends AsyncNotifier<User> {
@override
Future<User> build() async {
// Load initial data
final userId = ref.watch(selectedUserIdProvider);
final repository = ref.watch(userRepositoryProvider);
return await repository.getUser(userId);
}

Future<void> refresh() async {
state = const AsyncValue.loading();
state = await AsyncValue.guard(() async {
final userId = ref.read(selectedUserIdProvider);
final repository = ref.read(userRepositoryProvider);
return await repository.getUser(userId);
});
}

Future<void> updateUser(User user) async {
state = const AsyncValue.loading();
state = await AsyncValue.guard(() async {
final repository = ref.read(userRepositoryProvider);
return await repository.updateUser(user);
});
}
}

// Provider
final userAsyncNotifierProvider =
AsyncNotifierProvider<UserAsyncNotifier, User>(() {
return UserAsyncNotifier();
});

4.2 Sử Dụng AsyncNotifier

class UserScreen extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final userAsync = ref.watch(userAsyncNotifierProvider);

return Scaffold(
appBar: AppBar(
title: Text('User'),
actions: [
IconButton(
icon: Icon(Icons.refresh),
onPressed: () => ref.read(userAsyncNotifierProvider.notifier).refresh(),
),
],
),
body: userAsync.when(
data: (user) => UserDetailsWidget(user: user),
loading: () => Center(child: CircularProgressIndicator()),
error: (error, stack) => ErrorWidget(
error: error,
onRetry: () => ref.read(userAsyncNotifierProvider.notifier).refresh(),
),
),
);
}
}

5️⃣ Sử Dụng Provider (Alternative)

5.1 Cài Đặt Provider

dependencies:
provider: ^6.1.1

5.2 Tạo ChangeNotifier

import 'package:flutter/foundation.dart';

class UserProvider extends ChangeNotifier {
final UserRepository repository;

User? _user;
bool _isLoading = false;
String? _error;

User? get user => _user;
bool get isLoading => _isLoading;
String? get error => _error;

UserProvider(this.repository);

Future<void> loadUser(int userId) async {
_isLoading = true;
_error = null;
notifyListeners();

try {
_user = await repository.getUser(userId);
_error = null;
} catch (e) {
_error = e.toString();
_user = null;
} finally {
_isLoading = false;
notifyListeners();
}
}

Future<void> refresh() async {
if (_user != null) {
await loadUser(_user!.id);
}
}
}

5.3 Sử Dụng Provider

import 'package:provider/provider.dart';

class UserScreen extends StatelessWidget {
final int userId;

const UserScreen({Key? key, required this.userId}) : super(key: key);

@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => UserProvider(UserRepository())..loadUser(userId),
child: Consumer<UserProvider>(
builder: (context, provider, child) {
if (provider.isLoading) {
return Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}

if (provider.error != null) {
return Scaffold(
body: ErrorWidget(
error: provider.error!,
onRetry: () => provider.loadUser(userId),
),
);
}

if (provider.user == null) {
return Scaffold(
body: Center(child: Text('No data')),
);
}

return Scaffold(
appBar: AppBar(title: Text('User')),
body: UserDetailsWidget(user: provider.user!),
);
},
),
);
}
}

6️⃣ Caching và Auto Refresh

6.1 Caching với Riverpod

// Provider với cache
final cachedUserProvider = FutureProvider.family<User, int>((ref, userId) async {
final repository = ref.watch(userRepositoryProvider);

// Cache sẽ tự động được quản lý bởi Riverpod
return await repository.getUser(userId);
});

// Auto refresh khi dependency thay đổi
final userWithAutoRefreshProvider = FutureProvider.family<User, int>((ref, userId) async {
// Watch một provider khác để trigger refresh
ref.watch(refreshTriggerProvider);

final repository = ref.watch(userRepositoryProvider);
return await repository.getUser(userId);
});

6.2 Manual Refresh

class UserScreen extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final userAsync = ref.watch(userProvider(1));

return Scaffold(
appBar: AppBar(
title: Text('User'),
actions: [
IconButton(
icon: Icon(Icons.refresh),
onPressed: () {
// Invalidate và reload
ref.invalidate(userProvider(1));
},
),
],
),
body: userAsync.when(
data: (user) => UserDetailsWidget(user: user),
loading: () => Center(child: CircularProgressIndicator()),
error: (error, stack) => ErrorWidget(error: error),
),
);
}
}

7️⃣ Error Handling với Riverpod

7.1 Custom Error Handling

final userProvider = FutureProvider.family<User, int>((ref, userId) async {
try {
final repository = ref.watch(userRepositoryProvider);
return await repository.getUser(userId);
} on AppException catch (e) {
// Handle specific exceptions
throw e;
} catch (e) {
throw UnknownException('Failed to load user');
}
});

// Sử dụng
class UserScreen extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final userAsync = ref.watch(userProvider(1));

// Listen to errors
ref.listen(userProvider(1), (previous, next) {
next.whenOrNull(
error: (error, stack) {
if (error is AppException) {
ErrorHandler.handleError(error);
}
},
);
});

return userAsync.when(
data: (user) => UserDetailsWidget(user: user),
loading: () => CircularProgressIndicator(),
error: (error, stack) => ErrorWidget(error: error),
);
}
}

8️⃣ Ví Dụ Hoàn Chỉnh

8.1 Repository

class UserRepository {
final Dio dio;

UserRepository(this.dio);

Future<User> getUser(int id) async {
final response = await dio.get('/users/$id');
return User.fromJson(response.data as Map<String, dynamic>);
}

Future<List<User>> getUsers() async {
final response = await dio.get('/users');
return (response.data as List<dynamic>)
.map((json) => User.fromJson(json as Map<String, dynamic>))
.toList();
}

Future<User> createUser(User user) async {
final response = await dio.post('/users', data: user.toJson());
return User.fromJson(response.data as Map<String, dynamic>);
}
}

8.2 Providers

// API Service
final apiServiceProvider = Provider<Dio>((ref) {
return Dio(BaseOptions(baseUrl: 'https://api.example.com'));
});

// Repository
final userRepositoryProvider = Provider<UserRepository>((ref) {
final dio = ref.watch(apiServiceProvider);
return UserRepository(dio);
});

// User Provider
final userProvider = FutureProvider.family<User, int>((ref, userId) async {
final repository = ref.watch(userRepositoryProvider);
return await repository.getUser(userId);
});

// Users List Provider
final usersProvider = FutureProvider<List<User>>((ref) async {
final repository = ref.watch(userRepositoryProvider);
return await repository.getUsers();
});

8.3 UI

// User List Screen
class UserListScreen extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final usersAsync = ref.watch(usersProvider);

return Scaffold(
appBar: AppBar(
title: Text('Users'),
actions: [
IconButton(
icon: Icon(Icons.refresh),
onPressed: () => ref.invalidate(usersProvider),
),
],
),
body: usersAsync.when(
data: (users) => ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(users[index].name),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => UserScreen(userId: users[index].id),
),
);
},
);
},
),
loading: () => Center(child: CircularProgressIndicator()),
error: (error, stack) => ErrorWidget(
error: error,
onRetry: () => ref.invalidate(usersProvider),
),
),
);
}
}

// User Detail Screen
class UserScreen extends ConsumerWidget {
final int userId;

const UserScreen({Key? key, required this.userId}) : super(key: key);

@override
Widget build(BuildContext context, WidgetRef ref) {
final userAsync = ref.watch(userProvider(userId));

return Scaffold(
appBar: AppBar(title: Text('User')),
body: userAsync.when(
data: (user) => UserDetailsWidget(user: user),
loading: () => Center(child: CircularProgressIndicator()),
error: (error, stack) => ErrorWidget(
error: error,
onRetry: () => ref.invalidate(userProvider(userId)),
),
),
);
}
}

9️⃣ Best Practices

9.1 Tổ Chức Code

lib/
providers/
api_providers.dart
user_providers.dart
repositories/
user_repository.dart
models/
user.dart
screens/
user_screen.dart

9.2 Separation of Concerns

  • ✅ Repository: Xử lý API calls
  • ✅ Provider: Quản lý state
  • ✅ Widget: Hiển thị UI

9.3 Testing

// Test provider
void main() {
test('userProvider loads user correctly', () async {
final container = ProviderContainer();
final user = await container.read(userProvider(1).future);
expect(user.id, 1);
});
}

🔟 Kết Luận

Sử dụng Riverpod/Provider cho API state management giúp:

Code sạch hơn: Tách biệt logic và UI
Dễ test: Test providers độc lập
Caching tự động: Riverpod tự động cache
Auto dispose: Tự động cleanup
Type-safe: Compile-time safety

💡 Lời khuyên: Sử dụng Riverpod cho dự án mới. Nó mạnh mẽ hơn Provider và có nhiều tính năng tốt hơn. Provider vẫn tốt nếu bạn đã có codebase sử dụng nó.


🎓 Học Sâu Hơn Về Flutter

Muốn master Flutter, State Management, và các best practices? Tham gia các khóa học tại Hướng Nghiệp Dữ Liệu:

📚 Khóa Học Liên Quan:


📝 Bài viết này được biên soạn bởi đội ngũ Hướng Nghiệp Dữ Liệu. Để cập nhật thêm về Flutter, state management và các best practices trong phát triển ứng dụng di động, hãy theo dõi blog của chúng tôi.

Hướng Dẫn Upload Hình Lên Server Với Multipart (Dio)

· 11 min read

Upload hình ảnh là một tính năng phổ biến trong ứng dụng di động. Bài viết này sẽ hướng dẫn bạn cách upload hình ảnh lên server trong Flutter sử dụng Dio với Multipart, bao gồm chọn ảnh, compress, và theo dõi tiến trình upload.


1️⃣ Cài Đặt Dependencies

1.1 Thêm Packages

Thêm vào pubspec.yaml:

dependencies:
dio: ^5.4.0
image_picker: ^1.0.7
path_provider: ^2.1.1
image: ^4.1.3 # Cho compress image

Sau đó chạy:

flutter pub get

1.2 Cấu Hình Permissions

Android (android/app/src/main/AndroidManifest.xml)

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

iOS (ios/Runner/Info.plist)

<key>NSPhotoLibraryUsageDescription</key>
<string>App cần truy cập thư viện ảnh để chọn ảnh</string>
<key>NSCameraUsageDescription</key>
<string>App cần truy cập camera để chụp ảnh</string>

2.1 Sử Dụng Image Picker

import 'package:image_picker/image_picker.dart';
import 'dart:io';

class ImagePickerService {
final ImagePicker _picker = ImagePicker();

// Chọn ảnh từ gallery
Future<File?> pickImageFromGallery() async {
try {
final XFile? image = await _picker.pickImage(
source: ImageSource.gallery,
imageQuality: 85, // Chất lượng ảnh (0-100)
maxWidth: 1920, // Giới hạn kích thước
maxHeight: 1080,
);

if (image != null) {
return File(image.path);
}
return null;
} catch (e) {
print('Error picking image: $e');
return null;
}
}

// Chụp ảnh từ camera
Future<File?> pickImageFromCamera() async {
try {
final XFile? image = await _picker.pickImage(
source: ImageSource.camera,
imageQuality: 85,
maxWidth: 1920,
maxHeight: 1080,
);

if (image != null) {
return File(image.path);
}
return null;
} catch (e) {
print('Error taking picture: $e');
return null;
}
}

// Chọn nhiều ảnh
Future<List<File>> pickMultipleImages() async {
try {
final List<XFile> images = await _picker.pickMultiImage(
imageQuality: 85,
maxWidth: 1920,
maxHeight: 1080,
);

return images.map((xFile) => File(xFile.path)).toList();
} catch (e) {
print('Error picking multiple images: $e');
return [];
}
}
}

3️⃣ Compress Ảnh Trước Khi Upload

3.1 Compress Image Service

import 'dart:io';
import 'package:image/image.dart' as img;
import 'package:path_provider/path_provider.dart';

class ImageCompressor {
// Compress image và trả về file mới
static Future<File?> compressImage(File imageFile, {int quality = 85}) async {
try {
// Đọc file ảnh
final bytes = await imageFile.readAsBytes();
final image = img.decodeImage(bytes);

if (image == null) return null;

// Resize nếu cần (giữ tỷ lệ)
img.Image resizedImage;
if (image.width > 1920 || image.height > 1080) {
resizedImage = img.copyResize(
image,
width: image.width > image.height ? 1920 : null,
height: image.height > image.width ? 1080 : null,
maintainAspect: true,
);
} else {
resizedImage = image;
}

// Encode lại với chất lượng đã chỉ định
final compressedBytes = img.encodeJpg(resizedImage, quality: quality);

// Lưu vào temporary directory
final tempDir = await getTemporaryDirectory();
final compressedFile = File(
'${tempDir.path}/compressed_${DateTime.now().millisecondsSinceEpoch}.jpg',
);

await compressedFile.writeAsBytes(compressedBytes);

return compressedFile;
} catch (e) {
print('Error compressing image: $e');
return null;
}
}

// Get file size in MB
static Future<double> getFileSizeInMB(File file) async {
final bytes = await file.length();
return bytes / (1024 * 1024);
}
}

3.2 Sử Dụng Compressor

Future<File?> prepareImageForUpload(File originalImage) async {
// Kiểm tra kích thước file
final originalSize = await ImageCompressor.getFileSizeInMB(originalImage);
print('Original size: ${originalSize.toStringAsFixed(2)} MB');

// Nếu file > 2MB, compress
if (originalSize > 2.0) {
final compressedImage = await ImageCompressor.compressImage(
originalImage,
quality: 85,
);

if (compressedImage != null) {
final compressedSize = await ImageCompressor.getFileSizeInMB(compressedImage);
print('Compressed size: ${compressedSize.toStringAsFixed(2)} MB');
return compressedImage;
}
}

return originalImage;
}

4️⃣ Upload Ảnh Với Dio Multipart

4.1 Upload Service Cơ Bản

import 'package:dio/dio.dart';
import 'dart:io';

class ImageUploadService {
final Dio dio;

ImageUploadService(this.dio);

// Upload single image
Future<Map<String, dynamic>> uploadImage(
File imageFile, {
String? fileName,
Map<String, dynamic>? additionalData,
}) async {
try {
// Tạo FormData
final formData = FormData.fromMap({
'image': await MultipartFile.fromFile(
imageFile.path,
filename: fileName ?? 'image_${DateTime.now().millisecondsSinceEpoch}.jpg',
),
// Thêm các field khác nếu cần
if (additionalData != null) ...additionalData,
});

// Upload
final response = await dio.post(
'/upload/image',
data: formData,
);

return response.data as Map<String, dynamic>;
} catch (e) {
print('Error uploading image: $e');
rethrow;
}
}
}

4.2 Upload Với Progress Tracking

class ImageUploadService {
final Dio dio;

ImageUploadService(this.dio);

// Upload với progress callback
Future<Map<String, dynamic>> uploadImageWithProgress(
File imageFile, {
String? fileName,
Function(int sent, int total)? onProgress,
Map<String, dynamic>? additionalData,
}) async {
try {
final formData = FormData.fromMap({
'image': await MultipartFile.fromFile(
imageFile.path,
filename: fileName ?? 'image_${DateTime.now().millisecondsSinceEpoch}.jpg',
),
if (additionalData != null) ...additionalData,
});

final response = await dio.post(
'/upload/image',
data: formData,
onSendProgress: (sent, total) {
if (onProgress != null) {
onProgress(sent, total);
}
final progress = (sent / total * 100).toStringAsFixed(0);
print('Upload progress: $progress%');
},
);

return response.data as Map<String, dynamic>;
} catch (e) {
print('Error uploading image: $e');
rethrow;
}
}
}

4.3 Upload Multiple Images

Future<Map<String, dynamic>> uploadMultipleImages(
List<File> imageFiles, {
Function(int sent, int total)? onProgress,
Map<String, dynamic>? additionalData,
}) async {
try {
// Tạo list MultipartFile
final multipartFiles = await Future.wait(
imageFiles.asMap().entries.map((entry) async {
final index = entry.key;
final file = entry.value;
return await MultipartFile.fromFile(
file.path,
filename: 'image_$index.jpg',
);
}),
);

final formData = FormData.fromMap({
'images': multipartFiles, // Server sẽ nhận array
if (additionalData != null) ...additionalData,
});

final response = await dio.post(
'/upload/images',
data: formData,
onSendProgress: (sent, total) {
if (onProgress != null) {
onProgress(sent, total);
}
},
);

return response.data as Map<String, dynamic>;
} catch (e) {
print('Error uploading images: $e');
rethrow;
}
}

5️⃣ Ví Dụ Hoàn Chỉnh: Upload Service

import 'package:dio/dio.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';

class ImageUploadService {
final Dio dio;
final ImagePicker _picker = ImagePicker();

ImageUploadService(this.dio);

// Chọn và upload ảnh từ gallery
Future<UploadResult> pickAndUploadFromGallery({
Function(int sent, int total)? onProgress,
Map<String, dynamic>? additionalData,
bool compress = true,
}) async {
try {
// Chọn ảnh
final XFile? image = await _picker.pickImage(
source: ImageSource.gallery,
imageQuality: 85,
maxWidth: 1920,
maxHeight: 1080,
);

if (image == null) {
return UploadResult(
success: false,
error: 'Không có ảnh được chọn',
);
}

final imageFile = File(image.path);

// Compress nếu cần
File? fileToUpload = imageFile;
if (compress) {
fileToUpload = await ImageCompressor.compressImage(imageFile);
if (fileToUpload == null) {
fileToUpload = imageFile; // Fallback to original
}
}

// Upload
final result = await uploadImage(
fileToUpload!,
onProgress: onProgress,
additionalData: additionalData,
);

return UploadResult(
success: true,
data: result,
);
} catch (e) {
return UploadResult(
success: false,
error: e.toString(),
);
}
}

// Upload image file
Future<Map<String, dynamic>> uploadImage(
File imageFile, {
String? fileName,
Function(int sent, int total)? onProgress,
Map<String, dynamic>? additionalData,
}) async {
try {
final formData = FormData.fromMap({
'image': await MultipartFile.fromFile(
imageFile.path,
filename: fileName ?? 'image_${DateTime.now().millisecondsSinceEpoch}.jpg',
),
if (additionalData != null) ...additionalData,
});

final response = await dio.post(
'/upload/image',
data: formData,
onSendProgress: onProgress,
);

return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw UploadException(
message: e.message ?? 'Upload failed',
statusCode: e.response?.statusCode,
);
}
}

// Upload multiple images
Future<Map<String, dynamic>> uploadMultipleImages(
List<File> imageFiles, {
Function(int sent, int total)? onProgress,
Map<String, dynamic>? additionalData,
}) async {
try {
final multipartFiles = await Future.wait(
imageFiles.asMap().entries.map((entry) async {
final index = entry.key;
final file = entry.value;
return await MultipartFile.fromFile(
file.path,
filename: 'image_$index.jpg',
);
}),
);

final formData = FormData.fromMap({
'images': multipartFiles,
if (additionalData != null) ...additionalData,
});

final response = await dio.post(
'/upload/images',
data: formData,
onSendProgress: onProgress,
);

return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw UploadException(
message: e.message ?? 'Upload failed',
statusCode: e.response?.statusCode,
);
}
}
}

// Result class
class UploadResult {
final bool success;
final Map<String, dynamic>? data;
final String? error;

UploadResult({
required this.success,
this.data,
this.error,
});
}

// Custom exception
class UploadException implements Exception {
final String message;
final int? statusCode;

UploadException({required this.message, this.statusCode});

@override
String toString() => message;
}

6️⃣ UI Component: Upload Widget

6.1 Image Upload Widget

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'dart:io';

class ImageUploadWidget extends StatefulWidget {
final ImageUploadService uploadService;
final Function(String imageUrl)? onUploadSuccess;
final Function(String error)? onUploadError;

const ImageUploadWidget({
Key? key,
required this.uploadService,
this.onUploadSuccess,
this.onUploadError,
}) : super(key: key);

@override
_ImageUploadWidgetState createState() => _ImageUploadWidgetState();
}

class _ImageUploadWidgetState extends State<ImageUploadWidget> {
File? _selectedImage;
bool _isUploading = false;
double _uploadProgress = 0.0;

Future<void> _pickImage() async {
final result = await widget.uploadService.pickAndUploadFromGallery(
onProgress: (sent, total) {
setState(() {
_uploadProgress = sent / total;
});
},
compress: true,
);

if (result.success) {
setState(() {
_selectedImage = null; // Clear selected image
_isUploading = false;
_uploadProgress = 0.0;
});

final imageUrl = result.data?['url'] as String?;
if (imageUrl != null && widget.onUploadSuccess != null) {
widget.onUploadSuccess!(imageUrl);
}

ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Upload thành công!')),
);
} else {
setState(() {
_isUploading = false;
_uploadProgress = 0.0;
});

if (widget.onUploadError != null) {
widget.onUploadError!(result.error ?? 'Upload thất bại');
}

ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(result.error ?? 'Upload thất bại'),
backgroundColor: Colors.red,
),
);
}
}

Future<void> _selectImage() async {
final picker = ImagePicker();
final image = await picker.pickImage(
source: ImageSource.gallery,
imageQuality: 85,
);

if (image != null) {
setState(() {
_selectedImage = File(image.path);
});
}
}

Future<void> _uploadImage() async {
if (_selectedImage == null) return;

setState(() {
_isUploading = true;
_uploadProgress = 0.0;
});

try {
final result = await widget.uploadService.uploadImage(
_selectedImage!,
onProgress: (sent, total) {
setState(() {
_uploadProgress = sent / total;
});
},
);

setState(() {
_isUploading = false;
_uploadProgress = 0.0;
_selectedImage = null;
});

final imageUrl = result['url'] as String?;
if (imageUrl != null && widget.onUploadSuccess != null) {
widget.onUploadSuccess!(imageUrl);
}

ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Upload thành công!')),
);
} catch (e) {
setState(() {
_isUploading = false;
_uploadProgress = 0.0;
});

if (widget.onUploadError != null) {
widget.onUploadError!(e.toString());
}

ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Upload thất bại: ${e.toString()}'),
backgroundColor: Colors.red,
),
);
}
}

@override
Widget build(BuildContext context) {
return Column(
children: [
// Preview image
if (_selectedImage != null)
Container(
height: 200,
width: double.infinity,
margin: EdgeInsets.all(16),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(8),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.file(
_selectedImage!,
fit: BoxFit.cover,
),
),
),

// Progress indicator
if (_isUploading)
Padding(
padding: EdgeInsets.all(16),
child: Column(
children: [
LinearProgressIndicator(value: _uploadProgress),
SizedBox(height: 8),
Text(
'${(_uploadProgress * 100).toStringAsFixed(0)}%',
style: TextStyle(fontSize: 12),
),
],
),
),

// Buttons
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton.icon(
onPressed: _isUploading ? null : _selectImage,
icon: Icon(Icons.image),
label: Text('Chọn ảnh'),
),
SizedBox(width: 16),
if (_selectedImage != null)
ElevatedButton.icon(
onPressed: _isUploading ? null : _uploadImage,
icon: Icon(Icons.cloud_upload),
label: Text('Upload'),
),
],
),
],
);
}
}

7️⃣ Sử Dụng Với State Management (Riverpod)

7.1 Upload Provider

import 'package:flutter_riverpod/flutter_riverpod.dart';

final imageUploadServiceProvider = Provider<ImageUploadService>((ref) {
final dio = ref.watch(dioProvider);
return ImageUploadService(dio);
});

final uploadStateProvider = StateNotifierProvider<UploadNotifier, UploadState>((ref) {
final service = ref.watch(imageUploadServiceProvider);
return UploadNotifier(service);
});

class UploadState {
final File? selectedImage;
final bool isUploading;
final double progress;
final String? imageUrl;
final String? error;

UploadState({
this.selectedImage,
this.isUploading = false,
this.progress = 0.0,
this.imageUrl,
this.error,
});

UploadState copyWith({
File? selectedImage,
bool? isUploading,
double? progress,
String? imageUrl,
String? error,
}) {
return UploadState(
selectedImage: selectedImage ?? this.selectedImage,
isUploading: isUploading ?? this.isUploading,
progress: progress ?? this.progress,
imageUrl: imageUrl ?? this.imageUrl,
error: error,
);
}
}

class UploadNotifier extends StateNotifier<UploadState> {
final ImageUploadService service;

UploadNotifier(this.service) : super(UploadState());

Future<void> selectImage() async {
final picker = ImagePicker();
final image = await picker.pickImage(source: ImageSource.gallery);

if (image != null) {
state = state.copyWith(selectedImage: File(image.path));
}
}

Future<void> uploadImage() async {
if (state.selectedImage == null) return;

state = state.copyWith(isUploading: true, progress: 0.0, error: null);

try {
final result = await service.uploadImage(
state.selectedImage!,
onProgress: (sent, total) {
state = state.copyWith(progress: sent / total);
},
);

state = state.copyWith(
isUploading: false,
imageUrl: result['url'] as String?,
selectedImage: null,
);
} catch (e) {
state = state.copyWith(
isUploading: false,
error: e.toString(),
);
}
}
}

8️⃣ Best Practices

8.1 Compress Images

  • ✅ Luôn compress ảnh trước khi upload
  • ✅ Giới hạn kích thước (ví dụ: max 2MB)
  • ✅ Giữ chất lượng hợp lý (85-90%)

8.2 Error Handling

  • ✅ Xử lý lỗi network
  • ✅ Xử lý lỗi server
  • ✅ Hiển thị thông báo rõ ràng cho người dùng

8.3 Progress Tracking

  • ✅ Hiển thị progress bar
  • ✅ Cho phép cancel upload
  • ✅ Thông báo khi upload hoàn thành

8.4 Security

  • ✅ Validate file type
  • ✅ Validate file size
  • ✅ Sanitize file name

9️⃣ Kết Luận

Upload hình ảnh với Dio Multipart giúp bạn:

Upload dễ dàng: Sử dụng FormData và MultipartFile
Theo dõi tiến trình: Progress callback
Upload nhiều ảnh: Hỗ trợ multiple files
Compress ảnh: Giảm kích thước trước khi upload
Error handling: Xử lý lỗi tốt

💡 Lời khuyên: Luôn compress ảnh trước khi upload để tiết kiệm băng thông và thời gian. Sử dụng progress indicator để cải thiện trải nghiệm người dùng.


🎓 Học Sâu Hơn Về Flutter

Muốn master Flutter, File Upload, và các best practices? Tham gia các khóa học tại Hướng Nghiệp Dữ Liệu:

📚 Khóa Học Liên Quan:


📝 Bài viết này được biên soạn bởi đội ngũ Hướng Nghiệp Dữ Liệu. Để cập nhật thêm về Flutter, file upload và các best practices trong phát triển ứng dụng di động, hãy theo dõi blog của chúng tôi.

Xử Lý Lỗi API (401, 403, 500) và Hiển Thị Thông Báo Cho Người Dùng

· 11 min read

Xử lý lỗi API một cách chuyên nghiệp là yếu tố quan trọng để tạo trải nghiệm người dùng tốt. Bài viết này sẽ hướng dẫn bạn cách xử lý các lỗi API phổ biến và hiển thị thông báo thân thiện cho người dùng.


1️⃣ Các Loại Lỗi API Phổ Biến

1.1 HTTP Status Codes

Status CodeÝ NghĩaNguyên Nhân
400Bad RequestDữ liệu gửi lên không hợp lệ
401UnauthorizedChưa đăng nhập hoặc token hết hạn
403ForbiddenKhông có quyền truy cập
404Not FoundTài nguyên không tồn tại
500Internal Server ErrorLỗi server
502Bad GatewayGateway lỗi
503Service UnavailableService không khả dụng

1.2 Network Errors

  • Connection timeout
  • No internet connection
  • DNS resolution failed
  • SSL certificate error

2️⃣ Tạo Custom Exception Classes

2.1 Base Exception

abstract class AppException implements Exception {
final String message;
final int? statusCode;

AppException(this.message, [this.statusCode]);

@override
String toString() => message;
}

2.2 Specific Exceptions

// Bad Request (400)
class BadRequestException extends AppException {
BadRequestException([String? message])
: super(message ?? 'Yêu cầu không hợp lệ', 400);
}

// Unauthorized (401)
class UnauthorizedException extends AppException {
UnauthorizedException([String? message])
: super(message ?? 'Chưa đăng nhập hoặc phiên đăng nhập đã hết hạn', 401);
}

// Forbidden (403)
class ForbiddenException extends AppException {
ForbiddenException([String? message])
: super(message ?? 'Bạn không có quyền truy cập tài nguyên này', 403);
}

// Not Found (404)
class NotFoundException extends AppException {
NotFoundException([String? message])
: super(message ?? 'Không tìm thấy tài nguyên', 404);
}

// Server Error (500)
class ServerException extends AppException {
ServerException([String? message])
: super(message ?? 'Lỗi server. Vui lòng thử lại sau.', 500);
}

// Network Error
class NetworkException extends AppException {
NetworkException([String? message])
: super(message ?? 'Không có kết nối internet. Vui lòng kiểm tra lại.', null);
}

// Timeout
class TimeoutException extends AppException {
TimeoutException([String? message])
: super(message ?? 'Kết nối timeout. Vui lòng thử lại.', null);
}

// Unknown Error
class UnknownException extends AppException {
UnknownException([String? message])
: super(message ?? 'Đã xảy ra lỗi không xác định', null);
}

3️⃣ Xử Lý Lỗi Trong Dio Interceptor

3.1 Error Interceptor

import 'package:dio/dio.dart';

class ErrorInterceptor extends Interceptor {
@override
void onError(DioException err, ErrorInterceptorHandler handler) {
AppException exception;

switch (err.type) {
case DioExceptionType.connectionTimeout:
case DioExceptionType.sendTimeout:
case DioExceptionType.receiveTimeout:
exception = TimeoutException('Kết nối timeout. Vui lòng thử lại.');
break;

case DioExceptionType.badResponse:
final statusCode = err.response?.statusCode;
final message = _extractErrorMessage(err.response?.data);

switch (statusCode) {
case 400:
exception = BadRequestException(message);
break;
case 401:
exception = UnauthorizedException(message);
break;
case 403:
exception = ForbiddenException(message);
break;
case 404:
exception = NotFoundException(message);
break;
case 500:
case 502:
case 503:
exception = ServerException(message);
break;
default:
exception = ServerException('Lỗi server: $statusCode');
}
break;

case DioExceptionType.cancel:
exception = UnknownException('Request đã bị hủy');
break;

case DioExceptionType.unknown:
if (err.message?.contains('SocketException') ?? false) {
exception = NetworkException();
} else {
exception = UnknownException(err.message);
}
break;

default:
exception = UnknownException(err.message);
}

handler.reject(
DioException(
requestOptions: err.requestOptions,
error: exception,
type: err.type,
response: err.response,
),
);
}

String? _extractErrorMessage(dynamic data) {
if (data is Map<String, dynamic>) {
return data['message'] as String? ??
data['error'] as String?;
} else if (data is String) {
return data;
}
return null;
}
}

3.2 Sử Dụng Interceptor

final dio = Dio();

dio.interceptors.add(ErrorInterceptor());

// Khi gọi API, lỗi sẽ được map thành custom exception
try {
final response = await dio.get('/api/data');
} on DioException catch (e) {
if (e.error is AppException) {
final exception = e.error as AppException;
// Xử lý exception
_handleError(exception);
}
}

4️⃣ Error Handler Service

4.1 Centralized Error Handler

class ErrorHandler {
static void handleError(AppException exception) {
// Log error
_logError(exception);

// Show user-friendly message
_showErrorMessage(exception);
}

static void _logError(AppException exception) {
// Log to crashlytics, sentry, etc.
print('Error: ${exception.message} (${exception.statusCode})');
}

static void _showErrorMessage(AppException exception) {
// Get current context
final context = NavigationService.navigatorKey.currentContext;
if (context == null) return;

// Show snackbar
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(exception.message),
backgroundColor: _getErrorColor(exception),
duration: Duration(seconds: 3),
action: SnackBarAction(
label: 'Đóng',
textColor: Colors.white,
onPressed: () {},
),
),
);
}

static Color _getErrorColor(AppException exception) {
if (exception is UnauthorizedException) {
return Colors.orange;
} else if (exception is ForbiddenException) {
return Colors.red;
} else if (exception is ServerException) {
return Colors.red.shade700;
} else if (exception is NetworkException) {
return Colors.blue;
} else {
return Colors.grey;
}
}

// Get user-friendly message
static String getUserMessage(AppException exception) {
return exception.message;
}

// Check if error is retryable
static bool isRetryable(AppException exception) {
return exception is NetworkException ||
exception is TimeoutException ||
exception is ServerException;
}
}

5️⃣ Hiển Thị Thông Báo Lỗi Trong UI

5.1 Snackbar

void showErrorSnackbar(BuildContext context, AppException exception) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Row(
children: [
Icon(Icons.error_outline, color: Colors.white),
SizedBox(width: 12),
Expanded(
child: Text(
exception.message,
style: TextStyle(color: Colors.white),
),
),
],
),
backgroundColor: Colors.red,
duration: Duration(seconds: 4),
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
action: SnackBarAction(
label: 'Đóng',
textColor: Colors.white,
onPressed: () {},
),
),
);
}

5.2 Dialog

Future<void> showErrorDialog(
BuildContext context,
AppException exception, {
VoidCallback? onRetry,
}) async {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Row(
children: [
Icon(Icons.error_outline, color: Colors.red),
SizedBox(width: 8),
Text('Lỗi'),
],
),
content: Text(exception.message),
actions: [
if (onRetry != null && ErrorHandler.isRetryable(exception))
TextButton(
onPressed: () {
Navigator.of(context).pop();
onRetry();
},
child: Text('Thử lại'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Đóng'),
),
],
),
);
}

5.3 Custom Error Widget

class ErrorWidget extends StatelessWidget {
final AppException exception;
final VoidCallback? onRetry;

const ErrorWidget({
Key? key,
required this.exception,
this.onRetry,
}) : super(key: key);

@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
_getErrorIcon(),
size: 64,
color: Colors.red,
),
SizedBox(height: 16),
Text(
_getErrorTitle(),
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 8),
Text(
exception.message,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
),
),
if (onRetry != null && ErrorHandler.isRetryable(exception)) ...[
SizedBox(height: 24),
ElevatedButton.icon(
onPressed: onRetry,
icon: Icon(Icons.refresh),
label: Text('Thử lại'),
),
],
],
),
),
);
}

IconData _getErrorIcon() {
if (exception is NetworkException) {
return Icons.wifi_off;
} else if (exception is UnauthorizedException) {
return Icons.lock_outline;
} else if (exception is ServerException) {
return Icons.error_outline;
} else {
return Icons.warning_amber_rounded;
}
}

String _getErrorTitle() {
if (exception is NetworkException) {
return 'Không có kết nối';
} else if (exception is UnauthorizedException) {
return 'Phiên đăng nhập hết hạn';
} else if (exception is ServerException) {
return 'Lỗi server';
} else {
return 'Đã xảy ra lỗi';
}
}
}

6️⃣ Xử Lý Lỗi Trong Repository/Service

6.1 Repository với Error Handling

class UserRepository {
final Dio dio;

UserRepository(this.dio);

Future<User> getUser(int id) async {
try {
final response = await dio.get('/users/$id');
return User.fromJson(response.data as Map<String, dynamic>);
} on DioException catch (e) {
if (e.error is AppException) {
throw e.error as AppException;
}
throw UnknownException('Failed to get user');
}
}

Future<List<User>> getUsers() async {
try {
final response = await dio.get('/users');
return (response.data as List<dynamic>)
.map((json) => User.fromJson(json as Map<String, dynamic>))
.toList();
} on DioException catch (e) {
if (e.error is AppException) {
throw e.error as AppException;
}
throw UnknownException('Failed to get users');
}
}
}

6.2 Service với Error Handling

class ApiService {
final Dio dio;
final ErrorHandler errorHandler;

ApiService(this.dio, this.errorHandler);

Future<T> handleRequest<T>(
Future<Response> Function() request,
T Function(dynamic data) parser,
) async {
try {
final response = await request();
return parser(response.data);
} on DioException catch (e) {
if (e.error is AppException) {
final exception = e.error as AppException;
errorHandler.handleError(exception);
throw exception;
}
final exception = UnknownException('Request failed');
errorHandler.handleError(exception);
throw exception;
} catch (e) {
if (e is AppException) {
errorHandler.handleError(e);
}
rethrow;
}
}
}

7️⃣ Xử Lý Lỗi Trong Widget/UI

7.1 Sử Dụng FutureBuilder

class UserListWidget extends StatelessWidget {
final UserRepository userRepository;

const UserListWidget({Key? key, required this.userRepository}) : super(key: key);

@override
Widget build(BuildContext context) {
return FutureBuilder<List<User>>(
future: userRepository.getUsers(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}

if (snapshot.hasError) {
final error = snapshot.error;
if (error is AppException) {
return ErrorWidget(
exception: error,
onRetry: () {
// Retry logic
},
);
}
return ErrorWidget(
exception: UnknownException('Đã xảy ra lỗi'),
onRetry: () {
// Retry logic
},
);
}

if (snapshot.hasData) {
final users = snapshot.data!;
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return UserListItem(user: users[index]);
},
);
}

return SizedBox.shrink();
},
);
}
}

7.2 Sử Dụng try-catch trong Event Handler

class UserScreen extends StatefulWidget {
@override
_UserScreenState createState() => _UserScreenState();
}

class _UserScreenState extends State<UserScreen> {
final UserRepository userRepository = UserRepository(ApiService.dio);
User? user;
bool isLoading = false;
AppException? error;

@override
void initState() {
super.initState();
_loadUser();
}

Future<void> _loadUser() async {
setState(() {
isLoading = true;
error = null;
});

try {
final loadedUser = await userRepository.getUser(1);
setState(() {
user = loadedUser;
isLoading = false;
});
} on AppException catch (e) {
setState(() {
error = e;
isLoading = false;
});

// Show error message
ErrorHandler.handleError(e);
} catch (e) {
final exception = UnknownException('Đã xảy ra lỗi không xác định');
setState(() {
error = exception;
isLoading = false;
});
ErrorHandler.handleError(exception);
}
}

@override
Widget build(BuildContext context) {
if (isLoading) {
return Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}

if (error != null) {
return Scaffold(
body: ErrorWidget(
exception: error!,
onRetry: _loadUser,
),
);
}

if (user == null) {
return Scaffold(
body: Center(child: Text('Không có dữ liệu')),
);
}

return Scaffold(
appBar: AppBar(title: Text('User')),
body: UserDetailsWidget(user: user!),
);
}
}

8️⃣ Xử Lý 401 - Refresh Token

8.1 Refresh Token Interceptor

class RefreshTokenInterceptor extends Interceptor {
final Dio refreshDio;
final TokenService tokenService;

RefreshTokenInterceptor(this.refreshDio, this.tokenService);

@override
void onError(DioException err, ErrorInterceptorHandler handler) async {
if (err.response?.statusCode == 401) {
try {
// Refresh token
final newToken = await tokenService.refreshToken();

if (newToken != null) {
// Retry original request
final opts = err.requestOptions;
opts.headers['Authorization'] = 'Bearer $newToken';

final response = await refreshDio.request(
opts.path,
options: Options(
method: opts.method,
headers: opts.headers,
),
data: opts.data,
queryParameters: opts.queryParameters,
);

return handler.resolve(response);
} else {
// Refresh failed, logout
await tokenService.logout();
throw UnauthorizedException('Phiên đăng nhập đã hết hạn');
}
} catch (e) {
if (e is AppException) {
return handler.reject(
DioException(
requestOptions: err.requestOptions,
error: e,
),
);
}
}
}

return handler.next(err);
}
}

9️⃣ Best Practices

9.1 Centralized Error Handling

  • ✅ Tạo một ErrorHandler service duy nhất
  • ✅ Map tất cả lỗi thành custom exceptions
  • ✅ Log errors để debug
  • ✅ Hiển thị thông báo thân thiện với người dùng

9.2 User-Friendly Messages

  • ✅ Tránh technical jargon
  • ✅ Giải thích rõ ràng vấn đề
  • ✅ Đưa ra hướng giải quyết nếu có thể
  • ✅ Cung cấp nút "Thử lại" khi phù hợp

9.3 Error Logging

class ErrorLogger {
static void logError(AppException exception, {StackTrace? stackTrace}) {
// Log to console
print('Error: ${exception.message}');
if (stackTrace != null) {
print('Stack trace: $stackTrace');
}

// Log to crashlytics/sentry
// FirebaseCrashlytics.instance.recordError(exception, stackTrace);
}
}

🔟 Kết Luận

Xử lý lỗi API chuyên nghiệp giúp:

Trải nghiệm người dùng tốt hơn: Thông báo rõ ràng, dễ hiểu
Dễ debug: Log errors đầy đủ
Code sạch hơn: Xử lý lỗi tập trung
Maintainable: Dễ thêm/xóa/sửa error handling

💡 Lời khuyên: Luôn xử lý lỗi một cách graceful. Đừng để app crash vì lỗi API. Hãy hiển thị thông báo thân thiện và cho phép người dùng thử lại.


🎓 Học Sâu Hơn Về Flutter

Muốn master Flutter, Error Handling, và các best practices? Tham gia các khóa học tại Hướng Nghiệp Dữ Liệu:

📚 Khóa Học Liên Quan:


📝 Bài viết này được biên soạn bởi đội ngũ Hướng Nghiệp Dữ Liệu. Để cập nhật thêm về Flutter, error handling và các best practices trong phát triển ứng dụng di động, hãy theo dõi blog của chúng tôi.