'type 'String' is not a subtype of type 'Null' in get method flutter
I got this error: type 'String' is not a subtype of type 'Null' in get method flutter
this is the get api function that i use
Future<Stream<ServiceTypes>> getServiceTypesa() async {
final String url = 'https://test.com';
final client = new http.Client();
final streamedRest = await client.send(
http.Request('get', Uri.parse(url))
);
return streamedRest.stream
.transform(utf8.decoder)
.transform(json.decoder)
.expand((data) => (data as List))
.map((data) => ServiceTypes.fromJson(data));
}
you can see here the function detect the data
i saw also this error
StateError (Bad state: Stream has already been listened to.)
and this error
this is my listen function
@override
void initState() {
_serviceTypes = new List<ServiceTypes>();
listenForServiceTypes();
super.initState();
}
void listenForServiceTypes() async {
setState(() {
this._show_serviceTypesProgress = true;
});
final Stream<ServiceTypes> stream = await getServiceTypesa();
stream.listen((ServiceTypes serviceTypes) =>
setState(() => _serviceTypes.add(serviceTypes)));
setState(() {
this._show_serviceTypesProgress = false;
});
print(_serviceTypes);
}
this is the model that i made
I don't know what is the problem because the print function return : []
Solution 1:[1]
When you create model, the image type value is null so, the model is create with Null type of image but when images are not null type from server then it gives you an error
type 'String' is not a subtype of type 'Null' in get method flutter
because your image type is String from server and you get value by Null Object, So use String type object for getting string value or images.
Use this
Class ServiceTypes{
String image;
instead of
Class ServiceTypes{
Null image;
Solution 2:[2]
The issue is clear, you define image type as Null then trying to pass string to it, try to change definition.. like so:
Class ServiceTypes{
int id;
String name;
String image;
...
Solution 3:[3]
As extra information, you can check the keys name. I faced the same problem just because I tried to fetch a key not found.
In the first time I wrote content instead of details and in my API I have details not content.
have a good day :)
Solution 4:[4]
use ? this for nullable key. For example :
final String? title; final String? category;
here is the complete solution : Is it possible to parse json in Flutter/Dart with missing attributes (keys of json data)?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Avinash |
| Solution 2 | Mohamed Sayed |
| Solution 3 | Ethan |
| Solution 4 | gurjeet |



