there is null there, after first null I get nulls after it, cause it got caught but exception, how to make exception?enter image description here. As you can see in picture, vehichles and starship are null, and caught by exeption, after them there is 3 data, they become null too. When i remove vehichles and starship everything is ok How to make it ? I wanna get null for vehichles and starship and get data normally after them(Soryy for my English)
Future<dynamic> getSwData() async{
return await MyStarWarsService().getDataFromSWApi().then((value) async{
if(value != null){
setState((){
name = value!.name!;
height = value!.height!;
mass = value!.mass!;
birth_year = value!.birth_year!;
eye_color = value!.eye_color!;
films = value!.films!;
gender = value!.gender!;
hair_color = value!.hair_color!;
homeworld = value!.homeworld!;
skin_color = value!.skin_color!;
vehicles = value.vehcles; //// it is NULL
starships = value.starsips;// it is NUll
species = value!.species!;/// NOT null
created = value!.created!;//// NOT null but come NUll
edited = value!.edited!;//// NOT null but come NULL
url = value!.url!;//// NOT null, but come NULL
});
return value;
}
},
).catchError((_){
throw Exception("Exception is caught"); this exception caught null and after it everithings become null
});
}
}
HTTP 200 OK Content-Type: application/json Vary: Accept Allow: GET, HEAD, OPTIONS
{ "name": "C-3PO", "height": "167", "mass": "75", "hair_color": "n/a", "skin_color": "gold", "eye_color": "yellow", "birth_year": "112BBY", "gender": "n/a", "homeworld": "https://swapi.dev/api/planets/1/", "films": [ "https://swapi.dev/api/films/1/", "https://swapi.dev/api/films/2/", "https://swapi.dev/api/films/3/", "https://swapi.dev/api/films/4/", "https://swapi.dev/api/films/5/", "https://swapi.dev/api/films/6/" ], "species": [ "https://swapi.dev/api/species/2/" ], "vehicles": [], it null
"starships": [], it is null
"created": "2014-12-10T15:10:51.357000Z", afetr i get nulls for this but it is not null
"edited": "2014-12-20T21:17:50.309000Z",
"url": "https://swapi.dev/api/people/2/"
}
CodePudding user response:
I am struggling to understand the question (poor English), but it seems like you want to accept null as the value if it I null. If that's true, using the ! after the value tells the code that you are sure there is a non null value. Change the ! to ? to allow null.
For example:
name = value!.name!;
becomes
name = value.name?;
Name can now have a null value.
I suggest you research null safety.
CodePudding user response:
If you use async and await in your future and at the end SetState after Then, you will need to check the mounted in the tree like that :
Future<dynamic> getSwData() async{
return await MyStarWarsService().getDataFromSWApi().then((value){
if(this.mounted){
// add your SetState
}
}
}
This is a good habit to do.