首页 > 解决方案 > Flutter / Firebase在null上调用了getter'length'

问题描述

我使用 Firebase 作为后端开发 Flutter 应用程序,当我从屏幕移动到另一个 BottomNavigationBar 时,我正在使用 StreamProvider 将配置文件数据传递到另一个屏幕。

当我移动到另一个屏幕时,我收到此错误:

 The getter 'length' was called on null.
Receiver: null
Tried calling: length

The relevant error-causing widget was: 
  ProfileList 

这是 ProfileList 和 ProfileTile

class ProfileList extends StatefulWidget {
  @override
  _ProfileListState createState() => _ProfileListState();
}

class _ProfileListState extends State<ProfileList> {
  @override
  Widget build(BuildContext context) {

final profiles = Provider.of<List<Profile>>(context);

return ListView.builder(
    itemCount: profiles.length,
    itemBuilder: (context, index){
      return ProfileTile(profile: profiles[index]);
});
  }
}

ProfileTile

class ProfileTile extends StatefulWidget {
  final Profile profile;
  ProfileTile({this.profile});
  @override
  _ProfileTileState createState() => _ProfileTileState();
}

class _ProfileTileState extends State<ProfileTile> {



  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(top: 8),
      child: Card(
        margin: EdgeInsets.fromLTRB(20, 6, 20, 0),
        child: ListTile(
          leading: CircleAvatar(
            radius: 25,
            backgroundColor: Colors.green,
          ),
          title: Text(widget.profile.userName),
          subtitle: Text(widget.profile.city),
        ),
      ),
    );
  }
}

标签: firebaseflutterdartgoogle-cloud-firestoreprovider

解决方案


看来,

itemCount:profiles.length,

在提供者向其发送数据之前呈现部分。所以配置文件变量为空。

尝试这个,

itemCount: (profiles == null) ? 0 : profile.length,

推荐阅读