Search code examples
fluttergetflutter-dependencies

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:

data from json

I saw also this error:

StateError (Bad state: Stream has already been listened to.)

and this error:

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 T made:

enter image description here

I don't know what is the problem because the print function return : []


Solution

  • 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;