Search code examples
flutterdartdart-null-safety

i checked for null and still the null safety is bugging me in flutter


              case ConnectionState.done:
                {
                  if (taskData.data != Null) {
                    return Padding(
                      padding: EdgeInsets.all(8.0),
                      child: ListView.builder(
                        itemCount : taskData.data.length,
                        itemBuilder: (context, index) {
                          String task =
                              taskData.data[index]['task'].toString();
                          String day = DateTime.parse(
                                  taskData.data[index]['creationDate'])
                              .day
                              .toString();
                        },
                      ),
                    );
The property 'length' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!').
Missing case clause for 'none'.
Try adding a case clause for the missing constant, or adding a default clause.dart
The body might complete normally, causing 'null' to be returned, but the return type, 'Widget', is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.

im getting these errors

i checked in an if statement that supposed to be a solution but it didnt fix it tried Null and null same issue

im still noob im sorry if its simple but couldnt find an answer

edit

 child: FutureBuilder(
              future: getTasks(),
              builder: (_, taskData) {
               if (taskData.data != null){
                print(taskData.data);
               }
}
The body might complete normally, causing 'null' to be returned, but the return type, 'Widget', is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.

the error after making taskData


Solution

  • Provide datatype on FutureBuilder/StreamBuilder and use taskData.data?.length on itemCount.

     FutureBuilder<List<ModelClass>?>(
    builder: (context, taskData) {
    //... others
      if (taskData.data != null) {
        return ListView.builder(
          itemCount: taskData.data?.length,
          itemBuilder: (context, index) => Text(""),
        );
      }
      // To handle body retun null
      return Text("");   
    },
    ),
    

    This error message show because you are your FutureBuilder is missing default return.

    The body might complete normally, causing 'null' to be returned,