Home > Net >  Included null safety libs and now code is not running
Included null safety libs and now code is not running

Time:09-17

I have used null safety libs. Now am getting this problem. Please see the screenshot. Even after adding a null check, it's not going.

enter image description here

body: FutureBuilder(
    future: allPerson(),
    builder: (context, snapshot) {
      if (snapshot.hasError) print(snapshot.error);
      return snapshot.hasData
          ? ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, index) {
                List list = snapshot.data;
                return Card(
                  child: ListTile(
                    title: Container(
                      width: 100,
                      height: 100,
                      child: Image.network(
                          "http://192.168.1.101/image_upload_php_mysql/uploads/${list[index]['image']}"),
                    ),
                    subtitle: Center(child: Text(list[index]['name'])),
                  ),
                );
              })
          : Center(
              child: CircularProgressIndicator(),
            );
    },
  ),

Thanks.

CodePudding user response:

You can give a type to your returned value(s) from future function for snapshot data.

FutureBuilder<List<dynamic>>(
        future: allPerson(),
        builder: (context, AsyncSnapshot<List<dynamic>> snapshot) {
          if (snapshot.hasError) print(snapshot.error);
          return snapshot.hasData
              ? ListView.builder(
                  itemCount: snapshot.data!.length,
                  itemBuilder: (context, index) { ...

CodePudding user response:

snapshot.data can be null. So you should use snapshot.data?.length ?? 0

So if snapshot.data is null then it will set length as 0.

CodePudding user response:

just do this itemCount: snapshot.data!.length

and the problem will gone

CodePudding user response:

In null safety, you can not set a nullable variable(a variable that can be set as null) to non nullable variable(a variable that doesn't accept the value null).
Here itemCount is non nullable variable, however the variable data is nullable, and may not be available to access the variable length.

itemCount: snapshot.data.length

Try altering it to the following code

itemCount: snapshot.data?["length"] ?? 0
  • Related