Flutter Firebase工具集插件firebase_utils的使用

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

Flutter Firebase工具集插件firebase_utils的使用

本包提供了Firestore和Fire Storage的一系列实用工具,包括CRUD操作和其他重要功能。你可以轻松执行常见的数据库操作,并高效地存储和管理数据,从而专注于开发应用程序的核心功能。

安装

要将Firebase Utils用于你的项目,在pubspec.yaml文件中添加以下依赖项:

dependencies:
  firebase_utils: ^<最新版本>

然后运行flutter pub get来安装该包。

示例

ezgif com-resize

使用

Firestore实用工具

在Dart代码中导入包:

import 'package:firebase_utils/entity/firestore_doc.dart';
import 'package:firebase_utils/firebase/firestore_service.dart';

创建一个可以继承自FireStoreDocTimeStampedFireStoreDoc的Entity UserInfo。如果需要在Firestore表中包含createdDateupdatedDate字段,则应扩展TimeStampedFireStoreDoc

class UserInfo extends FireStoreDoc {
  final String name;
  final String email;
  final String profileImage;

  UserInfo(
      {required this.name, required this.email, required this.profileImage});

  [@override](/user/override)
  Map<String, dynamic> toMap() => {
        'name': name,
        'email': email,
        'profileImage': profileImage,
      };

  factory UserInfo.fromMap(Map<String, dynamic> map) => UserInfo(
        name: map['name'] as String,
        email: map['email'] as String,
        profileImage: map['profileImage'] as String,
      );
}

创建一个集合引用users,其中users是Firestore数据库中类型为UserInfo的集合。

CollectionReference<UserInfo> get _userCollectionRef =>
      widget._fireStoreService.getCollectionRef(
          'users', (snapshot, _) => UserInfo.fromMap(snapshot.data()!));

获取一个FireStoreService实例以执行所有Firestore操作。

final FireStoreService firestoreService =  FireStoreService.getInstance(FirebaseFirestore.instance);

在流中获取集合中的所有文档:

firestoreService.getListStream(_userCollectionRef).listen((event) {
  List<UserInfo> = event;
});

插入数据:

firestoreService.add(UserInfo(name: 'abc', email: 'abc@gmail.com', profileImage: 'imageUrl'), _userCollectionRef);

删除对象:

await fireStoreService.delete(_userCollectionRef.doc(docId));

你可以使用FireStoreService中定义的所有其他函数来进行Firestore操作。

FirebaseStorage实用工具

在Dart代码中导入包:

import 'package:firebase_utils/firebase/firebase_storage_service.dart';

获取一个FirebaseStorageService实例以执行所有FirebaseStorage操作。

final FirebaseStorageService firebaseStorageService =  FirebaseStorageService.getInstance(FirebaseStorage.instance);

上传文件:

firebaseStorageService.updateFileAndGetUrl(downloadUrl, file);

示例代码

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:firebase_utils/entity/firestore_doc.dart';
import 'package:firebase_utils/firebase/firebase_storage_service.dart';
import 'package:firebase_utils/firebase/firestore_service.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'firebase_options.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  initDependencies();
  runApp(const MyApp());
}

initDependencies() {
  Get.lazyPut<FirebaseStorage>(() => FirebaseStorage.instance, fenix: true);
  Get.lazyPut<FirebaseFirestore>(() => FirebaseFirestore.instance, fenix: true);
  Get.lazyPut<FireStoreService>(() => FireStoreService.getInstance(Get.find()));
  Get.lazyPut<FirebaseStorageService>(
      () => FirebaseStorageService.getInstance(Get.find()));
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Firebase Utils'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({super.key, required this.title});

  final String title;

  final FireStoreService _fireStoreService = Get.find();
  // final FirebaseStorageService _firebaseStorageService = Get.find();

  final RxList<UserInfo> userInfo = RxList();

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  CollectionReference<UserInfo> get _userCollectionRef =>
      widget._fireStoreService.getCollectionRef(
          'users', (snapshot, _) => UserInfo.fromMap(snapshot.data()!));

  final TextEditingController nameController = TextEditingController();
  final TextEditingController emailController = TextEditingController();

  [@override](/user/override)
  void initState() {
    widget._fireStoreService.getListStream(_userCollectionRef).listen((event) {
      widget.userInfo.value = event;
    });
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            TextFormField(
              decoration: const InputDecoration(hintText: 'Name'),
              controller: nameController,
            ),
            const SizedBox(
              height: 8,
            ),
            TextFormField(
              decoration: const InputDecoration(hintText: 'email'),
              controller: emailController,
            ),
            const SizedBox(
              height: 16,
            ),
            ElevatedButton(onPressed: _addUser, child: const Text('Add')),
            Expanded(
                child: Obx(
              () => ListView.separated(
                padding: const EdgeInsets.all(12),
                itemBuilder: _userItemBuilder,
                itemCount: widget.userInfo.length,
                separatorBuilder: (BuildContext context, int index) {
                  return const SizedBox(
                    height: 12,
                  );
                },
              ),
            )),
          ],
        ),
      ),
    );
  }

  void _addUser() async {
    if (nameController.text.trim().isNotEmpty &&
        emailController.text.trim().isNotEmpty) {
      await widget._fireStoreService.add(
          UserInfo(
              name: nameController.text,
              email: emailController.text,
              profileImage:
                  'https://fastly.picsum.photos/id/23/200/200.jpg?hmac=IMR2f77CBqpauCb5W6kGzhwbKatX_r9IvgWj6n7FQ7c'),
          _userCollectionRef);
    }
  }

  void _deleteUser(String docId) async {
    await widget._fireStoreService.delete(_userCollectionRef.doc(docId));
  }

  Widget _userItemBuilder(BuildContext context, int index) {
    final user = widget.userInfo[index];
    return Row(
      children: [
        CircleAvatar(
          backgroundImage: NetworkImage(user.profileImage),
          radius: 20,
        ),
        const SizedBox(
          width: 16,
        ),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                user.name,
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              Text(user.email),
            ],
          ),
        ),
        IconButton(
            onPressed: () => _deleteUser('${user.docId}'),
            icon: const Icon(Icons.delete_outline)),
      ],
    );
  }
}

