Flutter - Map JSON - flutter

I am new to DART / FLUTER and still have a lot of difficulties. I have a registration function and I need to return 2 attributes that are within a Json MAP. Constructs the function below but returns error
[ERROR: flutter / lib / ui / ui_dart_state.cc (157)] Unhandled Exception: type _InternalLinkedHashMap ' is not a subtype of type List
Can you help me?
About my code:
saveClient(Cliente cliente) async {
final Map<String, dynamic> clienteMap = {
"nome": cliente.nome,
"email": cliente.email,
"senha": cliente.senha,
"celular": cliente.celular,
};
final String clientJson = jsonEncode(clienteMap);
client.post(baseUrl + '/usuario',
headers: {'Content-type': 'application/json', 'password': 'admin'},
body: clientJson);
final Response response = await client.get(baseUrl + '/usuario/id');
final List<dynamic> decodedJson = jsonDecode(response.body);
final List<ClienteDto> dataUser = List();
for (Map<String, dynamic> clienteJson in decodedJson) {
final ClienteDto cliente = ClienteDto(
clienteJson['id'],
clienteJson['nome'],
);
dataUser.add(cliente);
print(dataUser);
}
return dataUser;
}

You're trying to assign your decoded JSON response, which is Map, to a List which isn't a valid assignment. You should try printing the result of jsonDecode(response.body) to figure out where the actual portion of the result you care about is within the response.

