The getter 'data' was called on null in response - flutter

I expext response.data to be when i got an error 422, like
{
"message": "You can NOT add a penalty!"
}
but i have an error The getter 'data' was called on null.
Future transferCoinsToUser(
String apiToken, String recipientBill, int coin) async {
Response response;
try {
response = await _dio.post(apiEndpoint + "bills/transfer",
options: Options(headers: {"Authorization": apiToken}),
data: {"recipient_bill": recipientBill, "coin": coin});
if(response.statusCode == 200){
print('status cod ' + response.statusCode.toString());
print('response bady ' + response.data.toString());//{message: completed successfully.}
}
} on DioError catch (error) {
print(error);
print(response.data);// The getter 'data' was called on null.
return null;
}
}
my stack trace
NoSuchMethodError: The getter 'data' was called on null.
I/flutter ( 7462): Receiver: null
I/flutter ( 7462): Tried calling: data
I/flutter ( 7462): NoSuchMethodError: The getter 'data' was called on null.
I/flutter ( 7462): Receiver: null
I/flutter ( 7462): Tried calling: data
I/flutter ( 7462): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
I/flutter ( 7462): #1 ApiProvider.transCoinToUser (package:no_fine/data/api_provider.dart:104:22)
I/flutter ( 7462): <asynchronous suspension>
I/flutter ( 7462): #2 TransferRepositoryImpl.transCoinToUser (package:no_fine/data/repository/transfer_repo.dart:37:20)
I/flutter ( 7462): <asynchronous suspension>
I/flutter ( 7462): #3 TransferBloc._mapTransferCoinsToUserToState (package:no_fine/bloc/auth/translations_bloc/translations_bloc.dart:42:33)
I/flutter ( 7462): <asynchronous suspension>
I/flutter ( 7462): #4 TransferBloc.mapEventToState (package:no_fine/bloc/auth/translations_bloc/translations_bloc.dart:26:14)
I/flutter ( 7462): <asynchronous suspension>
I/flutter ( 7462): #5 Bloc._bindEventsToStates.<anonymous closure> (package:bloc/src/bloc.dart:232:20)
I/flutter ( 7462): #6 Stream.asyncExpand.<anonymous closure>.<anonymous closure> (dart:async/stream.dart:644:30)
I/flutter ( 7462): #7 _rootRunUnary (dart:async/zone.dart:1198:47)
I/flutter ( 7462): #8 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
I/flutter ( 7462): #9 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
I/flutter ( 7462): #10 _BufferingStreamSubscription._sendData (dart:a

response might be null. You are calling .data on null hence the error. Try
print(response?.data)
or check
if(response != null) print(response.data);

You can't access the Response object, when you have an error. Instead, Please use below code:
on DioError catch (error) {
print(error);
print(error.response.data);// Here you will find the error response in error object
return null;
}

You can check your request host. In Android device you can not use the request host like "localhost" or "127.0.0.1" directly because this is the Android device's host and this is not your API host.You should use your API host's IP which like "http://192.168.50.123/request?foo=bar".

Related

Flutter Retrofit upload multipart throws 415 Unsupported Media Type

