for loop showing RangeError flutter - flutter

The following code shows
E/flutter ( 7354): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Exception: RangeError (index): Invalid value: Not in inclusive range 0..17: 18
E/flutter ( 7354): #0 List.[] (dart:core-patch/growable_array.dart:254:60)
E/flutter ( 7354): #1 parseStudent (package:xxx/screens/SearchActivity/main.dart:22:19)
E/flutter ( 7354): #2 _IsolateConfiguration.apply (package:flutter/src/foundation/_isolates_io.dart:81:34)
E/flutter ( 7354): #3 _spawn.<anonymous closure> (package:flutter/src/foundation/_isolates_io.dart:88:65)
E/flutter ( 7354): #4 _spawn.<anonymous closure> (package:flutter/src/foundation/_isolates_io.dart:87:5)
E/flutter ( 7354): #5 Timeline.timeSync (dart:developer/timeline.dart:163:22)
E/flutter ( 7354): #6 _spawn (package:flutter/src/foundation/_isolates_io.dart:85:35)
E/flutter ( 7354): #7 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:286:17)
E/flutter ( 7354): #8 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
this error.
Code:
Map<String, dynamic> map = json.decode(responseBody);
List<dynamic> data = map["students"];
//developer.log(data[0]);
List<Student> stL = List<Student>();
for(int i=0;data[i]!=null;i++){
Student student = Student(rollno:data[i]["username"],name:data[i]["name"],
hostel:data[i]["hostel"],room:data[i]["room"],gender:data[i]["gender"]);
stL.add(student);
}
developer.log(stL.toString());
return stL;
developer.log() is not called.Can someone give a solution?
Or is there a better way to parse the JSON to a list of Student

#Tipu solution is acceptable, but dart can provide more flexible way. You can also use the from named constructor of List.
List<Student> stL = List<Student>.from(map['students'].map((element) =>
Student(rollno:element["username"],name:element["name"],
hostel:element["hostel"],room:element["room"],gender:element["gender"])
).toList());

Instead of using List<dynamic> use Iterable.
Iterable list = map['students'];
list.forEach((element){
Student student = Student(rollno:element["username"],name:element["name"],
hostel:element["hostel"],room:element["room"],gender:element["gender"]);
stL.add(student);
});

Related

How do i resolve this issue with polyline not showing up on the map?

hoping someone is able to help me with this error i keep getting. I am using async - await method to call the function "drawPolylinefrompickuptodestination", but i keep getting this error..
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0
E/flutter ( 7629): #0 List.[] (dart:core-patch/growable_array.dart:264:36)
E/flutter ( 7629): #1 AssistantMethods.pickupToDestinationDirections (package:parcel_you_driver_app/assistant/assistant_methods.dart:52:70)
E/flutter ( 7629): <asynchronous suspension>
E/flutter ( 7629): #2 _NewTripScreenState.drawPolylineFromPickupToDestination (package:parcel_you_driver_app/mainScreens/new_trip_screen.dart:395:33)
E/flutter ( 7629): <asynchronous suspension>
E/flutter ( 7629): #3 _NewTripScreenState.build.<anonymous closure> (package:parcel_you_driver_app/mainScreens/new_trip_screen.dart:252:29)
E/flutter ( 7629): <asynchronous suspension>

Flutter get return empty body but it is not empty

