Flutter云数据库交互插件firestore_model的使用

发布于 1周前 作者 phonegap100 来自 Flutter

Flutter云数据库交互插件firestore_model的使用

firestore_model 是一个简化 Firestore 数据库与 Flutter 应用之间交互的插件,它允许开发者以更直观和面向对象的方式操作 Firestore 集合。本文将详细介绍如何在 Flutter 项目中使用 firestore_model 插件,并提供完整的示例代码。

添加 firestore_model 到你的项目

首先,在项目的 pubspec.yaml 文件中添加 firestore_model 的最新版本到依赖项中:

# pubspec.yaml

dependencies:
  firestore_model: ^<latest version>

初始化配置

main.dart 文件中初始化 Firebase 并设置 FirestoreModelSettings(可选):

void main() async {
  await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
      settings: const FirestoreModelSettings(
          //persistenceEnabled: true,
          ));
  runApp(MyApp());
}

定义数据模型

创建一个继承自 FirestoreModel 的类,并重写 toMapresponseBuilder 方法:

class User extends FirestoreModel<User> {
  String? firstName;
  String? lastName;

  User({this.firstName, this.lastName});

  // 从 Map 构建对象
  User.fromMap(Map<String, dynamic> map) {
    this.firstName = map['first_name'];
    this.lastName = map['last_name'];
  }

  // 将对象转换为 Map
  @override
  Map<String, dynamic> get toMap => {
        'first_name': this.firstName,
        'last_name': this.lastName,
      };

  @override
  ResponseBuilder<User> get responseBuilder => (map) => User.fromMap(map);

  // 可选:指定集合名称
  @override
  String get collectionName => 'users';
}

注入模型

在应用启动时注入模型:

FirestoreModel.injectAll([User()]);

创建、保存、更新和删除文档

创建文档

User user = User(firstName: "Mohamed", lastName: "Abdullah");
await user.create();

保存或更新文档

user.firstName = "New First Name";
await user.save();

更新特定字段

await user.update(data: {
  "first_name": "Mohamed",
  "last_name": "Abdullah"
});

删除文档

await user.delete();

查询文档

获取单个文档

User user = await FirestoreModel.use<User>().find('documentId');

流式获取单个文档

Stream<User> streamUser = FirestoreModel.use<User>().streamFind('documentId');

获取所有文档

List<User> users = await FirestoreModel.use<User>().all();

流式获取所有文档

Stream<List<User>> streamUsers = FirestoreModel.use<User>().streamAll();

分页查询

List<User> topUsers = await FirestoreModel.use<User>().paginate(
  perPage: 15,
  queryBuilder: (query) => query.orderBy('score', descending: true),
);

使用构建器

单个文档构建器

ModelSingleBuilder<User>(
  docId: 'documentId',
  builder: (_, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data?.firstName ?? 'No Data');
    }
    return CircularProgressIndicator();
  },
)

多个文档构建器

ModelGetBuilder<User>(
  query: (q) => q.orderBy('createdAt'),
  builder: (_, snapshot) {
    if (snapshot.hasData) {
      return ListView.builder(
        itemCount: snapshot.data?.length,
        itemBuilder: (_, index) {
          final user = snapshot.data?[index];
          return ListTile(
            title: Text("${user?.firstName} ${user?.lastName}"),
          );
        },
      );
    }
    return CircularProgressIndicator();
  },
)

示例代码

以下是一个完整的示例应用程序,展示了如何使用 firestore_model 插件:

import 'dart:developer';

import 'package:example/models/post.dart';
import 'package:example/models/user.dart';
import 'package:firestore_model/firestore_model.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';

