Realm 含义:
Realm 是一个可以直接在手机、平板电脑或可穿戴设备上运行的数据库。
Realm 基本类型:
int:整数
double:浮点数
bool:布尔值
String:字符串
DateTime:日期和时间
Uint8List:字节数组
Realm集合:
一个realm集合包含零个或者多个Realm支持的数据类型的实例。在Realm集合中,集合中的对象均为同一类型。
Realm具有以下类型的集合:
RealmList
RealmSet(不能直接用于Flutter,使用RealmList代替)
RealmRestults(flutter 使用realm.query<>()函数代替)
realm入门:
导入realm 相关包:
使用 flutter 命令方式:
flutter pub add realm
flutter pub add realm-generate
在项目的 pubspec.yaml 中,添加以下代码:
dependencies:
realm:^20.0.1
使用
flutter pub get
命令下载 realm 包。
下载完成 realm 相关包后,创建一个user.dart
import 'package: realm/realm.dart'// 导入 realm 包
part ‘app.realm.dart’ //声明 part 文件
() //定义一个名为 _User 的数据模型类
class _User {
()
late ObjectId id;
late String name;
late int age;
}
使用realm_generator包,使用 数据模型类_User 生成 RrealmObject 类 User,使用命令为:
dart run realm generate
realm 的用法:
打开 Realm:
var config = Configuration.local([User.schema]);//创建配置对象User
var realm = Realm(config);//打开Real
m
关闭 Realm:
realm.close();
添加 User 数据:
var user = User("user1",22);
realm.write((){
realm.add(user);
});
查询并修改 User 数据:
var users = realm.all<User>();
User myUser = User[0];// 使用索引的方式
print("My name is ${myUser.name} and age is ${myUser.age}");
users = realm.all<User>().query("name = 'user1'"); //通过query 方法进行查询
realm.write((){
myUser.name("user2"),
myUser.age("23"),
});
删除 User 数据:
var users = realm.all<User>();
User myUser = User[0];
realm.write((){
realm.delete(myUser),
})
realm 完整案例:
添加 realm 包到flutter应用:
flutter pub add realm
创建一个commodity.dart文件。
import 'package: realm/realm.dart'// 导入 realm 包
part ‘commodity.realm.dart’ //声明 part 文件
() //定义一个名为 _Commodity 的数据模型类
class _Commodity{
()
late ObjectId id;
late String name;
late int price;
}
添加 realm_genertor 包到flutter 应用:
flutter pub run realm_genertor
添加完成 realm_genertor 包
dart run realm generate
编写commoditiy_page.dart 文件
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:realm/realm.dart';
import 'package:rivierpod_test/realm/commodity.dart';
final realmProvider = Provider<Realm>((ref) {
final config = Configuration.local([Commodity.schema]);
return Realm(config);
});
class CommodityPage extends HookConsumerWidget {
const CommodityPage({super.key});
Widget build(BuildContext context, WidgetRef ref) {
final realm = ref.watch(realmProvider);
final commodities = useState<List<Commodity>>(realm.all<Commodity>().toList());
// 增
void addCommodity() {
final commodity = Commodity(ObjectId(), 'New Commodity', 100);
realm.write(() => realm.add(commodity));
commodities.value = realm.all<Commodity>().toList();
}
// 改
void updateCommodity(Commodity commodity, String newName, int newPrice) {
realm.write(() {
commodity.name = newName;
commodity.price = newPrice;
});
commodities.value = realm.all<Commodity>().toList();
}
// 删
void deleteCommodity(Commodity commodity) {
realm.write(() => realm.delete(commodity));
commodities.value = realm.all<Commodity>().toList();
}
return Scaffold(
appBar: AppBar(title: const Text('realm example')),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: commodities.value.length,
itemBuilder: (context, index) {
final commodity = commodities.value[index];
return ListTile(
title: Text(commodity.name),
subtitle: Text('\$${commodity.price}'),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
// 编辑按钮
IconButton(
icon: const Icon(Icons.edit),
onPressed: () {
showDialog(
context: context,
builder: (context) {
final nameController = TextEditingController(text: commodity.name);
final priceController = TextEditingController(text: commodity.price.toString());
return SimpleDialog(
title: const Text('Edit Commodity'),
children: [
TextField(controller: nameController, decoration: const InputDecoration(labelText: 'Name')),
TextField(controller: priceController, decoration: const InputDecoration(labelText: 'Price'), keyboardType: TextInputType.number),
TextButton(
onPressed: () {
final newName = nameController.text;
final newPrice = int.tryParse(priceController.text) ?? commodity.price;
updateCommodity(commodity, newName, newPrice);
Navigator.pop(context);
},
child: const Text('Save'),
),
],
);
},
);
},
),
// 删除按钮
IconButton(
icon: const Icon(Icons.delete),
onPressed: () => deleteCommodity(commodity),
),
],
),
);
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: addCommodity,
child: const Text('Add Commodity'),
),
),
],
),
);
}
}
结果如下: