| XÂY DỰNG ỨNG DỤNG MẪU HOÀN CHỈNH VỚI FLUTTER

Được viết bởi thanhdt vào ngày 28/11/2025 lúc 21:30 | 159 lượt xem

XÂY DỰNG ỨNG DỤNG MẪU HOÀN CHỈNH VỚI FLUTTER

Login – API – CRUD – Upload ảnh – Repository – State Management

https://docs.flutter.dev/assets/images/docs/arch-overview/archdiagram.png
https://raw.githubusercontent.com/khaledsawan/clean_architecture_flutter/main/architecture-proposal.png
https://touchlane.com/wp-content/uploads/2025/07/1_SC3qhGfa7gNjpP_BX1MYXw.webp

Bài này mô tả quy trình xây dựng một ứng dụng Flutter hoàn chỉnh, phù hợp cho dự án thực tế hoặc sản phẩm MVP. Ứng dụng bao gồm:

  • Đăng nhập bằng API
  • Lưu token
  • Lấy danh sách dữ liệu (Users, Products, Posts…)
  • CRUD dữ liệu
  • Upload ảnh
  • State management
  • Repository pattern
  • Tách tầng Clean Architecture

1. PHÂN TÍCH ỨNG DỤNG MẪU

Ứng dụng mẫu có các module:

  1. Màn hình Login
  2. Màn hình Dashboard
  3. Danh sách Items
  4. Chi tiết Item
  5. Tạo – Sửa – Xóa Item (CRUD)
  6. Upload ảnh
  7. Quản lý token & bảo mật
  8. Routing
  9. State Management (Riverpod hoặc Bloc)
https://repository-images.githubusercontent.com/213185926/271cee00-6346-11eb-8b41-a7cf60ed3e44
https://i.ytimg.com/vi/_uOgXpEHNbc/maxresdefault.jpg
https://miro.medium.com/1%2AxvCsoq7iYcznw1Xy5A8Jng.png

2. CẤU TRÚC DỰ ÁN

Cấu trúc đề xuất:

lib/
 ├── core/
 │    ├── error/
 │    ├── network/
 │    └── utils/
 ├── data/
 │    ├── models/
 │    ├── datasources/
 │    └── repositories/
 ├── domain/
 │    ├── entities/
 │    └── usecases/
 └── presentation/
      ├── login/
      ├── dashboard/
      ├── items/
      └── widgets/

3. MODULE LOGIN (API + TOKEN + SECURE STORAGE)

https://i.ytimg.com/vi/6kaEbTfb444/maxresdefault.jpg
https://miro.medium.com/v2/resize%3Afit%3A1200/1%2A-TvhhRoAomLjG0gy0Jo8xA.jpeg

API Login (POST)

POST /auth/login
{
  "email": "user@example.com",
  "password": "123456"
}

Backend trả về:

{
  "token": "jwt_token_here",
  "user": { "id": 1, "name": "Thanh" }
}

Flutter gọi API

Dùng Dio:

final response = await dio.post(
  "/auth/login",
  data: {"email": email, "password": password},
);

Lưu token

Dùng flutter_secure_storage:

await storage.write(key: "token", value: response.data['token']);

Tự động thêm token vào mọi request

dio.interceptors.add(
  InterceptorsWrapper(
    onRequest: (options, handler) async {
      final token = await storage.read(key: "token");
      if (token != null) {
        options.headers["Authorization"] = "Bearer $token";
      }
      return handler.next(options);
    },
  ),
);

4. MODULE LIST + DETAIL (READ DATA)

https://i.ytimg.com/vi/1OEhIpBIZXM/maxresdefault.jpg
https://i.ytimg.com/vi/EED7eWhXoc8/maxresdefault.jpg

API

GET /items
GET /items/:id

Flutter

Dùng FutureProvider (Riverpod):

final itemsProvider = FutureProvider<List<Item>>((ref) {
  return ref.read(itemRepositoryProvider).getItems();
});

Trong UI:

