0
votes

I have this variables problem this is my getdata function

Future <List <Deal>> getData() async{


String myUrl = "http://10.25.20.27:5000/api/all";
var response = await http.get(myUrl,
    headers: {
      'Accept':'application/json',

    });

var jsonData = json.decode(response.body);

List<Deal> deals =[];

var u;

for( u in jsonData){

  Deal deal = Deal(u["id"],u["name"],u["adress"],u["photo"],u["Description"],u["discount"]);

}


return deals;
}

And I got this error

Performing hot reload... Reloaded 14 of 594 libraries in 902ms. E/flutter ( 4211): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index' E/flutter ( 4211): #0 DatabaseHelper.getData (package:flutter_app/databasehelper.dart:116:25) E/flutter ( 4211): E/flutter ( 4211): #1 _HomeePageState.build. (package:flutter_app/homee_page.dart:100:80) E/flutter ( 4211): #2 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:654:14) E/flutter ( 4211): #3 _InkResponseState.build. (package:flutter/src/material/ink_well.dart:729:32) E/flutter ( 4211): #4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24) E/flutter ( 4211): #5 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:365:11) E/flutter ( 4211): #6 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:275:7) E/flutter ( 4211): #7 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:455:9)

1
try printing u variable to see whats inside: print(u);pskink
Can you share response JSON and Deal class for best to understand issue?Nikhil Vadoliya
when i print u i get null and thisi the response.body [[{id: 1, name: adresse Marrakech, adress: guéliz, photo: , Description: C'est un endroit zwiiin, discount: 30 }, {id: 2, name: Bogato, adress: guéliz, photo: , Descri ption: bniiinnn, discount: Offres }]]Halima Ouatab
so you mean that u is null inside for( u in jsonData){ loop?pskink
this is the whole loop : for( u in jsonData){ Deal deal = Deal(u["id"],u["name"],u["adress"],u["photo"],u["Description"],u["discount"]); deals.add(deal); }Halima Ouatab

1 Answers

0
votes

I think you can create "Deal" class like below:-

class Deal {
  String id;
  String name;
  String adress;
  String photo;
  String Description;
  String discount;

  Deal(
    this.id,
    this.name,
    this.adress,
    this.photo,
    this.Description,
    this.discount,
  );
}

Then you can use loop like below :-

var u;
for (u in jsonData) {
      Deal deal = Deal(
          u["id"].toString(),
          u["name"].toString(),
          u["adress"].toString(),
          u["photo"].toString(),
          u["Description"].toString(),
          u["discount"].toString());
}