I'm trying to upload an image using Multipart from Flutter Retrofit using this code
#POST("apiUrl/upload/files")
#MultiPart()
Future<TSSuccessResponse<UploadFileRemoteResponse>> uploadFile(
#Part() File file);
However it keeps getting error 415 that says application/form-octet is not supported MediaType.
E/flutter ( 8367): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DioError [bad response]: The request returned an invalid status code of 415.
E/flutter ( 8367): #0 DioMixin.fetch.<anonymous closure> (package:dio/src/dio_mixin.dart:530:7)
E/flutter ( 8367): #1 _RootZone.runBinary (dart:async/zone.dart:1665:54)
E/flutter ( 8367): #2 _FutureListener.handleError (dart:async/future_impl.dart:162:22)
E/flutter ( 8367): #3 Future._propagateToListeners.handleError (dart:async/future_impl.dart:779:47)
E/flutter ( 8367): #4 Future._propagateToListeners (dart:async/future_impl.dart:800:13)
E/flutter ( 8367): #5 Future._completeError (dart:async/future_impl.dart:575:5)
E/flutter ( 8367): #6 _SyncCompleter._completeError (dart:async/future_impl.dart:51:12)
E/flutter ( 8367): #7 _Completer.completeError (dart:async/future_impl.dart:23:5)
E/flutter ( 8367): #8 Future.any.onError (dart:async/future.dart:617:45)
E/flutter ( 8367): #9 _RootZone.runBinary (dart:async/zone.dart:1665:54)
E/flutter ( 8367): #10 _FutureListener.handleError (dart:async/future_impl.dart:162:22)
E/flutter ( 8367): #11 Future._propagateToListeners.handleError (dart:async/future_impl.dart:779:47)
E/flutter ( 8367): #12 Future._propagateToListeners (dart:async/future_impl.dart:800:13)
E/flutter ( 8367): #13 Future._completeError (dart:async/future_impl.dart:575:5)
E/flutter ( 8367): #14 Future._asyncCompleteError.<anonymous closure> (dart:async/future_impl.dart:666:7)
E/flutter ( 8367): #15 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 8367): #16 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
I/flutter ( 8367): ╔ DioErrorType.badResponse
I/flutter ( 8367): ║ {
I/flutter ( 8367): ║ statusCode: 415,
I/flutter ( 8367): ║ "File type application/octet-stream is not matching: image, pdf, powerpoint, prese
I/flutter ( 8367): ║ ntation, video, video/quicktime"
I/flutter ( 8367): ║ error: "Unsupported Media Type"
I/flutter ( 8367): ║ }
I/flutter ( 8367): ╚══════════════════════════════════════════════════════════════════════════════════════════╝
Then I tried to change the request to include content-type in the #Part() tag as someone mentioned, so that it satisfies the generated file from Retrofit.
#POST("apiUrl/upload/files")
#MultiPart()
Future<TSSuccessResponse<UploadFileRemoteResponse>> uploadFile(
#Part(contentType: "image/png") File file);
But it throw another error, that is
E/flutter ( 8367): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DioError [bad response]: The request returned an invalid status code of 415.
E/flutter ( 8367): #0 DioMixin.fetch.<anonymous closure> (package:dio/src/dio_mixin.dart:530:7)
E/flutter ( 8367): #1 _RootZone.runBinary (dart:async/zone.dart:1665:54)
E/flutter ( 8367): #2 _FutureListener.handleError (dart:async/future_impl.dart:162:22)
E/flutter ( 8367): #3 Future._propagateToListeners.handleError (dart:async/future_impl.dart:779:47)
E/flutter ( 8367): #4 Future._propagateToListeners (dart:async/future_impl.dart:800:13)
E/flutter ( 8367): #5 Future._completeError (dart:async/future_impl.dart:575:5)
E/flutter ( 8367): #6 _SyncCompleter._completeError (dart:async/future_impl.dart:51:12)
E/flutter ( 8367): #7 _Completer.completeError (dart:async/future_impl.dart:23:5)
E/flutter ( 8367): #8 Future.any.onError (dart:async/future.dart:617:45)
E/flutter ( 8367): #9 _RootZone.runBinary (dart:async/zone.dart:1665:54)
E/flutter ( 8367): #10 _FutureListener.handleError (dart:async/future_impl.dart:162:22)
E/flutter ( 8367): #11 Future._propagateToListeners.handleError (dart:async/future_impl.dart:779:47)
E/flutter ( 8367): #12 Future._propagateToListeners (dart:async/future_impl.dart:800:13)
E/flutter ( 8367): #13 Future._completeError (dart:async/future_impl.dart:575:5)
E/flutter ( 8367): #14 Future._asyncCompleteError.<anonymous closure> (dart:async/future_impl.dart:666:7)
E/flutter ( 8367): #15 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 8367): #16 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
I/flutter ( 8367): ╔ DioErrorType.badResponse
I/flutter ( 8367): ║ {
I/flutter ( 8367): ║ statusCode: 415,
I/flutter ( 8367): ║ message: "File type is not matching",
I/flutter ( 8367): ║ error: "Unsupported Media Type"
I/flutter ( 8367): ║ }
I/flutter ( 8367):
I also tried chaging the contentType to "image/*" but it throws error on the MediaType.parser (from the generated file) saying that it's an invalid type.
Is there anything I'm missing in this scenario? Have anyone solved this problem before? I tried solutions mentioned by [1],[2] and many others but still stuck in this problem. Thx in advance.
One thing to note: This request works normally in Postman with the same file.

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.

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!

How to handle exeptions in flutter

How to handle exeptions in flutter?
Why i cant have response.data?
...................................
rhtrhehrh regjnoeriwjgnowiermnfgorewmfelrg
Future addFine(String apiToken, String uin, int type) async {
try {
Response response = await _dio.post(apiEndpoint + "fines",
options: Options(headers: {"Authorization": apiToken}),
data: {"uin": uin, "type": type});
print(response.data);
print(response.statusMessage);
print(response.statusCode);
} catch (error, stacktrace) {
print(error);
print(stacktrace);
return null;
}
}
my stack trace
I/flutter ( 5580): DioError [DioErrorType.RESPONSE]: Http status error [422]
I/flutter ( 5580): #0 DioMixin._dispatchRequest (package:dio/src/dio.dart:966:7)
I/flutter ( 5580): <asynchronous suspension>
I/flutter ( 5580): #1 DioMixin._request._interceptorWrapper.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:dio/src/dio.dart:849:37)
I/flutter ( 5580): #2 DioMixin.checkIfNeedEnqueue (package:dio/src/dio.dart:1121:22)
I/flutter ( 5580): #3 DioMixin._request._interceptorWrapper.<anonymous closure>.<anonymous closure> (package:dio/src/dio.dart:846:22)
I/flutter ( 5580): #4 new Future.<anonymous closure> (dart:async/future.dart:175:37)
I/flutter ( 5580): #5 _rootRun (dart:async/zone.dart:1182:47)
I/flutter ( 5580): #6 _CustomZone.run (dart:async/zone.dart:1093:19)
I/flutter ( 5580): #7 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
I/flutter ( 5580): #8 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
I/flutter ( 5580): #9 _rootRun (dart:async/zone.dart:1190:13)
I/flutter ( 5580): #10 _CustomZone.run (dart:async/zone.dart:1093:19)
I/flutter ( 5580): #11 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
I/flutter ( 5580): #12
Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15
If you consider codes that indicate an error valid information and want to access the information anyway, you can decide yourself, what you consider an error:
Response response = await _dio.post(apiEndpoint + "fines",
options: Options(
headers: {"Authorization": apiToken},
validateStatus: (status) => true),
data: {"uin": uin, "type": type});
In the options, you can pass a validator that decides what status codes are valid. In this case I just made it use any code. any code at all. You may want to restrict that further to your usecase, maybe even per call. For example, you could restrict it to "OK" and "Unprocessable Entity", where for example a 401 would still throw an exception:
validateStatus: (status) => { return status == 200 || status == 422; }

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.