void main() async {
  await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
      settings: const FirestoreModelSettings());
  FirestoreModel.injectAll([User(), Post()]);
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final User _user = User(
    firstName: "Mohamed",
    lastName: "Abdullah",
    languages: ['php', 'dart', 'swift'],
  );

  void _addUser() async {
    await _user.create();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Center(
        child: ModelStreamGetBuilder<User>(
          query: (q) => q.orderBy('createdAt', descending: true),
          onLoading: () => const Center(child: Text("Loading")),
          onEmpty: () => const Center(child: Text("Sorry Your List is Empty")),
          onSuccess: (users) {
            return ListView.builder(
              itemCount: users?.length,
              itemBuilder: (_, index) {
                final user = users?[index];
                return ListTile(
                  title: Text("${user?.firstName} ${user?.lastName}"),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(user?.createdAt.toString() ?? ''),
                      Text(user?.languages.toString() ?? ''),
                    ],
                  ),
                  leading: IconButton(
                    onPressed: () {
                      user?.arrayUnion(field: 'languages', elements: ['kotlin']);
                    },
                    icon: const Icon(Icons.add),
                  ),
                  trailing: IconButton(
                    onPressed: () {
                      user?.delete();
                    },
                    icon: const Icon(Icons.delete),
                  ),
                );
              },
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addUser,
        tooltip: 'Add User',
        child: const Icon(Icons.add),
      ),
    );
  }
}

这个示例展示了如何创建用户、显示用户列表并进行增删改查操作。通过使用 firestore_model 插件,可以更方便地管理 Firestore 数据库中的数据。


更多关于Flutter云数据库交互插件firestore_model的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter云数据库交互插件firestore_model的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,关于Flutter中如何使用firestore_model插件与Firebase Firestore云数据库进行交互,下面是一个简单的代码示例。这个示例展示了如何配置firestore_model,定义数据模型,并进行基本的CRUD(创建、读取、更新、删除)操作。

首先,确保你已经在pubspec.yaml文件中添加了firestore_modelcloud_firestore依赖:

dependencies:
  flutter:
    sdk: flutter
  cloud_firestore: ^3.1.0
  firestore_model: ^0.3.0 # 请注意版本号可能有所更新,使用最新稳定版本

然后运行flutter pub get来安装依赖。

1. 配置Firestore

在你的Flutter应用的入口文件(通常是main.dart)中,配置Firebase Firestore:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firestore_model/firestore_model.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Firestore Model Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FirestoreDemo(),
    );
  }
}

2. 定义数据模型

创建一个新的Dart文件(例如user_model.dart),定义你的数据模型。这里我们定义一个简单的User模型:

import 'package:firestore_model/firestore_model.dart';

@FirestoreModel()
class User {
  String? id;
  String? name;
  int? age;

  User({this.id, this.name, this.age});

  // 从Firestore文档快照转换
  factory User.fromSnapshot(DocumentSnapshot snapshot) => User(
        id: snapshot.id,
        name: snapshot.data()!['name'] as String?,
        age: snapshot.data()!['age'] as int?,
      );

  // 转换为Map用于Firestore存储
  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'age': age,
    };
  }
}

3. 使用FirestoreModel进行CRUD操作

在你的主页面(例如firestore_demo.dart)中,使用FirestoreModel进行CRUD操作:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'user_model.dart';

class FirestoreDemo extends StatefulWidget {
  @override
  _FirestoreDemoState createState() => _FirestoreDemoState();
}

class _FirestoreDemoState extends State<FirestoreDemo> {
  final Firestore firestore = Firestore.instance;
  late FirestoreModel<User> userModel;

  @override
  void initState() {
    super.initState();
    userModel = FirestoreModel<User>(
      collectionName: 'users',
      firestore: firestore,
      fromSnapshot: User.fromSnapshot,
      toMap: (User user) => user.toMap(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Firestore Model Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                User user = User(name: 'John Doe', age: 30);
                await userModel.add(user);
              },
              child: Text('Add User'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                List<User> users = await userModel.getAll();
                print(users);
              },
              child: Text('Get All Users'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                User? user = await userModel.getById('user_id_here');
                print(user);
              },
              child: Text('Get User By ID'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                User userToUpdate = await userModel.getById('user_id_here')!;
                userToUpdate.age = 31;
                await userModel.update(userToUpdate);
              },
              child: Text('Update User'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                await userModel.deleteById('user_id_here');
              },
              child: Text('Delete User'),
            ),
          ],
        ),
      ),
    );
  }
}

请注意,上述代码中的'user_id_here'需要替换为实际的用户ID。

这个示例展示了如何使用firestore_model插件与Firebase Firestore进行基本的交互。根据你的实际需求,你可以进一步扩展和自定义这些操作。

回到顶部