Flutter 插件flamingo的使用_Flamingo 是一个基于 Firebase Firestore 的模型框架库
Flutter 插件flamingo的使用_Flamingo 是一个基于 Firebase Firestore 的模型框架库
简介
Flamingo 是一个基于 Firebase Firestore 的模型框架库。它简化了与 Firestore 交互的过程,并提供了多种实用功能如 CRUD 操作、分页、事务处理等。
安装
在 pubspec.yaml
文件中添加以下依赖:
dependencies:
flamingo:
flamingo_annotation:
dev_dependencies:
build_runner:
flamingo_generator:
设置
请参考 cloud_firestore 设置文档进行初始设置。
使用
初始化
在 main.dart
中添加初始化代码:
import 'package:flamingo/flamingo.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Flamingo.initializeApp();
runApp(MyApp());
}
创建模型
创建继承自 Document
的类,并实现 JSON 映射代码。可以使用 flamingo_generator
自动生成映射代码。
import 'package:flamingo/flamingo.dart';
import 'package:flamingo_annotation/flamingo_annotation.dart';
part 'user.flamingo.dart';
class User extends Document<User> {
User({
String? id,
DocumentSnapshot<Map<String, dynamic>>? snapshot,
Map<String, dynamic>? values,
}) : super(id: id, snapshot: snapshot, values: values);
@Field()
String? name;
@override
Map<String, dynamic> toData() => _$toData(this);
@override
void fromData(Map<String, dynamic> data) => _$fromData(this, data);
}
执行以下命令生成数据映射代码:
flutter pub run build_runner build
CRUD 操作
使用 DocumentAccessor
或 Batch
或 Transaction
进行 CRUD 操作。
final user = User()
..name = 'hoge';
final documentAccessor = DocumentAccessor();
// 保存
await documentAccessor.save(user);
// 更新
await documentAccessor.update(user);
// 删除
await documentAccessor.delete(user);
// 批量操作
final batch = Batch()
..save(user)
..update(user);
..delete(user);
await batch.commit();
分页查询
使用 CollectionPaging
和 CollectionPagingListener
实现分页和监听功能。
final collectionPaging = CollectionPaging<User>(
query: User().collectionRef.orderBy('createdAt', descending: true),
limit: 20,
decode: (snap) => User(snapshot: snap),
);
// 加载
List<User> items = await collectionPaging.load();
// 加载更多
final _items = await collectionPaging.loadMore();
items.addAll(_items);
快照监听
监听文档快照的变化。
// 监听
final user = User(id: '0')
..name = 'hoge';
final dispose = user.reference.snapshots().listen((snap) {
final user = User(snapshot: snap);
print('${user.id}, ${user.name}');
});
// 保存、更新、删除
DocumentAccessor documentAccessor = DocumentAccessor();
await documentAccessor.save(user);
user.name = 'fuga';
await documentAccessor.update(user);
await documentAccessor.delete(user);
await dispose.cancel();
子集合
示例:排名文档具有计数子集合。
// 排名模型
class Ranking extends Document<Ranking> {
Ranking(
{String? id,
DocumentSnapshot<Map<String, dynamic>>? snapshot,
Map<String, dynamic>? values,
CollectionReference<Map<String, dynamic>>? collectionRef})
: super(
id: id,
snapshot: snapshot,
values: values,
collectionRef: collectionRef) {
count = Collection(this, RankingKey.count.value);
}
@Field()
String? title;
@SubCollection()
late Collection<Count> count;
@override
Map<String, dynamic> toData() => _$toData(this);
@override
void fromData(Map<String, dynamic> data) => _$fromData(this, data);
}
// 计数模型
class Count extends Document<Count> {
Count({
String? id,
DocumentSnapshot<Map<String, dynamic>>? snapshot,
Map<String, dynamic>? values,
CollectionReference<Map<String, dynamic>>? collectionRef,
}) : super(
id: id,
snapshot: snapshot,
values: values,
collectionRef: collectionRef);
@Field()
String? userId;
@Field()
int count = 0;
@override
Map<String, dynamic> toData() => _$toData(this);
@override
void fromData(Map<String, dynamic> data) => _$fromData(this, data);
}
保存和获取子集合
final ranking = Ranking(id: '20201007')
..title = 'userRanking';
// 保存子集合
final countA = Count(collectionRef: ranking.count.ref)
..userId = '0'
..count = 10;
final countB = Count(collectionRef: ranking.count.ref)
..userId = '1'
..count = 100;
final batch = Batch()
..save(ranking)
..save(countA)
..save(countB);
await batch.commit();
// 获取子集合
final path = ranking.count.ref.path;
final snapshot = await firestoreInstance.collection(path).get();
final list = snapshot.docs.map((item) => Count(snapshot: item)).toList()
..forEach((count) {
print(count);
});
文件操作
可以对 Firebase Storage 进行文件上传和删除操作。
final post = Post();
final storage = Storage();
final file = ... // 加载图片。
// 获取上传器流
storage.fetch();
// 检查状态
storage.uploader.listen((data){
print('total: ${data.totalBytes} transferred: ${data.bytesTransferred}');
});
// 上传文件到 Firebase Storage 并保存文件元数据到 Firestore
final path = '${post.documentPath}/${PostKey.file.value}';
post.file = await storage.save(path, file, mimeType: mimeTypePng, metadata: {'newPost': 'true'});
await documentAccessor.save(post);
// 处理上传器流
storage.dispose();
增量操作
示例:信用卡文档具有积分和分数字段,这些字段是增量类型。
class CreditCard extends Document<CreditCard> {
CreditCard({
String? id,
DocumentSnapshot<Map<String, dynamic>>? snapshot,
Map<String, dynamic>? values,
}) : super(id: id, snapshot: snapshot, values: values);
@Field()
Increment<int> point = Increment<int>();
@Field()
Increment<double> score = Increment<double>();
@override
Map<String, dynamic> toData() => _$toData(this);
@override
void fromData(Map<String, dynamic> data) => _$fromData(this, data);
/// 在创建、更新、删除后调用。
@override
void onCompleted(ExecuteType executeType) {
point = point.onRefresh();
score = score.onRefresh();
}
}
增量和递减数据
// 增量
final card = CreditCard()
..point.incrementValue = 1
..score.incrementValue = 1.25;
await documentAccessor.save(card);
print('point ${card.point.value}, score: ${card.score.value}'); // point 1, score 1.25
// 递减
card
..point.incrementValue = -1
..score.incrementValue = -1.00;
await documentAccessor.update(card);
print('point ${card.point.value}, score: ${card.score.value}'); // point 0, score 0.25
示例 Demo
以下是一个简单的 Flutter 应用示例,展示了如何使用 Flamingo 进行基本操作:
import 'package:flutter/material.dart';
import 'package:flamingo/flamingo.dart';
import 'package:flamingo_example/firebase_options.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Flamingo.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Flamingo Example')),
body: Center(
child: ElevatedButton(
onPressed: () async {
final user = User()..name = 'John Doe';
final documentAccessor = DocumentAccessor();
await documentAccessor.save(user);
print('User saved with ID: ${user.id}');
},
child: Text('Save User'),
),
),
),
);
}
}
以上示例展示了如何使用 Flamingo 保存用户信息到 Firestore 数据库中。通过这种方式,您可以轻松地扩展应用以支持更多复杂的功能。
更多关于Flutter 插件flamingo的使用_Flamingo 是一个基于 Firebase Firestore 的模型框架库的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter 插件flamingo的使用_Flamingo 是一个基于 Firebase Firestore 的模型框架库的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter生态系统中,尽管flamingo
这个插件的具体功能描述为“未知”,这可能是由于该插件的文档不完整或者该插件较为新颖,尚未被广泛认知。不过,作为IT专家,我们可以尝试展示如何在一个Flutter项目中集成并使用一个假设的第三方插件,并给出一些基础的代码框架,以便开发者根据插件的实际API进行调整。
请注意,以下代码是一个假设性的示例,因为flamingo
插件的具体API和功能未知。这个示例旨在展示如何在Flutter项目中添加并使用第三方插件的一般流程。
- 添加依赖
首先,你需要在pubspec.yaml
文件中添加flamingo
插件的依赖项(假设它已经在pub.dev上发布)。由于具体版本和功能未知,这里使用占位符版本号。
dependencies:
flutter:
sdk: flutter
flamingo: ^x.y.z # 替换为实际版本号
然后运行flutter pub get
来安装依赖。
- 导入插件
在你的Dart文件中导入该插件。
import 'package:flamingo/flamingo.dart';
- 使用插件
由于我们不知道flamingo
插件的具体功能,以下代码将展示如何调用一个假设的方法或初始化一个假设的类。这只是一个模板,你需要根据插件的实际文档进行调整。
import 'package:flutter/material.dart';
import 'package:flamingo/flamingo.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
void initState() {
super.initState();
// 假设flamingo有一个初始化函数initFlamingo
// 并且我们可能需要传递一些配置参数
Flamingo.init(config: {
// 假设的配置参数
'apiKey': 'your_api_key',
'enableFeatureX': true,
});
// 假设有一个事件监听器可以订阅
Flamingo.onEvent.listen((event) {
print('Received event: $event');
// 根据事件类型进行相应处理
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flamingo Demo'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// 假设flamingo有一个执行某些操作的方法performAction
Flamingo.performAction('action_name').then((result) {
print('Action result: $result');
}).catchError((error) {
print('Error performing action: $error');
});
},
child: Text('Perform Flamingo Action'),
),
),
);
}
}
- 运行应用
确保你的开发环境已经设置好,然后运行flutter run
来启动你的Flutter应用。
重要提示:
- 由于
flamingo
插件的具体API和功能未知,上述代码中的Flamingo.init
,Flamingo.onEvent
, 和Flamingo.performAction
都是假设性的方法。你需要查阅插件的实际文档来了解如何正确初始化和使用该插件。 - 如果
flamingo
插件是一个私有插件或者尚未在pub.dev上发布,你可能需要按照插件提供者给出的特殊安装指令进行操作。
希望这个示例能帮助你开始集成和使用flamingo
插件,尽管其具体功能未知。随着你对该插件的了解加深,你可以逐步替换假设性的代码为实际的API调用。