Flutter JSON转Floor实体类插件json_to_floor_entity的使用
Flutter JSON转Floor实体类插件json_to_floor_entity的使用
内容
Contents
Features
Feature | Status |
---|---|
Null safety | ✅ |
toJson/fromJson |
✅ |
@entity classes |
✅ |
copyWith generation |
✅ |
clone and deepclone | ✅ |
nested json classes | ✅ |
alter tables and field | ❌ |
INTEGER(int) support | ✅ |
REAL(num) support | ✅ |
TEXT(String) support | ✅ |
BLOB(Uint8List) support | ✅ |
Installation
在pubspec.yaml
文件中添加依赖:
dev_dependencies:
json_to_floor_entity: last_version
然后运行以下命令安装:
pub get
如果你使用的是VSCode或Android Studio,也可以通过工具直接安装。
What does this library do
这是一个命令行工具,用于将.json
文件转换为不可变的.dart
模型。
Get started
该命令会遍历你的.json
文件,查找可能的类型、变量名、导入路径、装饰器和类名,并将其写入模板中。
- 在项目根目录下创建一个名为
jsons
的目录(默认)。 - 将所有的
.json
文件复制到./jsons/
目录中。 - 运行以下命令:
或者指定源目录和输出目录:flutter pub run json_to_floor_entity
flutter pub run json_to_floor_entity -s assets/api_jsons -o lib/models
Examples
Input
假设我们有两个JSON文件:product.json
和employee.json
。
product.json
{
"id": "123",
"caseId?": "123",
"startDate?": "2020-08-08",
"endDate?": "2020-10-10",
"placementDescription?": "Description string"
}
employee.json
{
"id": "123",
"displayName?": "Jan Jansen",
"@ignore products?": "$[]product"
}
Output
这将生成以下两个Dart文件:product.dart
和employee.dart
。
product.dart
import 'package:floor/floor.dart';
@Entity(tableName: 'product')
class Product {
const Product({
required this.id,
this.caseId,
this.startDate,
this.endDate,
this.placementDescription,
});
@PrimaryKey(autoGenerate: true)
final int id;
final String? caseId;
final String? startDate;
final String? endDate;
final String? placementDescription;
factory Product.fromJson(Map<String, dynamic> json) => Product(
id: json['id'] as String,
caseId: json['caseId'] != null ? json['caseId'] as String : null,
startDate: json['startDate'] != null ? json['startDate'] as String : null,
endDate: json['endDate'] != null ? json['endDate'] as String : null,
placementDescription: json['placementDescription'] != null ? json['placementDescription'] as String : null
);
Map<String, dynamic> toJson() => {
'id': id,
'caseId': caseId,
'startDate': startDate,
'endDate': endDate,
'placementDescription': placementDescription
};
Product clone() => Product(
id: id,
caseId: caseId,
startDate: startDate,
endDate: endDate,
placementDescription: placementDescription
);
Product copyWith({
int? id,
String? caseId,
String? startDate,
String? endDate,
String? placementDescription
}) => Product(
id: id ?? this.id,
caseId: caseId ?? this.caseId,
startDate: startDate ?? this.startDate,
endDate: endDate ?? this.endDate,
placementDescription: placementDescription ?? this.placementDescription,
);
@override
bool operator ==(Object other) => identical(this, other)
|| other is Product && id == other.id && caseId == other.caseId && startDate == other.startDate && endDate == other.endDate && placementDescription == other.placementDescription;
@override
int get hashCode => id.hashCode ^ caseId.hashCode ^ startDate.hashCode ^ endDate.hashCode ^ placementDescription.hashCode;
}
employee.dart
import 'package:floor/floor.dart';
import 'product.dart';
@Entity(tableName: 'employee')
class Employee {
const Employee({
required this.id,
this.displayName,
this.products,
});
@PrimaryKey(autoGenerate: true)
final int id;
final String? displayName;
final List<Product>? products;
factory Employee.fromJson(Map<String, dynamic> json) => Employee(
id: json['id'] as String,
displayName: json['displayName'] != null ? json['displayName'] as String : null
);
Map<String, dynamic> toJson() => {
'id': id,
'displayName': displayName
};
Employee clone() => Employee(
id: id,
displayName: displayName,
products: products?.map((e) => e.clone()).toList()
);
Employee copyWith({
int? id,
String? displayName,
List<Product>? products
}) => Employee(
id: id ?? this.id,
displayName: displayName ?? this.displayName,
products: products ?? this.products,
);
@override
bool operator ==(Object other) => identical(this, other)
|| other is Employee && id == other.id && displayName == other.displayName && products == other.products;
@override
int get hashCode => id.hashCode ^ displayName.hashCode ^ products.hashCode;
}
Create a DAO (Data Access Object)
DAO负责管理对底层SQLite数据库的访问。可以通过以下方式自动生成DAO:
import 'package:floor/floor.dart';
@dao
abstract class NewsDao {
@Query('SELECT * FROM News')
Future<List<News>> findAll();
@Query('SELECT * FROM News WHERE id = :id')
Future<News?> findById(int id);
@insert
Future<void> add(News entity);
@insert
Future<void> addList(List<News> entities);
@update
Future<void> edit(News entity);
@update
Future<void> editList(List<News> entities);
@delete
Future<void> remove(News entity);
@delete
Future<void> removeList(List<News> entities);
}
这些文件在创建后不会被删除或更新。
Create the Database
数据库必须是一个扩展了FloorDatabase
的抽象类。可以自动生成DAO:
// database.dart
// 必需的包导入
import 'dart:async';
import 'package:floor/floor.dart';
import 'package:sqflite/sqflite.dart' as sqflite;
import 'dao/person_dao.dart';
import 'entity/person.dart';
part 'database.g.dart'; // 生成的代码将在此处
@Database(version: 1, entities: [Person])
abstract class AppDatabase extends FloorDatabase {
PersonDao get personDao;
}
Getting started
- 在项目根目录下创建一个名为
jsons
的目录(默认)。 - 将所有JSON文件放入
jsons
目录中。 - 运行以下命令:
或者指定源目录和输出目录:pub run json_to_floor_entity
flutter pub run json_to_floor_entity -s assets/api_jsons -o lib/models
- 运行以下命令生成代码:
flutter packages pub run build_runner build
更多关于Flutter JSON转Floor实体类插件json_to_floor_entity的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter JSON转Floor实体类插件json_to_floor_entity的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
json_to_floor_entity
是一个用于在 Flutter 项目中自动生成 Floor 数据库实体类的插件。它可以根据 JSON 数据生成对应的 Dart 实体类,并且这些实体类可以直接用于 Floor 数据库操作。
安装插件
首先,你需要在 pubspec.yaml
文件中添加 json_to_floor_entity
插件的依赖:
dev_dependencies:
json_to_floor_entity: ^1.0.0
然后运行 flutter pub get
来安装插件。
使用插件
-
准备 JSON 数据:首先,你需要准备一个 JSON 文件或 JSON 字符串,该文件将用于生成实体类。
例如,假设你有以下 JSON 数据:
{ "id": 1, "name": "John Doe", "email": "john.doe@example.com", "age": 30 }
-
生成实体类:使用
json_to_floor_entity
插件生成实体类。你可以通过命令行工具来生成实体类。假设你的 JSON 文件名为
user.json
,你可以运行以下命令:flutter pub run json_to_floor_entity:generate -i user.json -o lib/models/user.dart
其中:
-i
指定输入的 JSON 文件路径。-o
指定生成的 Dart 文件路径。
-
生成的实体类:生成的 Dart 文件将包含一个 Floor 实体类。例如:
import 'package:floor/floor.dart'; [@entity](/user/entity) class User { @primaryKey final int id; final String name; final String email; final int age; User({ required this.id, required this.name, required this.email, required this.age, }); factory User.fromJson(Map<String, dynamic> json) => User( id: json['id'], name: json['name'], email: json['email'], age: json['age'], ); Map<String, dynamic> toJson() => { 'id': id, 'name': name, 'email': email, 'age': age, }; }
-
使用生成的实体类:你可以在你的 Flutter 项目中使用生成的实体类来进行数据库操作。例如,你可以使用 Floor 数据库库来创建、读取、更新和删除(CRUD)操作。
import 'package:floor/floor.dart'; import 'package:floor_demo/models/user.dart'; [@dao](/user/dao) abstract class UserDao { @Query('SELECT * FROM User') Future<List<User>> findAllUsers(); @insert Future<void> insertUser(User user); @update Future<void> updateUser(User user); @delete Future<void> deleteUser(User user); }
-
配置数据库:最后,你需要在你的 Flutter 项目中配置 Floor 数据库。
import 'package:floor/floor.dart'; import 'package:floor_demo/models/user.dart'; import 'package:floor_demo/dao/user_dao.dart'; part 'app_database.g.dart'; // 生成的代码文件 [@Database](/user/Database)(version: 1, entities: [User]) abstract class AppDatabase extends FloorDatabase { UserDao get userDao; }