You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求Flutter音乐应用Firebase Firestore存数据代码及报错解决

Flutter音乐应用Firestore存储实现与配置错误修复

一、修复Firebase配置错误

错误提示明确指出无法从资源加载FirebaseOptions,需按以下步骤排查:

  • 检查Android项目android/app/src/main/res/values/values.xml文件,确认已包含Firebase控制台提供的配置参数(apiKey、applicationId、projectId等),这些参数需与google-services.json中的内容完全匹配。
  • 确保Firebase集成步骤正确:
    1. 在项目根目录执行flutter pub add firebase_core cloud_firestore添加依赖。
    2. 在android/build.gradle中添加Google服务插件依赖:classpath 'com.google.gms:google-services:4.4.0'(版本可按需调整)。
    3. 在android/app/build.gradle末尾添加apply plugin: 'com.google.gms.google-services'。
    4. 将Firebase控制台下载的google-services.json文件放置在android/app目录下。

二、收藏与最近播放歌曲的Firestore存储代码

1. Firebase初始化

import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

// 初始化Firebase,建议在应用启动时调用
Future<void> initFirebase() async {
  await Firebase.initializeApp();
}

2. 歌曲数据模型

class Song {
  final String id;
  final String title;
  final String artist;
  final String album;
  final String coverUrl;

  Song({
    required this.id,
    required this.title,
    required this.artist,
    required this.album,
    required this.coverUrl,
  });

  // 转换为Firestore可存储的Map格式
  Map<String, dynamic> toMap() => {
        'id': id,
        'title': title,
        'artist': artist,
        'album': album,
        'coverUrl': coverUrl,
      };

  // 从Firestore的Map转换为Song对象
  factory Song.fromMap(Map<String, dynamic> map) => Song(
        id: map['id'],
        title: map['title'],
        artist: map['artist'],
        album: map['album'],
        coverUrl: map['coverUrl'],
      );
}

3. Firestore操作服务类

class FirestoreMusicService {
  final FirebaseFirestore _db = FirebaseFirestore.instance;
  final String userId;

  FirestoreMusicService(this.userId);

  // 添加歌曲到收藏列表
  Future<void> addToFavorites(Song song) async {
    try {
      await _db
          .collection('users')
          .doc(userId)
          .collection('favorites')
          .doc(song.id)
          .set(song.toMap());
    } catch (e) {
      print('添加收藏失败: $e');
      rethrow;
    }
  }

  // 移除收藏歌曲
  Future<void> removeFromFavorites(String songId) async {
    try {
      await _db
          .collection('users')
          .doc(userId)
          .collection('favorites')
          .doc(songId)
          .delete();
    } catch (e) {
      print('移除收藏失败: $e');
      rethrow;
    }
  }

  // 实时监听收藏列表
  Stream<List<Song>> watchFavorites() {
    return _db
        .collection('users')
        .doc(userId)
        .collection('favorites')
        .snapshots()
        .map((snapshot) => snapshot.docs.map((doc) => Song.fromMap(doc.data())).toList());
  }

  // 添加歌曲到最近播放(自动保留最近20条记录)
  Future<void> addToRecentPlays(Song song) async {
    try {
      final recentCollection = _db
          .collection('users')
          .doc(userId)
          .collection('recent_plays');

      // 先删除已有记录(避免重复)
      await recentCollection.doc(song.id).delete();
      // 添加带时间戳的新记录
      await recentCollection.doc(song.id).set({
        ...song.toMap(),
        'playedAt': FieldValue.serverTimestamp(),
      });

      // 限制最近播放数量为20条,超过则删除最早的记录
      final snapshot = await recentCollection.orderBy('playedAt', descending: true).get();
      if (snapshot.docs.length > 20) {
        for (var doc in snapshot.docs.sublist(20)) {
          await doc.reference.delete();
        }
      }
    } catch (e) {
      print('添加最近播放失败: $e');
      rethrow;
    }
  }

  // 实时监听最近播放列表(按播放时间倒序)
  Stream<List<Song>> watchRecentPlays() {
    return _db
        .collection('users')
        .doc(userId)
        .collection('recent_plays')
        .orderBy('playedAt', descending: true)
        .snapshots()
        .map((snapshot) => snapshot.docs.map((doc) => Song.fromMap(doc.data())).toList());
  }
}

4. 使用示例

// 假设已通过Firebase Auth获取到当前用户ID
final currentUserId = 'user_123456';
final musicService = FirestoreMusicService(currentUserId);

// 测试歌曲
final testSong = Song(
  id: 'song_001',
  title: '夜曲',
  artist: '周杰伦',
  album: '十一月的萧邦',
  coverUrl: 'https://example.com/yequ.jpg',
);

// 添加收藏
musicService.addToFavorites(testSong);

// 添加最近播放
musicService.addToRecentPlays(testSong);

// 监听收藏列表更新
musicService.watchFavorites().listen((favorites) {
  print('当前收藏歌曲: ${favorites.map((s) => s.title).join(', ')}');
});

// 监听最近播放更新
musicService.watchRecentPlays().listen((recentPlays) {
  print('最近播放歌曲: ${recentPlays.map((s) => s.title).join(', ')}');
});

内容的提问来源于stack exchange,提问作者Tarra Purna Chandra Rao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 03:07:51