Flutter集成Firebase服务插件firebase_for_all的使用
Flutter集成Firebase服务插件firebase_for_all的使用
摘要
firebase_for_all
插件允许你在所有平台上使用 Firebase 功能而无需更改代码。它利用了以下包:
firebase_dart
firedart
firebase_auth_desktop
firebase_core_desktop
在非 Windows 平台上,推荐使用原生库以减少错误和问题的风险。
特性
目前支持以下 Firebase 服务:
- 认证
- 云 Firestore
- 云存储
示例
所有示例位于 example/lib/functions.dart
。
使用
首先,在你的 pubspec.yaml
文件中添加依赖项:
dependencies:
firebase_for_all: ^latest
如果通过 FlutterFire CLI 设置 Firebase,初始化应用时会抛出错误。为避免此错误,你可以覆盖依赖项:
dependency_overrides:
firebase_core_platform_interface: 4.5.1
然后运行 flutter packages get
。
入门
初始化 Firebase
有两种配置 Firebase 的方法:
旧方法:手动配置
await FirebaseCoreForAll.initializeApp(
options: FirebaseOptions(
apiKey: 'XXXXXXXXXXXXXXXXXXXXXX',
appId: 'XXXXXXXXXXXXXXXXXXXXXX',
messagingSenderId: 'XXXXXXXXXXX',
projectId: 'XXXXXXXXXXXXXX',
authDomain: 'XXXXXXXXXXXXX.firebaseapp.com',
storageBucket: 'XXXXXXXXXXXXX.appspot.com',
),
firestore: true,
auth: true,
storage: true);
新方法:使用 Firebase CLI
await FirebaseCoreForAll.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
firestore: true,
auth: true,
storage: true);
云存储
获取 FirebaseAuth
实例:
await FirebaseAuthForAll.instance.createUserWithEmailAndPassword(email: "test@hotmail.com", password: "password123");
云 Firestore
文档与查询快照
QuerySnapshot
FirestoreForAll.instance
.collection('users')
.get()
.then((QuerySnapshotForAll querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc["first_name"]);
});
});
DocumentSnapshot
FirestoreForAll.instance
.collection('users')
.doc(userId)
.get()
.then((DocumentSnapshotForAll documentSnapshot) {
if (documentSnapshot.exists) {
print('Document data: ${documentSnapshot.data()}');
} else {
print('Document does not exist on the database');
}
});
查询
过滤
警告:isNotEqualTo
和 whereNotIn
在桌面端(除了 MacOS)不工作。
FirestoreForAll.instance
.collection('users')
.where('age', isGreaterThan: 10)
.get()
.then(...);
排序
FirestoreForAll.instance
.collection('users')
.orderBy('age', descending: true)
.get()
.then(...);
限制
警告:limitToLast
在桌面端(除了 MacOS)不工作。
FirestoreForAll.instance
.collection('users')
.limit(2)
.get()
.then(...);
起始和结束游标
警告:此功能在桌面端(除了 MacOS)不工作。
FirestoreForAll.instance
.collection('users')
.orderBy('age')
.orderBy('company')
.startAt([4, 'Alphabet Inc.'])
.endAt([21, 'Google LLC'])
.get()
.then(...);
添加、更新和删除文档
ColRef users = FirestoreForAll.instance.collection('users');
users
.add({
'full_name': fullName, // John Doe
'company': company, // Stokes and Sons
'age': age // 42
})
.then((value) => print("User Added"))
.catchError((error) => print("Failed to add user: $error"));
users
.doc("12345")
.set({
'full_name': fullName, // John Doe
'company': company, // Stokes and Sons
'age': age // 42
})
.then((value) => print("User Added"))
.catchError((error) => print("Failed to add user: $error"));
users
.doc('ABC123')
.update({'company': 'Stokes and Sons'})
.then((value) => print("User Updated"))
.catchError((error) => print("Failed to update user: $error"));
users
.doc('ABC123')
.delete()
.then((value) => print("User Deleted"))
.catchError((error) => print("Failed to delete user: $error"));
实时变化
监听集合
CollectionSnapshots collectionSnapshots = FirestoreForAll.instance.collection('users').snapshots();
collectionSnapshots.listen(
(snapshot) {},
onDone: () {},
onError: (e, stackTrace) {},
);
警告:StreamBuilder
对此不起作用。使用以下代码:
CollectionBuilder(
stream: FirestoreForAll.instance.collection("users").snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshotForAll> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
return ListView(
children:
snapshot.data!.docs.map((DocumentSnapshotForAll document) {
Map<String, dynamic> data =
document.data() as Map<String, dynamic>;
return ListTile(
title: Text(data['name']),
subtitle: Text(data['surname']),
);
}).toList(),
);
},
)
监听文档
DocumentSnapshots documentSnapshots=FirestoreForAll.instance.collection('users').doc('ABC123').snapshots();
documentSnapshots.listen(
(snapshot) {},
onDone: () {},
onError: (e, stackTrace) {},
);
警告:StreamBuilder
对此不起作用。使用以下代码:
DocumentBuilder(
stream: FirestoreForAll.instance
.collection("users")
.doc('ABC123')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshotForAll> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
return ListTile(
title: Text(snapshot.data!['name']),
subtitle: Text(snapshot.data!['surname']),
);
},
)
类型化 CollectionReference
和 DocumentReference
final moviesRef = FirestoreForAll.instance.collection('movies').withConverter<User>(
fromFirestore: (snapshot, _) => User.fromJson(snapshot.map!),
toFirestore: (movie, _) => movie.toJson(),
);
// 获取年龄为31岁的用户列表
List<DocumentSnapshotForAll<User>> users = await userRef
.where('age', isEqualTo: 31)
.get()
.then((snapshot) => snapshot.docs);
// 添加一个用户
await userRef.add(
User(
name: 'Chris',
surname: 'Doe',
age: 20
),
);
// 获取ID为42的用户
User user = await userRef.doc('42').get().then((snapshot) => snapshot.data()!);
云存储
上传文件
从文件上传
final storageRef = FirebaseStorageForAll.instance.ref();
final mountainsRef = storageRef.child("mountains.jpg");
Directory appDocDir = await getApplicationDocumentsDirectory();
String filePath = '${appDocDir.absolute}/file-to-upload.png';
File file = File(filePath);
UploadTaskForAll task = mountainsRef.putFile(file);
从字符串上传
String dataUrl = 'data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==';
UploadTaskForAll task = mountainsRef.putString(dataUrl, format: PutStringFormat.dataUrl);
上传原始数据
UploadTaskForAll task = mountainsRef.putData(file.readAsBytesSync());
获取下载链接
await mountainsRef.getDownloadURL();
管理上传
File file = File(filePath);
mountainsRef.putFile(file).snapshotEvents.listen((taskSnapshot) {
switch (taskSnapshot.state) {
case TaskState.running:
// ...
break;
case TaskState.paused:
// ...
break;
case TaskState.success:
// ...
break;
case TaskState.canceled:
// ...
break;
case TaskState.error:
// ...
break;
}
});
下载文件
内存中下载
final storageRef = FirebaseStorageForAll.instance.ref();
final islandRef = storageRef.child("images/island.jpg");
const oneMegabyte = 1024 * 1024;
final Uint8List? data = await islandRef.getData(oneMegabyte);
下载到本地文件
final islandRef = storageRef.child("images/island.jpg");
final appDocDir = await getApplicationDocumentsDirectory();
final filePath = "${appDocDir.absolute}/images/island.jpg";
final file = File(filePath);
DownloadTaskForAll downloadTask = await islandRef.writeToFile(file);
管理下载
downloadTask.snapshotEvents.listen((taskSnapshot) {
switch (taskSnapshot.state) {
case TaskState.running:
// TODO: Handle this case.
break;
case TaskState.paused:
// TODO: Handle this case.
break;
case TaskState.success:
// TODO: Handle this case.
break;
case TaskState.canceled:
// TODO: Handle this case.
break;
case TaskState.error:
// TODO: Handle this case.
break;
}
});
删除文件
final desertRef = storageRef.child("images/desert.jpg");
await desertRef.delete();
列出所有文件
final storageRef = FirebaseStorage.instance.ref().child("files/uid");
final listResult = await storageRef.listAll();
for (var prefix in listResult.prefixes) {
// The prefixes under storageRef.
// You can call listAll() recursively on them.
}
for (var item in listResult.items) {
// The items under storageRef.
}
新功能
StorageFile
class StorageFile{
String cloudPath;
String fileName;
StorageRef reference;
String type, extension;
List<String> relatedDirs;
int size;
}
StorageDirectory
class StorageDirectory{
String cloudPath;
String dirName;
StorageRef reference;
List<String> relatedDirs;
}
新函数 - getFiles()
List<StorageFile> files = await storageRef.getFiles();
新函数 - getSize()
final desertRef = FirebaseStorageForAll.instance.ref().child("images/desert.jpg");
int size = await desertRef.getSize();
新函数 - getDirectories()
List<StorageDirectory> files = await storageRef.getDirectories();
新函数 - getDirSize()
final storageRef = FirebaseStorageForAll.instance.ref().child("files/uid");
int size = await storageRef.getDirSize();
完整示例
以下是完整的示例代码:
import 'package:flutter/material.dart';
// ignore: depend_on_referenced_packages
import 'package:firebase_for_all/firebase_for_all.dart';
import 'firebase_options.dart';
import 'functions.dart';
void main() async {
await FirebaseCoreForAll.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
firestore: true,
auth: true,
storage: true);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: "title"),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: CollectionBuilder(
stream: FirestoreForAll.instance.collection("users").snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshotForAll> snapshot) {
if (snapshot.hasError) {
return const Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Text("Loading");
}
return ListView(
children:
snapshot.data!.docs.map((DocumentSnapshotForAll document) {
Map<String, dynamic> data =
document.data() as Map<String, dynamic>;
return ListTile(
title: Text(data['name']),
subtitle: Text(data['surname']),
);
}).toList(),
);
},
),
floatingActionButton: const FloatingActionButton(
onPressed: getCollection,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
更多关于Flutter集成Firebase服务插件firebase_for_all的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter集成Firebase服务插件firebase_for_all的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter项目中集成Firebase服务插件,尤其是像firebase_for_all
这样可能涵盖多种Firebase服务的插件(尽管需要注意的是,firebase_for_all
并不是Firebase官方提供的一个标准插件,这里假设它是一个综合多个Firebase服务的第三方插件),通常涉及以下几个步骤:添加依赖、配置Firebase项目、初始化Firebase服务以及使用相关服务。
由于firebase_for_all
不是官方插件,我将基于Flutter官方推荐的Firebase插件集合(如firebase_core
、firebase_auth
、firebase_firestore
等)来展示如何集成和使用Firebase服务。这些步骤和代码示例应该非常接近使用firebase_for_all
(如果存在的话)的过程。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加所需的Firebase插件依赖。例如,如果你想要集成Firebase身份验证和Firestore数据库,你可以添加如下依赖:
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.13.0 # 核心库,用于初始化Firebase应用
firebase_auth: ^3.3.10 # 身份验证服务
cloud_firestore: ^3.1.5 # Firestore数据库服务
然后运行flutter pub get
来安装这些依赖。
2. 配置Firebase项目
在Firebase控制台创建一个新的项目,并按照指示配置你的Android和iOS应用。下载google-services.json
(对于Android)和GoogleService-Info.plist
(对于iOS),并将它们分别放置在android/app/
和ios/Runner/
目录下。
3. 初始化Firebase应用
在你的main.dart
文件中,初始化Firebase应用:
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(); // 初始化Firebase应用
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Firebase Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
4. 使用Firebase服务
身份验证示例
import 'package:firebase_auth/firebase_auth.dart';
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<void> _signInAnonymously() async {
try {
UserCredential result = await _auth.signInAnonymously();
User? user = result.user;
// 更新UI或执行其他操作
} catch (e) {
print(e.toString());
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Firebase Auth Demo'),
),
body: Center(
child: ElevatedButton(
onPressed: _signInAnonymously,
child: Text('Sign in Anonymously'),
),
),
);
}
}
Firestore数据库示例
import 'package:cloud_firestore/cloud_firestore.dart';
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<void> _addData() async {
try {
await _firestore.collection('users').add({
'name': 'John Doe',
'age': 30,
});
// 更新UI或执行其他操作
} catch (e) {
print(e.toString());
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Firestore Demo'),
),
body: Center(
child: ElevatedButton(
onPressed: _addData,
child: Text('Add Data to Firestore'),
),
),
);
}
}
以上代码展示了如何在Flutter应用中集成并使用Firebase的核心功能。如果你使用的firebase_for_all
插件提供了类似的功能,集成和使用方式应该非常相似,只需参考该插件的文档进行具体实现即可。如果firebase_for_all
确实存在且有特殊用法,请参考其官方文档或GitHub仓库中的示例代码。