as I wrote in the title I'm trying to obtain data from a server but the method http.get(Uri.parse(url)) returns empty body and od course the error caused by trying to decode an empty body,
But if I copy paste the url used before I can see the json content. How is it possible?
The function I'm using is:
Future getData ( ) async {
String url = 'http://www.viaggiatreno.it/viaggiatrenonew/resteasy/viaggiatreno/andamentoTreno/...';
http.Response response = await http.get(Uri.parse(url));
if (response.statusCode == 204) {
var data = response.body;
print("data are : $data");
return jsonDecode(data);
} else {
print("unable to load data");
}
}
This is a little portion of what I should see with this command: print("data are : $data");
{
"tipoTreno":"PG",
"orientamento":"B",
"codiceCliente":1,
"fermateSoppresse":[
],
"dataPartenza":null,
"fermate":[
{
"orientamento":"B",
"kcNumTreno":null,
"stazione":"VENEZIA SANTA LUCIA",
"id":"S02593",
"listaCorrispondenze":null,
"programmata":1646663160000,
"programmataZero":null,
"effettiva":1646663160000,
"ritardo":0,
"partenzaTeoricaZero":1646663160000,
"arrivoTeoricoZero":null,
"partenza_teorica":1646663160000,
"arrivo_teorico":null,
"isNextChanged":false,
"partenzaReale":1646663160000,
"arrivoReale":null,
"ritardoPartenza":0,
"ritardoArrivo":0,
"\"pro ...........}"
so as you can see the body is what you want but not empty, and it is in json format.
Can anyone help me? I can't solve this issue.
Output is:
I/flutter (3177): data are:
E/flutter ( 3177): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: FormatException: Unexpected end of input (at character 1)
E/flutter ( 3177):
E/flutter ( 3177): ^
E/flutter ( 3177):
E/flutter ( 3177): #0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1405:5)
E/flutter ( 3177): #1 _ChunkedJsonParser.close (dart:convert-patch/convert_patch.dart:523:7)
E/flutter ( 3177): #2 _parseJson (dart:convert-patch/convert_patch.dart:41:10)
E/flutter ( 3177): #3 JsonDecoder.convert (dart:convert/json.dart:612:36)
E/flutter ( 3177): #4 JsonCodec.decode (dart:convert/json.dart:216:41)
E/flutter ( 3177): #5 jsonDecode (dart:convert/json.dart:155:10)
E/flutter ( 3177): #6 NetworkHelper.ottieniTutteInfo (package:agenda_ferrovia/utilities/networkConnection.dart:36:14)
E/flutter ( 3177): <asynchronous suspension>
E/flutter ( 3177): #7 _ServizioUIAggiungiTrenoState.build.ottieniOrigine (package:agenda_ferrovia/screens/servizioUI/servizioUI_singolo.dart:110:33)
E/flutter ( 3177): <asynchronous suspension>
E/flutter ( 3177): #8 _ServizioUIAggiungiTrenoState.build.<anonymous closure> (package:agenda_ferrovia/screens/servizioUI/servizioUI_singolo.dart:231:23)
E/flutter ( 3177): <asynchronous suspension>
E/flutter ( 3177):
Thanks all for the support! I've found the issue!
Some part of the 'url's String' comes from another call.
Inside a variable there was the "hidden chars" \n. That was the cause of the issue -.-
I've solved removing all chars except letters before save into variable used for the 'url'.
I hope that my English was clear enough to understand.
Bye!

Error calling provider on button click (FORM SAVED)

I am posting a map on button click using provider, which calls Chopper service to post a map data to the server. It gives an error to the server which is something like this.
I/flutter ( 4801): Observatory listening on ************************************
E/flutter ( 4801): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Converting object to an encodable object failed: Instance of 'DateTime'
E/flutter ( 4801): #0 _JsonStringifier.writeObject (dart:convert/json.dart:688:7)
E/flutter ( 4801): #1 _JsonStringifier.writeMap (dart:convert/json.dart:769:7)
E/flutter ( 4801): #2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:724:21)
E/flutter ( 4801): #3 _JsonStringifier.writeObject (dart:convert/json.dart:679:9)
E/flutter ( 4801): #4 _JsonStringStringifier.printOn (dart:convert/json.dart:877:17)
E/flutter ( 4801): #5 _JsonStringStringifier.stringify (dart:convert/json.dart:862:5)
E/flutter ( 4801): #6 JsonEncoder.convert (dart:convert/json.dart:262:30)
E/flutter ( 4801): #7 JsonCodec.encode (dart:convert/json.dart:172:45)
E/flutter ( 4801): #8 JsonConverter.encodeJson
E/flutter ( 4801): #9 JsonConverter.convertRequest
E/flutter ( 4801): #10 ChopperClient._encodeRequest
E/flutter ( 4801): #11 ChopperClient._handleRequestConverter
E/flutter ( 4801): #12 ChopperClient.send
E/flutter ( 4801): #13 _$PersonalPostingService.postPersonal
E/flutter ( 4801): #14 _FormState.build.<anonymous closure>.<anonymous closure>
E/flutter ( 4801): #15 _FormState.build.<anonymous closure>.<anonymous closure>
E/flutter ( 4801): #33 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:282:7)
E/flutter ( 4801): #34 _dispatchPointerDataPacket (dart:ui/hooks.dart:96:31)
E/flutter ( 4801):
Exited (1)
This is where I am calling the function the body is a MAP of string, dynamic
child: RaisedButton(
onPressed: () async {
final form = _formKey.currentState;
if (form!.validate()) {
form.save();
showNotification();
await Provider.of<PersonalPostingService>(
context,
listen: false)
.postPersonal(data);
}
},
child: Text('Save'))),
The GET requests are working fine and are easily being displayed in a listview but the POST function is not working, just for the reference below is the chopper service for POST
#Post(path: 'http://157.......:8040/personal')
Future<Response> postPersonal(
#Body() Map<String, dynamic> body,
);

How to convert JSON response to Dart Map<String, int> object ...?

I'm getting data from my api as a following JSON object to create chart with the data. I want to covert this DIO response to a Map<String, int> object in my flutter app.
My API response:
{
"November 20": 1,
"October 20": 3,
"September 20": 1
}
My try of creating a map object:
Future<bool> fetchChartData() async {
var response = await CasesApiService().getChartData();
Map<String, dynamic> data = jsonDecode(response.data);
}
But it shows the following error:
E/flutter ( 4733): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
E/flutter ( 4733): #0 CasesProvider.fetchChartData
package:bdopsApp/providers/casesProvider.dart:86
E/flutter ( 4733): <asynchronous suspension>
E/flutter ( 4733): #1 _CasesChartViewState.build.<anonymous closure>
package:bdopsApp/…/casesApp/casesChart.dart:31
E/flutter ( 4733): #2 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:985
E/flutter ( 4733): #3 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:1101
E/flutter ( 4733): #4 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:183
E/flutter ( 4733): #5 TapGestureRecognizer.handleTapUp
package:flutter/…/gestures/tap.dart:598
E/flutter ( 4733): #6 BaseTapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:287
E/flutter ( 4733): #7 BaseTapGestureRecognizer.handlePrimaryPointer
package:flutter/…/gestures/tap.dart:222
E/flutter ( 4733): #8 PrimaryPointerGestureRecognizer.handleEvent
package:flutter/…/gestures/recognizer.dart:476
E/flutter ( 4733): #9 PointerRouter._dispatch
package:flutter/…/gestures/pointer_router.dart:77
E/flutter ( 4733): #10 PointerRouter._dispatchEventToRoutes.<anonymous closure>
package:flutter/…/gestures/pointer_router.dart:122
E/flutter ( 4733): #11 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter ( 4733): #12 PointerRouter._dispatchEventToRoutes
package:flutter/…/gestures/pointer_router.dart:120
E/flutter ( 4733): #13 PointerRouter.route
package:flutter/…/gestures/pointer_router.dart:106
E/flutter ( 4733): #14 GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:368
E/flutter ( 4733): #15 GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:348
E/flutter ( 4733): #16 RendererBinding.dispatchEvent
package:flutter/…/rendering/binding.dart:268
E/flutter ( 4733): #17 GestureBinding._handlePointerEventImmediately
package:flutter/…/gestures/binding.dart:303
E/flutter ( 4733): #18 GestureBinding.handlePointerEvent
package:flutter/…/gestures/binding.dart:267
E/flutter ( 4733): #19 GestureBinding._flushPointerEventQueue
package:flutter/…/gestures/binding.dart:225
E/flutter ( 4733): #20 GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:208
E/flutter ( 4733): #21 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 4733): #22 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 4733): #23 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 4733): #24 _invoke1 (dart:ui/hooks.dart:265:10)
E/flutter ( 4733): #25 _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5)
N.B: I'm doing my final year project. Therefore, the process I'm following might not be what is used in real world project.
If you run the following example in the dartPad you will get the result that you are looking for:
import 'dart:convert';
void main() {
var jsonString= "{\"November 20\": \"1\",\"October 20\": \"2\",\"September 20\": \"3\"}";
Map<String, dynamic> data = jsonDecode(jsonString);
print(data);
}
I think you need to check the data that you are getting it from the response.data

How to save values from query in shared_preferences with conditional statement flutter

I have a query function for data from the database that comes with the id number from the database, then the id is saved in shared_preferences in case the new id that comes from the database is larger than the old id that was in the shared_preferences previously.But after running the code, the following problem comes:
E/flutter (30884): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: Class 'String' has no instance method '<'.
E/flutter (30884): Receiver: ""
E/flutter (30884): Tried calling: <(7)
E/flutter (30884): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter (30884): #1 AddCommentsState.getLogin.<anonymous closure> (package:flutter_apptestqeuriy/AddComment.dart:84:46)
E/flutter (30884): #2 State.setState (package:flutter/src/widgets/framework.dart:1240:30)
E/flutter (30884): #3 AddCommentsState.getLogin (package:flutter_apptestqeuriy/AddComment.dart:78:5)
E/flutter (30884): <asynchronous suspension>
E/flutter (30884): #4 AddCommentsState.initState.<anonymous closure> (package:flutter_apptestqeuriy/AddComment.dart:57:9)
E/flutter (30884): #5 interval.function (package:flutter_apptestqeuriy/AddComment.dart:21:9)
E/flutter (30884): #6 _rootRun (dart:async/zone.dart:1182:47)
E/flutter (30884): #7 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (30884): #8 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter (30884): #9 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter (30884): #10 _rootRun (dart:async/zone.dart:1190:13)
E/flutter (30884): #11 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (30884): #12 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
E/flutter (30884): #13 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter (30884): #14 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:397:19)
E/flutter (30884): #15 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:428:5)
E/flutter (30884): #16 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter (30884):
This is the code used to query from the database:
var user_id;
var my_pre_id;
Future<String> getLogin() async {
var response = await http.get(Uri.encodeFull("http://xxxxxxxxxxx/Application.php"),);
setState(() {
var convertDataToJson = json.decode(response.body);
data = convertDataToJson['result'];
if (data != null) {
user_id = int.parse(data[0]['id']);
my_pre_id = _myPreferences.id;
if (my_pre_id == null || my_pre_id < user_id ){
_myPreferences.id = user_id;
_myPreferences.commit();
// print("tappeeeeedddd $my_pre_id");
}
}
});
}
Does anyone know the cause of the problem?
I think the issue comes from my_pre_id < user_id where my_pre_id is actually a String. You might want to do an int.parse() on it as well or change its type in the class.