flutter-backend-api-mapping

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Flutter-Backend API Mapping

Flutter-后端API映射

Problem

问题

Backend Python (SQLite) trả String cho ID fields (
"1"
), frontend Dart model dùng
int
. Cast sai → app crash.
后端Python(SQLite)为ID字段返回字符串类型(
"1"
),前端Dart模型使用
int
类型。类型转换错误→应用崩溃。

Common mismatch patterns

常见不匹配模式

BackendFlutter ModelFix
"empId": "1"
(String)
int id
int.tryParse(data['empId']) ?? 0
"empId": 1
(Integer)
int id
data['empId'] as int
"empName"
field
name
field
Map field names explicitly
initial
null missing
initial
required
Fallback
"?"
hoặc
"M"
后端Flutter模型修复方案
"empId": "1"
(字符串)
int id
int.tryParse(data['empId']) ?? 0
"empId": 1
(整数)
int id
data['empId'] as int
"empName"
字段
name
字段
显式映射字段名称
initial
字段缺失且为null
initial
为必填项
默认值设为
"?"
"M"

Safe Session.fromJson

安全的Session.fromJson实现

dart
factory Session.fromJson(Map<String, dynamic> json) {
  // ID: SQLite trả String sometimes
  final rawId = json['empId'] ?? json['id'] ?? 0;
  final id = rawId is int 
    ? rawId 
    : int.tryParse(rawId.toString()) ?? 0;

  // Name: có fallback khi rỗng
  final name = (json['empName'] ?? json['name'] ?? '') as String;

  // Nested employee object
  final emp = json['employee'] as Map<String, dynamic>?;

  return Session(
    id: id,
    name: name.isEmpty ? 'Mới' : name,
    initial: emp?['initial'] as String? ?? json['initial'] as String?,
    colorIdx: emp?['color_idx'] as int? ?? json['color_idx'] as int?,
    role: json['role'] as String? ?? 'employee',
  );
}
dart
factory Session.fromJson(Map<String, dynamic> json) {
  // ID: SQLite有时会返回字符串
  final rawId = json['empId'] ?? json['id'] ?? 0;
  final id = rawId is int 
    ? rawId 
    : int.tryParse(rawId.toString()) ?? 0;

  // 名称:为空时设置默认值
  final name = (json['empName'] ?? json['name'] ?? '') as String;

  // 嵌套的employee对象
  final emp = json['employee'] as Map<String, dynamic>?;

  return Session(
    id: id,
    name: name.isEmpty ? 'Mới' : name,
    initial: emp?['initial'] as String? ?? json['initial'] as String?,
    colorIdx: emp?['color_idx'] as int? ?? json['color_idx'] as int?,
    role: json['role'] as String? ?? 'employee',
  );
}

Checklist

检查清单

  • Backend trả
    int
    hay
    String
    cho ID?
  • Field names khớp (
    empId
    vs
    id
    ,
    empName
    vs
    name
    )
  • Null safety cho mọi field
  • Fallback khi data missing
  • Test login → tab Tài khoản hiện tên chính xác
  • 后端返回的ID是
    int
    还是
    String
    类型?
  • 字段名称是否匹配(
    empId
    vs
    id
    empName
    vs
    name
  • 为所有字段处理空安全
  • 数据缺失时设置默认值
  • 测试登录→账户标签页显示正确名称