class UserInfo extends FireStoreDoc {
  final String name;
  final String email;
  final String profileImage;

  UserInfo(
      {required this.name, required this.email, required this.profileImage});

  [@override](/user/override)
  Map<String, dynamic> toMap() => {
        'name': name,
        'email': email,
        'profileImage': profileImage,
      };

  factory UserInfo.fromMap(Map<String, dynamic> map) => UserInfo(
        name: map['name'] as String,
        email: map['email'] as String,
        profileImage: map['profileImage'] as String,
      );
}

更多关于Flutter Firebase工具集插件firebase_utils的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Firebase工具集插件firebase_utils的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,firebase_utils 并不是 Flutter 官方或广泛认知的一个 Firebase 插件。然而,基于你的需求,我们可以假设 firebase_utils 是一个自定义的或者第三方工具集插件,用于简化 Firebase 服务的集成和使用。在现实中,Flutter 社区通常使用官方提供的 Firebase 插件集合(如 firebase_core, firebase_auth, firebase_firestore, firebase_storage 等)来实现 Firebase 功能。

不过,为了回应你的帖子,并给出一个假设性的 firebase_utils 插件使用案例,我们可以构建一个简化的示例,展示如何封装 Firebase 服务。请注意,这个示例将基于 Flutter 和 Firebase 官方插件,并假设 firebase_utils 是我们自定义的一个封装工具集。

假设的 firebase_utils 插件

首先,我们需要在 pubspec.yaml 文件中添加必要的 Firebase 插件依赖:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.10.0
  firebase_auth: ^3.3.3
  firebase_firestore: ^2.5.3
  firebase_storage: ^10.0.2

然后,我们创建一个 firebase_utils 文件夹,并在其中创建一个 firebase_service.dart 文件,用于封装 Firebase 服务:

// firebase_utils/firebase_service.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_firestore/firebase_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';

class FirebaseService {
  late FirebaseApp firebaseApp;
  late FirebaseAuth firebaseAuth;
  late FirebaseFirestore firebaseFirestore;
  late FirebaseStorage firebaseStorage;

  FirebaseService() async {
    // Initialize Firebase App
    firebaseApp = await Firebase.initializeApp();

    // Initialize Firebase Auth
    firebaseAuth = FirebaseAuth.instance;

    // Initialize Firebase Firestore
    firebaseFirestore = FirebaseFirestore.instance;

    // Initialize Firebase Storage
    firebaseStorage = FirebaseStorage.instance;
  }

  // Example method to get user
  Future<User?> getCurrentUser() {
    return firebaseAuth.currentUser;
  }

  // Example method to write data to Firestore
  Future<void> writeToFirestore(String collection, Map<String, dynamic> data) {
    return firebaseFirestore.collection(collection).add(data);
  }

  // Example method to upload a file to Storage
  Future<String?> uploadFile(String filePath) {
    final storageRef = firebaseStorage.ref().child('uploads/${filePath.split('/').last}');
    return storageRef.putFile(File.fromUri(Uri.parse(filePath))).then((taskSnapshot) {
      return taskSnapshot.ref.getDownloadURL().then((downloadUrl) {
        return downloadUrl.toString();
      });
    });
  }
}

使用 firebase_utils 插件

接下来,我们在应用的某个地方(例如 main.dart)使用这个封装好的 FirebaseService

// main.dart
import 'package:flutter/material.dart';
import 'firebase_utils/firebase_service.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late FirebaseService firebaseService;

  @override
  void initState() {
    super.initState();
    // Initialize FirebaseService
    firebaseService = FirebaseService();

    // Optionally, use the service to perform actions
    _getUser();
    _writeToFirestore();
    _uploadFile();
  }

  Future<void> _getUser() async {
    final user = await firebaseService.getCurrentUser();
    if (user != null) {
      print('User found: ${user.uid}');
    } else {
      print('No user signed in');
    }
  }

  Future<void> _writeToFirestore() async {
    await firebaseService.writeToFirestore('users', {
      'name': 'John Doe',
      'email': 'john.doe@example.com',
    });
    print('Data written to Firestore');
  }

  Future<void> _uploadFile() async {
    final filePath = 'path/to/your/file.jpg'; // Replace with actual file path
    final downloadUrl = await firebaseService.uploadFile(filePath);
    if (downloadUrl != null) {
      print('File uploaded: $downloadUrl');
    } else {
      print('Failed to upload file');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Firebase Utils Example'),
        ),
        body: Center(
          child: Text('Check the console for Firebase operations results.'),
        ),
      ),
    );
  }
}

注意事项

  1. Firebase 配置:确保你的 Firebase 项目已正确配置,并且在 google-services.json(Android)和 GoogleService-Info.plist(iOS)文件中包含了正确的配置信息。

  2. 权限:确保你的 Firebase 项目具有执行这些操作所需的权限(例如,Firestore 数据库规则和 Storage 规则)。

  3. 错误处理:在实际应用中,应添加适当的错误处理逻辑,以处理可能出现的异常情况。

  4. 依赖版本:上述代码中的依赖版本可能会随时间而变化,请确保使用最新版本的 Firebase 插件。

这个示例展示了如何封装和使用 Firebase 服务,尽管它是基于假设的 firebase_utils 插件。在实际项目中,你可能需要根据具体需求进行更详细的封装和扩展。

回到顶部