简体   繁体   中英

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. 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.

Add 1 condition for while loading stream data on initial stage.

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

 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
      }
   )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM