1.Firebase 設定
# Cài FlutterFire CLI
dart pub global activate flutterfire_cli
# Cấu hình project
flutterfire configure --project=my-flutter-app
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
2. 雲端Firestore
class FirestoreProductRepository {
final _collection = FirebaseFirestore.instance.collection('products');
// Create
Future<void> add(Product product) async {
await _collection.doc(product.id).set(product.toJson());
}
// Read
Future<List<Product>> getAll() async {
final snapshot = await _collection.orderBy('createdAt', descending: true).get();
return snapshot.docs.map((doc) => Product.fromJson(doc.data())).toList();
}
// Realtime stream
Stream<List<Product>> watchAll() {
return _collection
.orderBy('createdAt', descending: true)
.snapshots()
.map((snapshot) => snapshot.docs.map((doc) => Product.fromJson(doc.data())).toList());
}
// Query
Future<List<Product>> getByCategory(String category, {int limit = 20}) async {
final snapshot = await _collection
.where('category', isEqualTo: category)
.where('price', isGreaterThan: 0)
.limit(limit)
.get();
return snapshot.docs.map((doc) => Product.fromJson(doc.data())).toList();
}
// Update
Future<void> update(String id, Map<String, dynamic> data) async {
await _collection.doc(id).update(data);
}
// Delete
Future<void> delete(String id) async {
await _collection.doc(id).delete();
}
}
3、雲端儲存
class StorageService {
final _storage = FirebaseStorage.instance;
Future<String> uploadImage(File file, String path) async {
final ref = _storage.ref().child(path);
final uploadTask = ref.putFile(file, SettableMetadata(contentType: 'image/jpeg'));
uploadTask.snapshotEvents.listen((event) {
final progress = event.bytesTransferred / event.totalBytes;
debugPrint('Upload: ${(progress * 100).toStringAsFixed(0)}%');
});
final snapshot = await uploadTask;
return snapshot.ref.getDownloadURL();
}
}
4.Crashlytics 和分析
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
PlatformDispatcher.instance.onError = (error, stack) {
FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
return true;
};
await FirebaseAnalytics.instance.logEvent(name: 'app_open');
runApp(const MyApp());
}
下一篇: 認證與授權。