flutter-backend-api-mapping
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFlutter-Backend API Mapping
Flutter-后端API映射
Problem
问题
Backend Python (SQLite) trả String cho ID fields (), frontend Dart model dùng . Cast sai → app crash.
"1"int后端Python(SQLite)为ID字段返回字符串类型(),前端Dart模型使用类型。类型转换错误→应用崩溃。
"1"intCommon mismatch patterns
常见不匹配模式
| Backend | Flutter Model | Fix |
|---|---|---|
| | |
| | |
| | Map field names explicitly |
| | Fallback |
| 后端 | Flutter模型 | 修复方案 |
|---|---|---|
| | |
| | |
| | 显式映射字段名称 |
| | 默认值设为 |
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ả hay
intcho ID?String - Field names khớp (vs
empId,idvsempName)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 - 字段名称是否匹配(vs
empId,idvsempName)name - 为所有字段处理空安全
- 数据缺失时设置默认值
- 测试登录→账户标签页显示正确名称