ref.watch(itemsProvider).when(
  data: (items) => ListView.builder(
    itemCount: items.length,
    itemBuilder: (_, i) => ListTile(
      title: Text(items[i].name),
    ),
  ),
  loading: () => CircularProgressIndicator(),
  error: (_, __) => Text("Error"),
);

5. MODULE CREATE – UPDATE – DELETE (CRUD)

https://fluttergems.dev/media-cards/gsform.png
https://i.sstatic.net/gFC1l.png
https://s3-ap-southeast-1.amazonaws.com/djamblog/article-100820064531.png

API

POST /items
PUT /items/:id
DELETE /items/:id

Flutter: Form Data

await dio.post("/items", data: {
  "name": nameController.text,
  "description": descController.text,
});

Sửa:

await dio.put("/items/$id", data: updatedData);

Xóa:

await dio.delete("/items/$id");

6. MODULE UPLOAD ẢNH

https://i.sstatic.net/59OUS.gif
https://i.sstatic.net/Wben4.png

Chọn ảnh từ thư viện

Dùng image_picker:

final image = await ImagePicker().pickImage(source: ImageSource.gallery);

Upload ảnh

final formData = FormData.fromMap({
  "file": await MultipartFile.fromFile(image.path),
});

await dio.post("/items/$id/upload", data: formData);

Backend trả URL → hiển thị

Image.network(item.imageUrl);

7. ROUTING & FLOW ỨNG DỤNG

https://docs.flutter.dev/assets/images/docs/app-architecture/guide/feature-architecture-simplified-Data-highlighted.png
https://www.researchgate.net/publication/325015573/figure/fig2/AS%3A624009939017734%401525786971434/Flow-Chart-of-Flutter-Test.png

Routing đề xuất:

  • /login
  • /dashboard
  • /items
  • /items/create
  • /items/:id
  • /items/:id/edit

Dùng go_router hoặc Navigator 2.0.


8. STATE MANAGEMENT CHO ỨNG DỤNG MẪU

Sử dụng Riverpod hoặc Bloc để quản lý:

  • Trạng thái loading
  • Error
  • Data
  • Action (create/update/delete)

Ví dụ với StateNotifier:

class ItemController extends StateNotifier<ItemState> {
  ItemController(this.repo) : super(ItemInitial());

  Future<void> createItem(ItemData data) async {
    state = ItemLoading();
    try {
      await repo.createItem(data);
      state = ItemSuccess();
    } catch (_) {
      state = ItemError();
    }
  }
}

9. DEPLOY ỨNG DỤNG

https://miro.medium.com/1%2AMeF0AF25h9OxYYLoJh5ZLw.jpeg
https://docs.flutter.dev/assets/images/docs/arch-overview/archdiagram.png

Android:

flutter build apk
flutter build appbundle

iOS:

flutter build ios --release

Web:

flutter build web

Có thể deploy lên:

  • Firebase Hosting
  • Vercel
  • Hostinger (upload folder build/web)

10. TỔNG KẾT QUY TRÌNH XÂY DỰNG ỨNG DỤNG

  1. Phân tích cấu trúc
  2. Login + Token
  3. Repository + Model
  4. Fetch data (List/Detail)
  5. CRUD
  6. Upload ảnh
  7. Routing
  8. State management
  9. Deploy

Quy trình này là tiêu chuẩn cho mọi ứng dụng Flutter có backend.


THAM CHIẾU – TÀI LIỆU FLUTTER

Toàn bộ tài nguyên và lộ trình học Flutter bạn có thể xem tại:

https://www.huongnghieplaptrinhflutter.com
Thành ĐT

Thành ĐT

Founder & Chief Technology Officer, HNDL
1.313 Bài viết
15.4k Người theo dõi
120k+ Lượt đọc

Chuyên gia với hơn 10 năm kinh nghiệm trong phát triển hệ thống giao dịch tự động (Trading Bot), Fintech, Mobile App và phân tích dữ liệu tài chính (Quantitative Analysis). Người sáng lập và trực tiếp dẫn dắt các khóa học thực chiến tại Hướng Nghiệp Dữ Liệu.