Home > Back-end >  I see this eroor when run my app type 'string' is not a subtype of type 'int' of
I see this eroor when run my app type 'string' is not a subtype of type 'int' of

Time:01-04

when I want to get a value from a json form in flutter, i face this error it says

type 'String' is not a subtype of type 'int' of 'index'

and Im using http: ^0.13.4 and this is my code

void getData() async{

  Response res=await get("https://something.com");
  String dat=res.body;
  var datta=jsonDecode(dat)['title'];

  print(datta);

  }

how can I fix this problem?

CodePudding user response:

dont forget to write Uri.parse

void getData() async{

  Response res=await get(Uri.parse("https://something.com"));
  String dat=res.body;
  var datta=jsonDecode(dat)['title'];

  print(datta);

  }

CodePudding user response:

You should handle the request in this way, worked for me:

void getData() async {
  String baseUrl = "something.com";
  String endpoint = "/your/endpoint";
  
  Uri url = Uri.https(baseUrl, endpoint, {});

  http.Response response = await http.get(url);

  // Error handling
  // if (response.statusCode != "200") {
  //   sendError();
  // }

  String stringBody = response.body;
}

Then you convert the string into a JSON object using dart:convert library:

import "dart:convert";

// Json object
Map<String, dynamic> jsonVar = json.decode(stringBody) as Map<String, dynamic>;

That should be enough, but I suggest you to implement a model class to handle your response, and another model to handle the kind of object you are working with (e.g. Book, Post, Product, etc).

  •  Tags:  
  • Related