This is my all code of class WebClient:
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart';
import 'package:http_interceptor/http_interceptor.dart';
import 'package:owlwee/Models/Cartao.dart';
import 'package:owlwee/Models/Cliente.dart';
import 'package:owlwee/Models/ClienteDto.dart';
final Client client =
HttpClientWithInterceptor.build(interceptors: [LoggingInterceptor()]);
const String baseUrl = 'http://xxxxxxxxxxxxxx:8080'; // LEROMA
const String baseUrlCheckIn = 'http://xxxxxxxxxxxxx:8081'; // LEROMA
class LoggingInterceptor implements InterceptorContract {
#override
Future<RequestData> interceptRequest({RequestData data}) async {
print('Request');
print('Headers: ${data.headers}');
print('body: ${data.body}');
return data;
}
#override
Future<ResponseData> interceptResponse({ResponseData data}) async {
print('Status ${data.statusCode}');
print('Headers: ${data.headers}');
print('body: ${data.body}');
return data;
}
}
saveClient(Cliente cliente) async {
final Map<String, dynamic> clienteMap = {
"nome": cliente.nome,
"email": cliente.email,
"senha": cliente.senha,
"celular": cliente.celular,
};
final String clientJson = jsonEncode(clienteMap);
client.post(baseUrl + '/usuario',
headers: {'Content-type': 'application/json', 'password': 'admin'},
body: clientJson);
final Response response = await client.get(baseUrl + '/usuario/id');
final List<dynamic> decodedJson = jsonDecode(response.body);
final List<ClienteDto> dataUser = List();
for (Map<String, dynamic> clienteJson in decodedJson) {
final ClienteDto cliente = ClienteDto(
clienteJson['id'],
clienteJson['nome'],
);
dataUser.add(cliente);
print(dataUser);
}
return dataUser;
}
And this is answer of console:
√ Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...
Syncing files to device Android SDK built for x86...
I/flutter (15631): Request
I/flutter (15631): Headers: {Content-type: application/json; charset=utf-8, password: admin}
I/flutter (15631): body: {"nome":"Hudson","email":"hudson#email.com","senha":"123456","celular":21987987987}
I/flutter (15631): Request
I/flutter (15631): Headers: {}
I/flutter (15631): body:
I/flutter (15631): Status 400
I/flutter (15631): Headers: {connection: close, content-type: application/json, date: Wed, 05 Feb 2020 00:38:37 GMT, transfer-encoding: chunked}
I/flutter (15631): body: {"timestamp":"2020-02-05T00:38:37.040+0000","status":400,"error":"Bad Request","message":"Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: \"id\"","trace":"org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: \"id\"\r\n\tat org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:133)\r\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(Invocable
E/flutter (15631): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'
E/flutter (15631): #0 saveClient (package:owlwee/http/webclient.dart:83:23)
E/flutter (15631): <asynchronous suspension>
E/flutter (15631): #1 _CadastroState.build.<anonymous closure> (package:owlwee/Views/Cadastro.dart:192:25)
E/flutter (15631): #2 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (15631): #3 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (15631): #4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (15631): #5 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (15631): #6 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (15631): #7 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:236:7)
E/flutter (15631): #8 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter (15631): #9 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20)
E/flutter (15631): #10 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (15631): #11 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (15631): #12 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (15631): #13 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (15631): #14 _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (15631): #15 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (15631): #16 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (15631): #17 _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (15631): #18 _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
E/flutter (15631):
I/flutter (15631): Status 201
I/flutter (15631): Headers: {content-type: application/json, location: http://192.168.1.9:8080/usuario/9, date: Wed, 05 Feb 2020 00:38:37 GMT, transfer-encoding: chunked}
I/flutter (15631): body: {"id":9,"nome":"Hudson"}
Is that what you asked?

Related

Null Check operator used on a null value on flutter with Sqflite

I'm studying flutter with Sqflite and trying to make a small app, but I'm getting this error when I run the code, I've looked literaly everywhere to findout what it could be.
Here the code code who use the Sqflite package:
Future<Database> getDatabase() async {
final String path = join(await getDatabasesPath(), 'bytebank.db');
return openDatabase(path, onCreate: (db, version) {
db.execute('CREATE TABLE contacts'
'(id INTEGER PRIMARY KEY, '
'name TEXT, '
'account_number INTEGER)');
}, version: 1);
}
Future<int> save(Contact contact) async {
final Database db = await getDatabase();
final Map<String, dynamic> contactMap = Map();
contactMap['name'] = contact.name;
contactMap['account_number'] = contact.account;
contactMap['id'] = contact.id;
return db.insert('contacts', contactMap);
}
Future<List<Contact>> findAll() async {
final Database db = await getDatabase();
final List<Map<String, dynamic>> result = await db.query('contacts');
final List<Contact> contacts = [];
for (Map<String, dynamic> row in result) {
final Contact contact = Contact(
row['id'],
row['name'],
row['account_number'],
);
contacts.add(contact);
}
return contacts;
}
And here is the only one place where I use This functions:
void main() {
save(Contact('William', 2, 13456)).then((id) {
findAll().then((contacts) => print(contacts));
});
runApp(ByteBankApp());
}
Model Class:
class Contact {
final String name;
final int account;
final int id;
Contact( this.id,
this.name,
this.account,
);
#override
String toString() {
return 'Contact{name: $name, account: $account}';
}
}
Error Trace back:
Launching lib\main.dart on sdk gphone x86 arm in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Debug service listening on ws://127.0.0.1:52296/07rtnvW9tlQ=/ws
Syncing files to device sdk gphone x86 arm...
E/flutter (28649): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
E/flutter (28649): #0 MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:142:86)
E/flutter (28649): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:148:36)
E/flutter (28649): #2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:331:12)
E/flutter (28649): #3 invokeMethod (package:sqflite/src/sqflite_impl.dart:17:13)
E/flutter (28649): #4 SqfliteDatabaseFactoryImpl.invokeMethod (package:sqflite/src/factory_impl.dart:82:7)
E/flutter (28649): #5 SqfliteDatabaseFactoryMixin.safeInvokeMethod.<anonymous closure> (package:sqflite_common/src/factory_mixin.dart:41:38)
E/flutter (28649): #6 wrapDatabaseException (package:sqflite/src/exception_impl.dart:7:32)
E/flutter (28649): #7 SqfliteDatabaseFactoryImpl.wrapDatabaseException (package:sqflite/src/factory_impl.dart:78:7)
E/flutter (28649): #8 SqfliteDatabaseFactoryMixin.safeInvokeMethod (package:sqflite_common/src/factory_mixin.dart:41:7)
E/flutter (28649): #9 SqfliteDatabaseFactoryMixin.getDatabasesPath (package:sqflite_common/src/factory_mixin.dart:153:26)
E/flutter (28649): #10 getDatabasesPath (package:sqflite/sqflite.dart:161:54)
E/flutter (28649): #11 getDatabase (package:bytebank/database/app_database.dart:6:34)
E/flutter (28649): #12 save (package:bytebank/database/app_database.dart:16:29)
E/flutter (28649): #13 main (package:bytebank/main.dart:7:3)
E/flutter (28649): #14 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:142:25)
E/flutter (28649): #15 _rootRun (dart:async/zone.dart:1354:13)
E/flutter (28649): #16 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (28649): #17 _runZoned (dart:async/zone.dart:1789:10)
E/flutter (28649): #18 runZonedGuarded (dart:async/zone.dart:1777:12)
E/flutter (28649): #19 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:138:5)
E/flutter (28649): #20 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter (28649): #21 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter (28649):
I am not sure if will help, but I was running into a similar issue when initializing a database in an async "main" method. Adding the following:
WidgetsFlutterBinding.ensureInitialized();
inside the method before the code initializing the database solved the problem.

Multipe images uploading on server not working flutter

I am trying to upload multiple images to server but always get issues. I tried some other solutions as well but not working.
saveImages() async {
// string to uri
Uri uri = Uri.parse('http://100.0.50.10:8000/API/AddImageCarSale/Post');
// create multipart request
MultipartRequest request = http.MultipartRequest("POST", uri);
if (images != null) {
for (var i = 0; i < images.length; i++) {
ByteData byteData = await images[i].getByteData();
List<int> imageData = byteData.buffer.asUint8List();
MultipartFile multipartFile = MultipartFile.fromBytes(
'photo', //key of the api
imageData,
filename: images[i].name,
contentType: MediaType("image",
"jpg"), //this is not nessessory variable. if this getting error, erase the line.
);
request.fields['PhoneNo'] = '1122';
request.fields['VehicleNo'] = '1234';
// add file to multipart
request.files.add(multipartFile);
// send
var response = await request.send();
}
}
}
My error is
[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: Bad state: Can't finalize a finalized Request.
E/flutter (11521): #0 BaseRequest.finalize (package:http/src/base_request.dart:104:20)
E/flutter (11521): #1 MultipartRequest.finalize (package:http/src/multipart_request.dart:92:11)
E/flutter (11521): #2 IOClient.send (package:http/src/io_client.dart:28:26)
E/flutter (11521): #3 BaseRequest.send (package:http/src/base_request.dart:119:35)
E/flutter (11521): #4 _SellerFormState.savedNew (package:Autolog/pages/buySell/sellerForm.dart:361:38)
E/flutter (11521):
E/flutter (11521): #5 _SellerFormState._buildBody. (package:Autolog/pages/buySell/sellerForm.dart:754:25)
E/flutter (11521): #6 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
E/flutter (11521): #7 _InkResponseState.build. (package:flutter/src/material/ink_well.dart:1098:38)
E/flutter (11521): #8 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter (11521): #9 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter (11521): #10 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter (11521): #11 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:256:7)
E/flutter (11521): #12 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:158:27)
E/flutter (11521): #13 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:224:20)
E/flutter (11521): #14 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter (11521): #15 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter (11521): #16 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter (11521): #17 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter (11521): #18 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter (11521): #19 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter (11521): #20 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter (11521): #21 _invoke1 (dart:ui/hooks.dart:267:10)
E/flutter (11521): #22 _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
E/flutter (11521):
You need to create a new multipart request for every loop as multipart request gets finalized.
Try this modification and it should work.
// string to uri
Uri uri = Uri.parse('http://100.0.50.10:8000/API/AddImageCarSale/Post');
// create multipart request
if (images != null) {
for (var i = 0; i < images.length; i++) {
MultipartRequest request = http.MultipartRequest("POST", uri);
ByteData byteData = await images[i].getByteData();
List<int> imageData = byteData.buffer.asUint8List();
MultipartFile multipartFile = MultipartFile.fromBytes(
'photo', //key of the api
imageData,
filename: images[i].name,
contentType: MediaType("image",
"jpg"), //this is not nessessory variable. if this getting error, erase the line.
);
request.fields['PhoneNo'] = '1122';
request.fields['VehicleNo'] = '1234';
// add file to multipart
request.files.add(multipartFile);
// send
var response = await request.send();
}
}
}

flutter ClientException in http requests

This is the function containing the request :
Future<String> getRequest(String serviceName, Map<String, String> a) async {
var responseBody = '{"data": "", "status": "NOK"}';
try {
http.Response response =
await http.get(_urlBase + '$_serverApi$serviceName', headings: a);
if (response.statusCode == 200) {
responseBody = response.body;
}
} catch (e) {
// An error was received
throw new Exception("GET ERROR");
}
return responseBody;
}
and this is where i call it :
void _confirm() async {
if (_formKey.currentState.saveAndValidate()) {
print(_formKey.currentState.value);
Map<String, String> c =
Map<String, String>.from(_formKey.currentState.value);
// just below
var a = await auth.getRequest('se_connecter', c);
print(a);
} else {
print(_formKey.currentState.value);
print("validation failed");
}
}
everytime i try it, the code in the try bloc fails, and it throws the exception (ClientException after i removed try and catch bloc)
This the exception stacktrace :
I/flutter (10979): #0 IOClient.send
package:http/src/io_client.dart:65
I/flutter (10979): <asynchronous suspension>
I/flutter (10979): #1 BaseClient._sendUnstreamed
package:http/src/base_client.dart:176
I/flutter (10979): #2 BaseClient.get
package:http/src/base_client.dart:35
I/flutter (10979): #3 get.<anonymous closure>
package:http/http.dart:46
I/flutter (10979): #4 _withClient
package:http/http.dart:166
I/flutter (10979): #5 get
package:http/http.dart:46
I/flutter (10979): #6 getRequest
package:event_app/auth.dart:125
I/flutter (10979): #7 ConnectPageState._confirm
package:event_app/pages/connect_page.dart:28
I/flutter (10979): #8 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:706
I/flutter (10979): #9 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:789
I/flutter (10979): #10 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:182
I/flutter (10979): #11 TapGestureRecognizer.handleTapUp
package:flutter/…/gestures/tap.dart:486
I/flutter (10979): #12 BaseTapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:264
I/flutter (10979): #13 BaseTapGestureRecognizer.
In my case (sometimes instead of blank appeared the error "HttpException: Connection closed before full header was received") the call was to an https address using Microsoft Internet Information Services as backend, in the SSL settings of the website in IIS i had mistakenly set "Client certificates: Accept" instead of "Client certificates: Ignore", setting "Ignore" solved the problem.
Solved, the problem was the ssl encryption, so i removed it from my backend.

Unable to retrieve fetch ID data from API. How to fix?

I want to fetch details of a product by retrieving its ID and by accessing its Id to load the details needed but I keep getting an error that I dont quite understand?
here is my provider data:
class AddCar {
int id;
String name;
String city;
String country;
String currencyT;
double price;
String date;
int sponsNum;
String category;
String company;
String model;
String year;
String engine;
double distanceCovered;
String transmission;
String oilT;
String outColor;
String inColor;
String description;
File image;
PlaceLocation location;
bool isFavorite;
AddCar({
this.id,
this.name,
this.city,
this.country,
this.currencyT,
this.price,
this.date,
this.sponsNum,
this.category,
this.company,
this.model,
this.year,
this.engine,
this.distanceCovered,
this.transmission,
this.oilT,
this.outColor,
this.inColor,
this.description,
this.image,
this.location,
this.isFavorite = false,
});
}
class PlaceLocation {
final double latitude;
final double longitude;
final String address;
const PlaceLocation({
this.address,
this.latitude,
this.longitude,
});
}
Here is how im fetching the data (i have a link to a custome ID that im clicking on to lead to that product):
Future<void> fetchAndSetCarDetails() async {
const url = 'customLink/Detail?Id=204';
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
List<AddCar> loadedCars = [];
extractedData.forEach((carId, carData) {
loadedCars.add(AddCar(
id: int.parse(carId),
name: carData['adTitle'],
sponsNum: carData['adNumber'],
price: carData['adPrice'],
date: carData['adDate'],
model: carData['brandModel'],
year: carData['modelYear'],
distanceCovered: carData['kilometer'],
transmission: carData['gearType'],
oilT: carData['fuelType'],
location: carData['adLocation'][PlaceLocation(
address: carData['adAddress'],
latitude: carData['lath'],
longitude: carData['lang'],
)],
description: carData['adDetails'],
country: carData['country'],
city: carData['cityName'],
category: carData['category'],
company: carData['brand'],
engine: carData['cylinder'],
outColor: carData['exteriorColor'],
inColor: carData['interiorColor'],
));
});
_cars = loadedCars;
print(response.body);
notifyListeners();
}
Here is the print data I get:
I/flutter (13626): {"id":204,"adTitle":null,"adDate":"2019-11-07T11:52:40.0156875","adPrice":25.0,"adNumber":195,"adAddress":"AdAddressssssss","adLocation":{"lath":"40.959028921030104","lang":" 30.992774628906318"},"adDetails":null,"country":227,"cityName":"Stockholm","category":"car child 1","categoryId":7,"brand":"mercedes","brandId":1,"brandModelId":6,"brandModel":"M300","cylinder":"6C","kilometer":300.0,"modelYear":"2010","fuelType":"benz","gearType":"automatic","exteriorColor":"red","interiorColor":"yellow","carType":1,"image":[],"isFavorite":false,
Here is the error I get when I click on the product to access its details:
E/flutter (13626): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: FormatException: Invalid radix-10 number (at character 1)
E/flutter (13626): id
E/flutter (13626): ^
E/flutter (13626):
E/flutter (13626): #0 int._throwFormatException (dart:core-patch/integers_patch.dart:131:5)
E/flutter (13626): #1 int._parseRadix (dart:core-patch/integers_patch.dart:142:16)
E/flutter (13626): #2 int._parse (dart:core-patch/integers_patch.dart:100:12)
E/flutter (13626): #3 int.parse (dart:core-patch/integers_patch.dart:63:12)
E/flutter (13626): #4 Cars.fetchAndSetCarDetails.<anonymous closure>
package:flutter_app/providers/car_provider.dart:88
E/flutter (13626): #5 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter (13626): #6 Cars.fetchAndSetCarDetails
package:flutter_app/providers/car_provider.dart:86
E/flutter (13626): <asynchronous suspension>
E/flutter (13626): #7 _MyCarDetailsState.initState.<anonymous closure>
package:flutter_app/details/car_details.dart:23
E/flutter (13626): #8 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter (13626): #9 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter (13626): #10 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
E/flutter (13626): #11 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
E/flutter (13626): #12 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
E/flutter (13626): #13 Future._complete (dart:async/future_impl.dart:512:7)
E/flutter (13626): #14 new Future.delayed.<anonymous closure> (dart:async/future.dart:313:16)
E/flutter (13626): #15 _rootRun (dart:async/zone.dart:1120:38)
E/flutter (13626): #16 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (13626): #17 _CustomZone.runGuarded (dart:async/zone.dart:923:7)
E/flutter (13626): #18 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
E/flutter (13626): #19 _rootRun (dart:async/zone.dart:1124:13)
E/flutter (13626): #20 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (13626): #21 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:947:23)
E/flutter (13626): #22 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:21:15)
E/flutter (13626): #23 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:382:19)
E/flutter (13626): #24 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:416:5)
E/flutter (13626): #25 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)
E/flutter (13626):
You have several problems.
1 - your forEach closure looks like you are expecting the JSON to include a list of cars that you are going to add to loadedCars but it does not - there's just one car. That's why extractedData is a Map<String, dynamic> not a List<Map<String, dynamic>>.
2 - that means that the forEach closures is iterating over the members of the map so gets called once with carId='id' and carData=204 and then again with carId='adPrice' and carData=25.0 etc. This is clearly not what you're expecting! The exception happens when you try to parse 'id' into an int.
Given that there's only one car in your current json you can dispense with the loop. You should extract that one car like:
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
var theOneCar = AddCar(
id: extractedData['id'], // no need for parse either - id is already an int
name: extractedData['adTitle'],
// etc
// etc
print (theOneCar);

Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index' Problem Dart & flutter

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)
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());
}