Home > Software engineering >  Migrating project to null safety not achieved
Migrating project to null safety not achieved

Time:06-21

I am trying to migrate an old Flutter project to Null Safety.

There is a ListView.builder where I get the list items from a API.

This is the old code:

 Expanded(
                  child: Container(
                    child: FutureBuilder(
                      future: fetchClinicas(miId),
                      builder: (context, snapshot) {
                        print("SNAPSHOT   "   snapshot.hasData.toString());

                        if (snapshot.hasData) {
                          return ListView.builder(
                            itemCount: snapshot.data.length,
                            shrinkWrap: true,
                            itemBuilder: (BuildContext context, index) {
                              print(index.toString());
                              Clinica clinica = snapshot.data[index];

Using the same code in my new app, there are a couple of errors.

First error at line

itemCount: snapshot.data.length,

The error output for the first error is:

The property 'length' can't be unconditionally accessed because the receiver can be 'null'

I have changed the line with

itemCount: snapshot.data?.length,

But the error is not gone.

And the second error is at line

Clinica clinica = snapshot.data[index];

The error output for the second error is

The method '[]' can't be unconditionally invoked because the receiver can be 'null'

I have changed this second line with

Clinica clinica = snapshot.data![index];

but the error is not gone.

I would like to know how to make the code Null Safety compliant.

CodePudding user response:

Try the migration tool which will migrate your codes easily. Check this for reference

https://dart.dev/null-safety/migration-guide

Also for the issues that you are facing on each error if you hover on it, it should show a suggestion to add a null check operator ! Or ? Please note if you add an exclamation mark it means that the data is not null and if you add a ? It means that the data can be null or may have a value in it.

Clinica? clinica = snapshot.data![index'];

You can add a ? After the datatype which would mention that clinica can be null too. You may get other errors of you add a ? Here please make sure you add clinica! Wherever you use this variable

  • Related