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

Flutter中如何结合Firebase Auth使用Firebase实时数据库?

结合Firebase Auth使用Firebase实时数据库解决方案

要解决权限拒绝问题,核心是确保用户完成Firebase Auth登录流程,实时数据库会自动将当前登录用户的认证信息附加到请求中,从而通过auth != null的规则校验。以下是具体步骤:

1. 集成Firebase Auth依赖

在项目的pubspec.yaml中添加Firebase Auth相关包:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^latest_version
  firebase_auth: ^latest_version
  firebase_database: ^latest_version

执行flutter pub get完成依赖安装。

2. 初始化Firebase Auth

在main函数中完成Firebase全局初始化:

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';

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

3. 实现用户登录流程

必须让用户完成登录(支持邮箱密码、匿名、第三方登录等方式),以下是两种常用实现示例:

示例1:邮箱密码登录

Future<void> signInWithEmail(String email, String password) async {
  try {
    await FirebaseAuth.instance.signInWithEmailAndPassword(
      email: email,
      password: password,
    );
    // 登录成功,可执行受保护的数据库操作
  } on FirebaseAuthException catch (e) {
    // 处理登录错误(如邮箱不存在、密码不匹配)
    print('登录失败: ${e.message}');
  }
}

示例2:匿名登录(快速测试用)

Future<void> signInAnonymously() async {
  try {
    await FirebaseAuth.instance.signInAnonymously();
    print('匿名登录成功');
  } on FirebaseAuthException catch (e) {
    print('匿名登录失败: ${e.message}');
  }
}

4. 监听Auth状态,安全访问数据库

通过监听Auth状态变化,确保仅在用户登录后访问受保护的数据库节点:

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    // 监听用户登录状态变化
    FirebaseAuth.instance.authStateChanges().listen((User? user) {
      if (user != null) {
        // 用户已登录,访问受保护节点
        _fetchProtectedData();
      } else {
        // 用户未登录,提示或跳转到登录页面
        print('请先完成登录');
      }
    });
  }

  void _fetchProtectedData() async {
    final database = FirebaseDatabase.instanceFor(
      app: Firebase.app(),
      databaseURL: 'https://myproject.firebaseio.com/',
    );
    final protectedRef = database.ref('protected-node'); // 对应read规则为auth != null的节点

    try {
      final snapshot = await protectedRef.get();
      if (snapshot.exists) {
        print('获取数据成功: ${snapshot.value}');
      } else {
        print('节点无数据');
      }
    } on FirebaseException catch (e) {
      print('访问错误: ${e.message}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Firebase Auth + 实时数据库')),
        body: Center(
          child: ElevatedButton(
            onPressed: () => signInAnonymously(), // 点击触发登录
            child: const Text('匿名登录'),
          ),
        ),
      ),
    );
  }
}

关键注意事项

  • 确保Firebase控制台已启用对应登录方式(如邮箱密码、匿名登录);
  • 实时数据库规则配置正确,例如:
    {
      "rules": {
        "protected-node": {
          ".read": "auth != null",
          ".write": "auth != null"
        }
      }
    }
    
  • 若登录后仍出现权限问题,检查是否在用户登录前就发起了数据库请求——需确保数据库操作在Auth状态变为已登录后执行。

内容的提问来源于stack exchange,提问作者Daniel Watrous

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 10:10:57