Flutter get return empty body but it is not empty - flutter

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!

Related

How to convert the type Future<List<T>> to <List<T>> in fultter?

everyone! I was developing e-commerce flutter app with doofinder APIs.
But I faced a thorny problem. I tried to get data from doofinder(it's just search service) API then present to screen. I added screen-shots.
Future<List<Product>> fetchProduct(query) async {
var response = await http.get(
Uri.parse(
'https://eu1-search.doofinder.com/5/search?hashid=30a5f&query=$query'),
// Send authorization headers to the backend.
headers: {'Authorization': 'c59dadc5d822ca2b134f170'},
);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
print(jsonDecode(response.body)['results'].toList().runtimeType);
return jsonDecode(response.body)['results'].toList().cast<List<Product>>();
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
then,
onChanged: (_) => EasyDebounce.debounce(
'tFMemberController',
const Duration(milliseconds: 800),
() {
isSearchStarted =
textController!.text.isNotEmpty &&
textController!.text.trim().length > 0;
print('isSearchStarted $isSearchStarted');
if (isSearchStarted) {
print('${textController!.text.trim()}');
searchedProducts =
fetchProduct(textController!.text)
as List<Product>;
print(searchedProducts);
}
setState(() {});
},
),
And this is error log.
E/flutter ( 5295): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'Future<List<Product>>' is not a subtype of type 'List<Product>' in type cast
E/flutter ( 5295): #0 _SearchPageState.build.<anonymous closure>.<anonymous closure> (package:s4s_mobileapp/search/page_search.dart:151:41)
E/flutter ( 5295): #1 EasyDebounce.debounce.<anonymous closure> (package:easy_debounce/easy_debounce.dart:44:22)
E/flutter ( 5295): #2 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter ( 5295): #3 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter ( 5295): #4 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter ( 5295): #5 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
E/flutter ( 5295):
I/flutter ( 5295): List<dynamic>
E/flutter ( 5295): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'CastList<dynamic, List<Product>>' is not a subtype of type 'FutureOr<List<Product>>'
E/flutter ( 5295): #0 fetchProduct (package:s4s_mobileapp/search/page_search.dart:41:58)
E/flutter ( 5295): <asynchronous suspension>
E/flutter ( 5295):
This makes me crazy.
I want you to take a closer look at the pictures below and find a suitable solution please.
Change
jsonDecode(response.body)['results'].toList().cast<List<Product>>();
to this:
jsonDecode(response.body)['results'].toList().cast<Product>();
The cast method already knows that you are working with lists and only wants to know the type of the elements, but not the type of the list itself.
EDIT: You also need to change:
searchedProducts = fetchProduct(textController!.text) as List<Product>;
to this:
searchedProducts = fetchProduct(textController!.text) as Future<List<Product>>;
You have to work with futures as your result is processed asynchronously. In the widget tree you have to use FutureBuilder which takes a future and builds your list as you want.

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>

for loop showing RangeError 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);
});

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.

Simple GET API request in Flutter

I'm trying to use a simple GET requests in REST to flutter, but have an error
Code:
Future<Map> timeStamp() async {
const request =
"https://armariosinteligentes.com/api/v3/timestamp";
http.Response response = await http.get(request);
print(json.decode(response.body));
}
json: {"timestamp":1566397501}
Error:
E/flutter ( 7041): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: HandshakeException: Handshake error in client (OS Error:
E/flutter ( 7041): BLOCK_TYPE_IS_NOT_01(padding.c:108)
E/flutter ( 7041): PADDING_CHECK_FAILED(rsa_impl.c:641)
E/flutter ( 7041): public key routines(a_verify.c:105)
E/flutter ( 7041): CERTIFICATE_VERIFY_FAILED: certificate signature failure(handshake.cc:352)) E/flutter ( 7041):
#0 IOClient.send (package:http/src/io_client.dart:33:23) E/flutter ( 7041): <asynchronous suspension> E/flutter ( 7041):
#1 BaseClient._sendUnstreamed (package:http/src/base_client.dart:169:38) E/flutter ( 7041): <asynchronous suspension> E/flutter ( 7041):
#2 BaseClient.get (package:http/src/base_client.dart:32:7) E/flutter ( 7041):
#3 get.<anonymous closure> (package:http/http.dart:46:36) E/flutter ( 7041):
#4 _withClient (package:http/http.dart:166:20) E/flutter ( 7041): <asynchronous suspension> E/flutter ( 7041):
#5 get (package:http/http.dart:46:5) E/flutter ( 7041):
#6 timeStamp (package:armarios_inteligentes/screens/locker_screen.dart:196:34) E/flutter ( 7041): <asynchronous suspension> E/flutter ( 7041):
#7 LockerScreenState.build.<anonymous closure> (package:armarios_inteligentes/screens/locker_screen.dart:114:15) E/flutter ( 7041):
#8 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:635:14) E/flutter ( 7041):
#9 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:711:32) E/flutter ( 7041):
#10 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24) E/flutter ( 7041): #11 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:365:11) E/flutter ( 7041):
#12 TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:312:7) E/flutter ( 7041):
#13 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27) E/flutter ( 7041):
#14 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20) E/flutter ( 7041):
#15 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22) E/flutter ( 7041):
#16 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7) E/flutter ( 7041):
#17 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7) E/flutter ( 7041):
#18 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7) E/flutter ( 7041):
#19 _rootRunUnary (dart:async/zone.dart:1136:13) E/flutter ( 7041):
#20 _CustomZone.runUnary (dart:async/zone.dart:1029:19) E/flutter ( 7041):
#21 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7) E/flutter ( 7041):
#22 _invoke1 (dart:ui/hooks.dart:250:10) E/flutter ( 7041):
#23 _dispatchPointerDataPacket (dart:ui/hooks.dart:159:5) E/flutter ( 7041):
timeStamp() async {
final response =
await http.get('http://armariosinteligentes.com/api/v3/timestamp');
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON.
var jsonResponse = json.decode(response.body);
tempoStamp tempo = new tempoStamp.fromJson(jsonResponse);
var time = ('${tempo.timestamp}');
return time;
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load post');
}
}
Result: 1566411603
Try to remove the https and put http instead. And verify your connection, you need to know if you can call websites like this in your local...