简体   繁体   English

我正在尝试从 firebase 获取数据,但 flutter 在 StreamBuilder 上显示 null 安全错误

[英]I'm trying to get data from firebase but flutter is showing null safety error on StreamBuilder

I'm using StreamBuilder and inside that, I have got a list of tasks which takes input from the snapshots and display the data accordingly, but I'm having a null safety issue when dealing with snapshot data.我正在使用StreamBuilder ,在其中,我有一个任务列表,这些任务从快照中获取输入并相应地显示数据,但是在处理快照数据时我遇到了 null 安全问题。 Here's what the code looks like:代码如下所示:

StreamBuilder<List<Task>>(
  stream: DatabaseService()
      .getCompletedTasks(orderName),
  builder: (context, snapshot) {
    List<Task> completedTasks =
        snapshot.data!;
    return snapshot.data!.isEmpty
        ? Container(
            alignment:
                Alignment.center,
            child: Text(
              "You don't have any completed tasks.",
              style: TextStyle(
                fontSize: 20,
                fontFamily:
                    "Roboto",
                color: Colors.black,
              ),
            ),
          )
        : Container(
            child: Flexible(
              flex: 0,
              child: ListView
                  .separated(
                physics:
                    const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                separatorBuilder:
                    (context,
                            index) =>
                        const SizedBox(
                  height: 5,
                ),
                itemCount:
                    completedTasks
                        .length,
                itemBuilder:
                    (context,
                        index) {
                  return Dismissible(
                    background:
                        Container(
                      color: Colors
                          .red,
                      child:
                          const Align(
                        alignment:
                            Alignment
                                .centerLeft,
                        child:
                            Padding(
                          padding:
                              EdgeInsets.all(
                                  15.0),
                          child:
                              Icon(
                            Icons
                                .delete,
                            color: Colors
                                .white,
                          ),
                        ),
                      ),
                    ),
                    secondaryBackground:
                        Container(
                      color: Colors
                          .red,
                      child:
                          const Align(
                        alignment:
                            Alignment
                                .centerRight,
                        child:
                            Padding(
                          padding:
                              EdgeInsets.all(
                                  15.0),
                          child:
                              Icon(
                            Icons
                                .delete,
                            color: Colors
                                .white,
                          ),
                        ),
                      ),
                    ),
                    key:
                        UniqueKey(),
                    onDismissed:
                        (direction) {
                      DatabaseService()
                          .deleteTask(
                              completedTasks[index]
                                  .id);
                      AwesomeNotifications()
                          .cancelSchedule(
                              completedTasks[index]
                                  .id);
                    },
                    child: Item(
                      task:
                          completedTasks[
                              index],
                    ),
                  );
                },
              ),
            ),
          );
  }),

Everything works fine but just null safety error pops up for a short amount of time.一切正常,但只是在短时间内弹出 null 安全错误。

Add 1 condition for while loading stream data on initial stage.在初始阶段加载 stream 数据时添加 1 个条件。

StreamBuilder<List<Task>>(
        stream: DatabaseService()
            .getCompletedTasks(orderName),
        builder: (context, snapshot) {
          
          // Add this condition.
          if(!snapshot.hasData){
            
            return Center(child: CircularProgressIndicator());
          }
          
          List<Task> completedTasks =
          snapshot.data!;
          return snapshot.data!.isEmpty
              ? Container(
            alignment:
            Alignment.center,
            child: Text(
              "You don't have any completed tasks.",
              style: TextStyle(
                fontSize: 20,
                fontFamily:
                "Roboto",
                color: Colors.black,
              ),
            ),
          )
              : Container(
            child: Flexible(
              flex: 0,
              child: ListView
                  .separated(
                physics:
                const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                separatorBuilder:
                    (context,
                    index) =>
                const SizedBox(
                  height: 5,
                ),
                itemCount:
                completedTasks
                    .length,
                itemBuilder:
                    (context,
                    index) {
                  return Dismissible(
                    background:
                    Container(
                      color: Colors
                          .red,
                      child:
                      const Align(
                        alignment:
                        Alignment
                            .centerLeft,
                        child:
                        Padding(
                          padding:
                          EdgeInsets.all(
                              15.0),
                          child:
                          Icon(
                            Icons
                                .delete,
                            color: Colors
                                .white,
                          ),
                        ),
                      ),
                    ),
                    secondaryBackground:
                    Container(
                      color: Colors
                          .red,
                      child:
                      const Align(
                        alignment:
                        Alignment
                            .centerRight,
                        child:
                        Padding(
                          padding:
                          EdgeInsets.all(
                              15.0),
                          child:
                          Icon(
                            Icons
                                .delete,
                            color: Colors
                                .white,
                          ),
                        ),
                      ),
                    ),
                    key:
                    UniqueKey(),
                    onDismissed:
                        (direction) {
                      DatabaseService()
                          .deleteTask(
                          completedTasks[index]
                              .id);
                      AwesomeNotifications()
                          .cancelSchedule(
                          completedTasks[index]
                              .id);
                    },
                    child: Item(
                      task:
                      completedTasks[
                      index],
                    ),
                  );
                },
              ),
            ),
          );
        }),

you force non null value here你在这里强制非 null 值

 List<Task> completedTasks =snapshot.data!;
// this caused issue

add conditon like this像这样添加条件

StreamBuilder<List<Task>>(
   stream: DatabaseService().getCompletedTasks(orderName),
   builder: (context, snapshot) {
      
      if(snapshot.hasData){
       // Returns whether this snapshot contains a non-null [data] value.
       //your widget list
       // display widget when it success
      }else if(snapshot.hasError){
        //your widget show error state
        // display when error occured
      }else{
      // your default widget,
      // like loader , etc
      // display while loading run the function stream
      }
   )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter:查询firebase实时数据库数据列表,streambuilder出错 - Flutter: querying firebase realtime database data list with streambuilder error Flutter 错误:添加空安全后,StreamProvider 需要 initialData 参数。 流提供者<usermodel>来自 firebase</usermodel> - Flutter Error: StreamProvider requires initialData parameter after null-safety added. StreamProvider<UserModel> from firebase Flutter 在使用 StreamBuilder 从 firebase 加载数据之前显示红色错误屏幕,如何解决? - Flutter show's a red error screen before loading data from firebase using StreamBuilder, how to fix? 我正在尝试从 FireBase 读取信息,但出现此错误。 如何解决? - I'm trying to read information from FireBase, but I get this error. How to fix it? Flutter &amp; Firebase streamBuilder 分页 - Flutter & Firebase streamBuilder paginantion 当我尝试从 firebase 检索数据到 viewpager2 时,无法将 java.util.HashMap 类型的值转换为字符串错误 - Failed to convert value of type java.util.HashMap to String error when I'm trying to retrieve data from firebase to viewpager2 我正在尝试使用 Firebase 在 Flutter 中使用 Google 注销,但它不起作用 - I'm trying to signOut with google in Flutter with Firebase and it doesn't work 在Flutter中使用带有FireBase数据的StreamBuilder时,如何将ListView替换为GroupedListView? - How to replace ListView with GroupedListView while using StreamBuilder with FireBase data in Flutter? 我正在尝试将图像上传到 firebase 存储并获取下载 url - I'm trying to upload an image to firebase storage and get the download url 我在我的 todo 应用程序中遇到 null 安全问题 - I'm having issue with null safety in my todo app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM