iampawan / 30DaysOfFlutter

Learn Flutter in 30 Days
410 stars 324 forks source link

ERROR in Chapter 27: Unhandled Exception: type 'Null' is not a subtype of type 'Iterable<dynamic>' #42

Closed pranjal-barnwal closed 1 year ago

pranjal-barnwal commented 1 year ago

Error in Chapter 27 (HTTP | API | Networking | Badge) while Fetching data from the jsonbin.io API

Error: Unhandled Exception: type 'Null' is not a subtype of type 'Iterable' image

Effect: Screen stuck in loading screen

pranjal-barnwal commented 1 year ago

Problem busted:

Our main json will be stored inside 'record' image

Fix

We just basically need to access first ['records'] & then ['products'] inside it, instead of directly accessing ['products']

Fixed Working Code

  Future<void> loadData() async {
    await Future.delayed(Duration(seconds: 2));
    //? earlier local json data
    // final catalogJson = await rootBundle.loadString('assets/files/catalog.json');

    //? online fetched data
    final response = await http.get(Uri.parse(url));
    print(response);
    // final catalogJson = response.body;
    // final decodedData = jsonDecode(catalogJson); 

    final decodedData = json.decode(response.body);
    print("DECODED DATA: ");
    print(decodedData);

    //? converting from string to object
    var productsData = decodedData["record"]["products"]; 

    //?picking only products
    print(productsData);

    CatalogModel.items = List.from(productsData)
        .map<Item>((item) => Item.fromMap(item))
        .cast<Item>()
        .toList();
    setState(() {});

  }