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

如何结合Firebase QuerySnapshot使用StreamProvider?初始化数据报错

StreamProvider新增initialData参数引发的ProviderNullException解决方法

问题情况

跟随旧教程使用StreamProvider时,因API变更必须添加initialData参数,设置为null后编译通过,但运行时抛出ProviderNullException,提示BrewList读取的Provider类型不匹配。

Home.dart代码

//const Home({super.key});
final AuthService _auth = AuthService();

@override
Widget build(BuildContext context) {
  return StreamProvider<QuerySnapshot?>.value(
    value: DatabaseService(uid: '').brews,
    initialData: null,
    child: Scaffold(
      backgroundColor: Colors.brown[50],
      appBar: AppBar(
        title: Text('Brew Crew'),
        backgroundColor: Colors.brown[400],
        elevation: 0.0,
        actions: <Widget>[
          TextButton.icon(
            icon: Icon(Icons.person),
            label: Text('logout'),
            onPressed: () async {
              await _auth.signOut();
            },
          )
        ],
      ),
      body: BrewList(),
    ),
  );
}

Database.dart代码

class DatabaseService {
  final String uid;

  DatabaseService({required this.uid});
  // collection reference
  final CollectionReference brewCollection =
      FirebaseFirestore.instance.collection('brews');

  Future updateUserData(String sugars, String name, int strength) async {
    return await brewCollection.doc(uid).set({
      'sugars': sugars,
      'name': name,
      'strength': strength,
    });
  }
  // get brews stream
  Stream<QuerySnapshot> get brews {
    return brewCollection.snapshots();
  }
}

错误日志

Instance of 'BrewUser'
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following ProviderNullException was thrown building BrewList(dirty, dependencies:
[_InheritedProviderScope<QuerySnapshot<Object?>?>], state: _BrewListState#7ae11):
Error: The widget BrewList tried to read Provider<QuerySnapshot<Object?>> but the matching
provider returned null.

To fix the error, consider changing Provider<QuerySnapshot<Object?>> to
Provider<QuerySnapshot<Object?>>?.

The relevant error-causing widget was:
  BrewList
  BrewList:file:///C:/Users/Chris/source/repos/firebase-example/brew_crew/lib/screens/home/home.dart:33:15

When the exception was thrown, this was the stack:
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 296:3       throw_
packages/provider/src/provider.dart 307:9                                         of packages/brew_crew/screens/home/brews_list.dart 15:28                             build

解决步骤

  • 修正Provider读取类型:找到BrewList中读取Provider的代码,将Provider.of<QuerySnapshot>(context)改为Provider.of<QuerySnapshot?>(context),因为当前StreamProvider提供的是可空的QuerySnapshot类型,读取时要对应匹配。
  • 给initialData赋非空值:如果不想使用可空类型,可给initialData传入空的QuerySnapshot实例,代码改为initialData: QuerySnapshot.empty(),确保已导入cloud_firestore包。
  • 额外提示:当前DatabaseService的uid传的是空字符串,后续用户登录后需替换为实际用户uid,否则无法正确关联用户数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 04:25:04