Home > OS >  Type error while fetching data from API while using Future builder
Type error while fetching data from API while using Future builder

Time:06-20

_TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List')

This is my http method class:

List<Property>? areaview;
Future<void> fetcharea() async {
  final response = await http.get(
      Uri.parse('https://arz-e-nafees.nafeessolutions.com/public/api/view'));
  if (response.statusCode == 200) {
    var property = (json.decode(response.body));
    Areaview viewarea = Areaview.fromJson(property);
    areaview = viewarea.properties;
    return property;
  } else {
    throw Exception('Unexpected error occured!');
  }
}

This is my model class:

// To parse this JSON data, do
//
//     final areaview = areaviewFromJson(jsonString);

import 'dart:convert';

Areaview areaviewFromJson(String str) => Areaview.fromJson(json.decode(str));

String areaviewToJson(Areaview data) => json.encode(data.toJson());

class Areaview {
  Areaview({
    required this.properties,
  });

  List<Property> properties;

  factory Areaview.fromJson(Map<String, dynamic> json) => Areaview(
        properties: List<Property>.from(
            json["properties"].map((x) => Property.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "properties": List<dynamic>.from(properties.map((x) => x.toJson())),
      };
}

class Property {
  Property({
    required this.propertyImage,
    required this.propertyTitle,
    required this.locationCity,
    required this.locationArea,
    required this.propertyDescription,
    required this.propertyPrice,
  });

  String? propertyImage;
  String propertyTitle;
  String locationCity;
  String locationArea;
  String propertyDescription;
  String propertyPrice;

  factory Property.fromJson(Map<String, dynamic> json) => Property(
        propertyImage:
            json["property_image"] == null ? null : json["property_image"],
        propertyTitle: json["property_title"],
        locationCity: json["location_city"],
        locationArea: json["location_area"],
        propertyDescription: json["property_description"],
        propertyPrice: json["property_price"],
      );

  Map<String, dynamic> toJson() => {
        "property_image": propertyImage == null ? null : propertyImage,
        "property_title": propertyTitle,
        "location_city": locationCity,
        "location_area": locationArea,
        "property_description": propertyDescription,
        "property_price": propertyPrice,
      };
}

And this is my future builder:

FutureBuilder(
              future: fetcharea(),
              builder: (context, AsyncSnapshot snapshot) {
                if (!snapshot.hasData) {
                  return Center(child: CircularProgressIndicator());
                } else {
                  return VerticalCards(snapshot.data);
                }
              },
            ),

here is a screenshot of exception enter image description here

data type I am getting after return from http method:

enter image description here

The problem is I am return when I try to return Areaview type then I cannot return property in vertical cards and when I return property type then I cannot return Areaview.

Edit: Vertical Cards class

// ignore_for_file: prefer_const_constructors, must_be_immutable, use_key_in_widget_constructors, sized_box_for_whitespace

import 'package:arzenafees/Components/Constants.dart';
import 'package:arzenafees/model/areaview.dart';
import 'package:arzenafees/services/areaviewapi.dart';
import 'package:flutter/material.dart';

class VerticalCards extends StatelessWidget {
  List<Areaview> areaData;
  VerticalCards(this.areaData);
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(color: Constants.colorSecond),
      height: MediaQuery.of(context).size.height,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: areaData.length,
        itemBuilder: (context, index) {
          final String? image = areaData[index] as String;

          return Container(
              // width: MediaQuery.of(context).size.width * 0.6,
              child: Padding(
            padding: const EdgeInsets.all(12.0),
            child: Card(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(15.0),
              ),
              child: SizedBox(
                  width: 300,
                  height: 180,
                  child: GestureDetector(
                    onTap: () {},
                    child: Stack(alignment: Alignment.bottomLeft, children: [
                      Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(15.0)),
                          image: DecorationImage(
                            image: NetworkImage(image!),
                            fit: BoxFit.fill,
                          ),
                        ),
                      ),
                    ]),
                  )),
            ),
          ));
        },
      ),
    );
  }
}

CodePudding user response:

Try it and tell me if have any problem

 Future fetcharea() async {
      final response = await http.get(
          Uri.parse('https://arz-e-nafees.nafeessolutions.com/public/api/view'));
      if (response.statusCode == 200) {
        return areaviewFromJson(response.body).properties;
      } else {
        throw Exception('Unexpected error occured!');
      }
    }



FutureBuilder(
                  future: fetcharea(),
                  builder: (context, AsyncSnapshot snapshot) {
                    if (!snapshot.hasData) {
                      return Center(child: CircularProgressIndicator());
                    } else {
                      final data = snapshot.data
                      return VerticalCards(data);
                    }
                  },
                ),
  • Related