I am trying to get data from an API to my flutter, but I keep getting this error:
Please help have spend days on this single error!
Here is my code
welcome_screen.dart
// ignore_for_file: prefer_const_constructors, unused_import
import 'dart:html';
import 'package:barakh_sooq/components/foot_navigation_bar.dart';
import 'package:barakh_sooq/components/custom_drawer.dart';
import 'package:barakh_sooq/config.dart';
import 'package:barakh_sooq/constants.dart';
import 'package:barakh_sooq/data.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:convert'; // for using json.decode()
import 'dart:developer';
import 'package:http/http.dart' as http;
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:barakh_sooq/models/home.dart';
// import 'package:barakh_sooq/repos/home_repo.dart';
Future<List<Ads>> getAds() async {
final response = await http.get(Uri.parse("http://localhost:4000/home"));
// log(response.body);
if (response.statusCode == 200) {
final parsed = jsonDecode(response.body).cast<Map<String, dynamic>>();
log(parsed);
return parsed.map<Ads>((json) => Ads.fromJson(json)).toList();
} else {
throw Exception('Failed to load album');
}
}
class WelcomeScreen extends StatelessWidget {
const WelcomeScreen({Key? key}) : super(key: key);
static String routeID = 'welcome_screen';
@override
Widget build(BuildContext context) {
return WelcomeScreenView();
}
}
class WelcomeScreenView extends StatefulWidget {
const WelcomeScreenView({Key? key}) : super(key: key);
@override
_WelcomeScreenViewState createState() => _WelcomeScreenViewState();
}
class _WelcomeScreenViewState extends State<WelcomeScreenView> {
final GlobalKey<ScaffoldState> _key = GlobalKey<ScaffoldState>();
late bool _navIsVisible;
late ScrollController _hideBottomNavController;
late Future<List<Ads>> futureAds;
@override
void initState() {
super.initState();
futureAds = getAds();
_navIsVisible = true;
_hideBottomNavController = ScrollController();
_hideBottomNavController.addListener(() {
if (_hideBottomNavController.position.userScrollDirection ==
ScrollDirection.reverse) {
if (_navIsVisible) {
setState(() {
_navIsVisible = false;
});
}
}
if (_hideBottomNavController.position.userScrollDirection ==
ScrollDirection.forward) {
if (!_navIsVisible) {
setState(() {
_navIsVisible = true;
});
}
}
});
}
@override
void dispose() {
_hideBottomNavController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
SizeConfig().screenSizeInit(context);
return Scaffold(
key: _key,
drawer: CustomDrawer(),
body: FutureBuilder<List<Ads>>(
future: futureAds,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Container(
child: Text(snapshot.error.toString()),
);
} else if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) => ListTile(
title: Text(snapshot.data![index].itemTitle),
subtitle: Text(
"Here",
softWrap: false,
overflow: TextOverflow.ellipsis,
),
),
);
}
return Center(
child: CircularProgressIndicator(),
);
},
));
}
}
home_repo.dart
import 'dart:developer';
import 'package:http/http.dart' as http;
import 'package:barakh_sooq/models/home.dart';
import 'dart:convert';
class HomeRepository {
Future<List<Ads>> getAds() async {
final response = await http.get(Uri.parse("http://localhost:4000/home"));
// log(response.body);
if (response.statusCode == 200) {
final parsed = jsonDecode(response.body).cast<Map<String, dynamic>>();
log(parsed);
return parsed.map<Ads>((json) => Ads.fromJson(json)).toList();
} else {
throw Exception('Failed to load album');
}
}
}
home.dart(model)
import 'dart:convert';
import 'dart:convert';
List<Ads> adsFromJson(String str) =>
List<Ads>.from(json.decode(str).map((x) => Ads.fromJson(x)));
class Home {
Home({
required this.category,
required this.state,
required this.ads,
});
late final List<Category> category;
late final List<Region> state;
late final List<Ads> ads;
Home.fromJson(Map<String, dynamic> json) {
category =
List.from(json['category']).map((e) => Category.fromJson(e)).toList();
state = List.from(json['state']).map((e) => Region.fromJson(e)).toList();
ads = List.from(json['ads']).map((e) => Ads.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['category'] = category.map((e) => e.toJson()).toList();
_data['state'] = state.map((e) => e.toJson()).toList();
_data['ads'] = ads.map((e) => e.toJson()).toList();
return _data;
}
}
class Ads {
Ads({
required this.id,
required this.location,
required this.category,
required this.subcategory,
required this.itemTitle,
required this.itemPrice,
required this.negotiable,
required this.phoneNumber,
required this.condition,
required this.address,
required this.description,
required this.owner,
required this.createdAt,
required this.updatedAt,
required this.V,
required this.images,
});
late final String id;
late final String location;
late final String category;
late final String subcategory;
late final String itemTitle;
late final int itemPrice;
late final bool negotiable;
late final String phoneNumber;
late final String condition;
late final String address;
late final String description;
late final String owner;
late final String createdAt;
late final String updatedAt;
late final int V;
late final List<Images> images;
Ads.fromJson(Map<String, dynamic> json) {
id = json['id'];
location = json['location'];
category = json['category'];
subcategory = json['subcategory'];
itemTitle = json['item_title'];
itemPrice = json['item_price'];
negotiable = json['negotiable'];
phoneNumber = json['phone_number'];
condition = json['condition'];
address = json['address'];
description = json['description'];
owner = json['owner'];
createdAt = json['createdAt'];
updatedAt = json['updatedAt'];
V = json['__v'];
images = List.from(json['images']).map((e) => Images.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['location'] = location;
_data['category'] = category;
_data['subcategory'] = subcategory;
_data['item_title'] = itemTitle;
_data['item_price'] = itemPrice;
_data['negotiable'] = negotiable;
_data['phone_number'] = phoneNumber;
_data['condition'] = condition;
_data['address'] = address;
_data['description'] = description;
_data['owner'] = owner;
_data['createdAt'] = createdAt;
_data['updatedAt'] = updatedAt;
_data['__v'] = V;
_data['images'] = images.map((e) => e.toJson()).toList();
return _data;
}
}
class Images {
Images({
required this.id,
required this.filename,
required this.contentType,
required this.adid,
required this.createdAt,
required this.updatedAt,
required this.V,
});
late final String id;
late final String filename;
late final String contentType;
late final String adid;
late final String createdAt;
late final String updatedAt;
late final int V;
Images.fromJson(Map<String, dynamic> json) {
id = json['id'];
filename = json['filename'];
contentType = json['contentType'];
adid = json['adid'];
createdAt = json['createdAt'];
updatedAt = json['updatedAt'];
V = json['__v'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['filename'] = filename;
_data['contentType'] = contentType;
_data['adid'] = adid;
_data['createdAt'] = createdAt;
_data['updatedAt'] = updatedAt;
_data['__v'] = V;
return _data;
}
}
This is the structure of my file:
Structure of file :
Here is the JSON Response
{
"category": [
{
"_id": "616ed1bb0b784e17e4fefc67",
"name": "Food",
"createdAt": "2021-10-19T14:10:03.361Z",
"updatedAt": "2021-10-19T14:40:50.115Z",
"__v": 0,
"subcategory": []
},
{
"_id": "616ed7e92bacf63664f36eec",
"name": "car",
"createdAt": "2021-10-19T14:36:25.567Z",
"updatedAt": "2021-10-19T14:36:25.567Z",
"__v": 0,
"subcategory": [
{
"_id": "616ee646d7f5732acc905693",
"name": "Toyota",
"category": "car",
"createdAt": "2021-10-19T15:37:42.858Z",
"updatedAt": "2021-10-19T15:37:42.858Z",
"__v": 0
},
{
"_id": "617008c79c4eb53b20573889",
"name": "Honda",
"category": "car",
"createdAt": "2021-10-20T12:17:11.467Z",
"updatedAt": "2021-10-20T12:17:11.467Z",
"__v": 0
}
]
}
],
"state": [
{
"_id": "616ff4a9220ea7072892985d",
"name": "الرياض",
"createdAt": "2021-10-20T10:51:21.962Z",
"updatedAt": "2021-10-20T10:51:21.962Z",
"__v": 0,
"city": [
{
"_id": "616ff533220ea70728929861",
"name": "الخرج",
"state": "الرياض",
"createdAt": "2021-10-20T10:53:39.139Z",
"updatedAt": "2021-10-20T10:53:39.139Z",
"__v": 0
},
{
"_id": "616ff547220ea70728929865",
"name": "الدرعية",
"state": "الرياض",
"createdAt": "2021-10-20T10:53:59.096Z",
"updatedAt": "2021-10-20T10:53:59.096Z",
"__v": 0
},
{
"_id": "616ff552220ea70728929869",
"name": "الدلم",
"state": "الرياض",
"createdAt": "2021-10-20T10:54:10.287Z",
"updatedAt": "2021-10-20T10:54:10.287Z",
"__v": 0
},
{
"_id": "616ff559220ea7072892986d",
"name": "الدوادمي",
"state": "الرياض",
"createdAt": "2021-10-20T10:54:17.834Z",
"updatedAt": "2021-10-20T10:54:17.834Z",
"__v": 0
},
{
"_id": "616ff562220ea70728929871",
"name": "الحريق",
"state": "الرياض",
"createdAt": "2021-10-20T10:54:26.079Z",
"updatedAt": "2021-10-20T10:54:26.079Z",
"__v": 0
},
{
"_id": "616ff56c220ea70728929875",
"name": "الزلفي",
"state": "الرياض",
"createdAt": "2021-10-20T10:54:36.334Z",
"updatedAt": "2021-10-20T10:54:36.334Z",
"__v": 0
}
]
},
{
"_id": "616ff57e220ea70728929879",
"name": "الشرقية",
"createdAt": "2021-10-20T10:54:54.271Z",
"updatedAt": "2021-10-20T10:54:54.271Z",
"__v": 0,
"city": [
{
"_id": "616ff589220ea7072892987d",
"name": "الدمام",
"state": "الشرقية",
"createdAt": "2021-10-20T10:55:05.258Z",
"updatedAt": "2021-10-20T10:55:05.258Z",
"__v": 0
},
{
"_id": "616ff5a5220ea70728929881",
"name": "حفر الباطن",
"state": "الشرقية",
"createdAt": "2021-10-20T10:55:33.224Z",
"updatedAt": "2021-10-20T10:55:33.224Z",
"__v": 0
}
]
}
],
"ads": [
{
"_id": "616d9af509dfe63ac8c44447",
"location": "lagos",
"category": "car",
"subcategory": "toyota",
"item_title": "Big Daddy",
"item_price": 2000,
"negotiable": true,
"phone_number": "09033536548",
"condition": "New",
"address": "Lagos",
"description": "Good car",
"owner": "6169e4aa2265f9405c4de4cb",
"createdAt": "2021-10-18T16:04:05.611Z",
"updatedAt": "2021-10-18T16:04:05.611Z",
"__v": 0,
"images": [
{
"_id": "616d9af509dfe63ac8c44449",
"filename": "images-1634573045577.png",
"contentType": "image/png",
"adid": "616d9af509dfe63ac8c44447",
"createdAt": "2021-10-18T16:04:05.611Z",
"updatedAt": "2021-10-18T16:04:05.611Z",
"__v": 0
},
{
"_id": "616d9af509dfe63ac8c44448",
"filename": "images-1634573045562.png",
"contentType": "image/png",
"adid": "616d9af509dfe63ac8c44447",
"createdAt": "2021-10-18T16:04:05.611Z",
"updatedAt": "2021-10-18T16:04:05.611Z",
"__v": 0
}
]
},
{
"_id": "616ea77e384b2f2f60c3ff38",
"location": "abuja",
"category": "car",
"subcategory": "honda",
"item_title": "Big Daddy",
"item_price": 2000,
"negotiable": true,
"phone_number": "09033536548",
"condition": "New",
"address": "Lagos",
"description": "Good car",
"owner": "6169e4aa2265f9405c4de4cb",
"createdAt": "2021-10-19T11:09:50.236Z",
"updatedAt": "2021-10-19T11:09:50.236Z",
"__v": 0,
"images": [
{
"_id": "616ea77e384b2f2f60c3ff39",
"filename": "images-1634641780856.png",
"contentType": "image/png",
"adid": "616ea77e384b2f2f60c3ff38",
"createdAt": "2021-10-19T11:09:50.237Z",
"updatedAt": "2021-10-19T11:09:50.237Z",
"__v": 0
}
]
}
]
}
CodePudding user response:
You should use
(jsonDecode(response.body) as Map<String, dynamic>)
in places where you are using .cast<Map<String,dynamic>
CodePudding user response:
It's working now, I modify my home_repo.dart as below:
class HomeRepository {
Future<List<Ads>> getAds() async {
List<Ads> _loadAds = [];
final response = await http.get(Uri.parse("http://localhost:4000/home"));
if (response.statusCode == 200) {
// List<Ads> getAdsHere = response.body["ads"] as List<Ads>;
final parsed = jsonDecode(response.body);
for (var i = 0; i < parsed["ads"].length; i ) {
Map<String, dynamic> map = parsed["ads"][i];
_loadAds.add(Ads.fromJson(map));
// _loadAds.add(parsed["ads"][i]);
}
log("Location ---------${_loadAds[0].location} ");
return _loadAds;
} else {
throw Exception('Failed to load album');
}
}
}