简体   繁体   中英

Flutter - Unable to get data from REST API

I am trying to load data from my REST API and load them into the UI. Below is my code

 FutureBuilder loadProductSellAds() {
    return FutureBuilder<ProductSellAdvertisement>(
      future: DataFetch().loadProductSellSingleAd(
          AppNavigation.getAPIUrl() +
              "sellAdvertisement/getAdByID/" +
              widget._advertisementID.toString()),
      builder: (context, snapshot) {
        if (snapshot.hasError) print(snapshot.error);

        if(snapshot.hasData)
        {
          ProductSellAdvertisement p = snapshot.data;

          setValuesToProductDataSection(
            type: p.type,
            location: p.location,
            quantity: p.quantity.toString(),
            stocksAvailable: p.stocksAvailableTill.toString(),
            unitPrice: p.unitPrice.toString()

          );
          displayProductInfoSection = true;
        }
      },
    );
  }

datafetch.dart

/**
   * Use to Load Product Sell Advertisements
   * 
   **/
  Future<ProductSellAdvertisement> loadProductSellSingleAd(String url) async {
    final response = await http.get(url);
    // Use the compute function to run parsePhotos in a separate isolate
    final parsed =
        convert.json.decode(response.body).cast<Map<String, dynamic>>();

    ProductSellAdvertisement obj = parsed
        .map<ProductSellAdvertisement>(
            (json) => new ProductSellAdvertisement.fromJson(json));
    return obj;
  }

and finally, the model class, product_sell_advertisement.dart

import './product.dart';
import './product_unit.dart';
import './user.dart';

import 'package:json_annotation/json_annotation.dart';


part 'product_sell_advertisement.g.dart';

@JsonSerializable()

class ProductSellAdvertisement
{
     int idproductSellAdvertisement;
     Product product;
     ProductUnit productUnits;
     User user;
     String type;
     String grade;
     double unitPrice;
     double quantity;
     String location;
     int stocksAvailableTill;
     String extraInformation;
     int expireOn;
     int deleteTimestamp;
     int dateCreated;
     int lastUpdated;

     ProductSellAdvertisement(this.idproductSellAdvertisement, this.product, this.productUnits, this.user, this.type,
     this.grade, this.unitPrice, this.quantity, this.location, this.stocksAvailableTill, this.extraInformation, this.expireOn,
     this.deleteTimestamp,this.dateCreated, this.lastUpdated);


  factory ProductSellAdvertisement.fromJson(Map<String, dynamic> json) => _$ProductSellAdvertisementFromJson(json);


  Map<String, dynamic> toJson() => _$ProductSellAdvertisementToJson(this);
}

When I execute the loadProductSellAds method (the first code in this post), I run into the below error

    [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
E/flutter ( 4670): Receiver: _LinkedHashMap len:15
E/flutter ( 4670): Tried calling: cast<Map<String, dynamic>>()
E/flutter ( 4670): Found: cast<RK, RV>() => Map<RK, RV>
E/flutter ( 4670): #0      Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
E/flutter ( 4670): #1      DataFetch.loadProductSellSingleAd 
package:xxx/custom_functions/data_fetch.dart:101
E/flutter ( 4670): <asynchronous suspension>
E/flutter ( 4670): #2      SingleSellAdvertisementState.loadProductSellAds 
package:xxx/pages/single_sell_advertisement_page.dart:225
E/flutter ( 4670): #3      SingleSellAdvertisementState.initState 
package:xxx/pages/single_sell_advertisement_page.dart:5

Why is this happening?

By definition that cast() is a method introduced in Dart 2 on Iterable that actually creates a new iterable of type Iterable (or subclass List) filled with the values of the original interable. Your source object is not an instance if Iterable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM