首页 > 解决方案 > 当我尝试使用我的颤振 ap 在 Firestore 中显示记录时,它会给出一个名为“小部件库异常捕获”的错误

问题描述

这是我得到的错误

theftion trible tribrars捕获的例外╞═══════════════════════════════════════════ ════════════════ 在构建 StreamBuilder(dirty, state: _StreamBuilderBaseState<User, AsyncSnapshot>#0ddea) 时引发了以下 NoSuchMethodError:在 null 上调用了 getter 'department'。Receiver: null 尝试调用:department 相关的导致错误的小部件是:StreamBuilder

这是代码。我要开发一个在线公告栏。这些代码在新的飞镖更新之前正常工作。在我给出更新之后它给出了上述错误。请给我一个修复它的方法

批准通知.dart

  Widget build(BuildContext context) {

 return StreamProvider<List<Notice>>.value(
  value: NoticeService().notices, 
  child: Scaffold(
  appBar: AppBar(
    elevation: 0.0,
   title: Text('Aprove Notices',
   style: TextStyle(
     fontFamily: 'Montserrat',
     fontWeight: FontWeight.bold,
     color: Colors.white,
   ),
   ),
   backgroundColor: Colors.blue[800],
   actions: <Widget>[
     IconButton(
       icon: Icon(Icons.search, color: Colors.white,), 
       onPressed: (){}
       ),
       
   ], 
  ),
  

body:UnApprovedNotices() ,

UnapproveNotices.dart

 class UnApprovedNotices extends StatefulWidget {
  @override
 _UnApprovedNoticesState createState() => _UnApprovedNoticesState();
 }

 class _UnApprovedNoticesState extends State<UnApprovedNotices> {

  @override
  Widget build(BuildContext context) {
  final notices = Provider.of<List<Notice>>(context) ?? [];

    
    return StreamBuilder<List<Notice>>(
  stream: NoticeService().notices,
  builder: (context, snapshot) {
    if(snapshot.hasData){
      
      return GridView.builder (
        
      itemCount: notices.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 1),
      // ignore: missing_return
      itemBuilder: (context,index){
          return SingleNotice(
          notice:notices[index]

        );
      }
     }
      
      
    );
  }else{
    return(Text('No List'));
  }
    }

尽管 Firestore 中有记录,但它显示“无列表”并给出上述错误。

标签: flutterexceptiondartgoogle-cloud-firestorestream-builder

解决方案


该错误是由department在 null 上调用属性引起的,这意味着,您尝试调用类似 的东西user.department,不幸user的是为 null。

我认为,您正在造成麻烦,因为您没有AsyncSnapshot正确处理。

为了正确实现快照数据,您已经处理了所有的状态AsyncSnapshot

if (snapshot.hasError) {
  // Return Widget to display error
  // snapshot.error will be not nil.
  return ErrorWidget(snapshot.error);
} else {
   if (snapshot.connectionState == ConnectionState.waiting) {
       // snapshot is waiting for data
       // Generally we could use this to show `CircularProgressIndicator`
       return Center(child: CircularProgressIndicator());
   } else if (snapshot.hasData) {
      // Snapshot will contains particular data.
      // get this value by snapshot.data 
      return DataWidget(snapshot.data);
   }
}

注意:代码未经测试。希望这有助于一般实施。如果需要更多的控制ConnectionState,请做 switch 语句。

在 Flutter 文档中阅读更多信息:StreamBuilder类。


推荐阅读