Trying to upload image using DIO. (error) - flutter

Hello i hope you all good. Im trying to upload an image but im stuck and getting some errors.
I/flutter (23022): El error es: DioError [DioErrorType.other]: Converting object to an encodable object failed: FormData
I/flutter (23022): #0 _JsonStringifier.writeObject (dart:convert/json.dart:794:7)
I/flutter (23022): #1 _JsonStringStringifier.printOn (dart:convert/json.dart:983:17)
I/flutter (23022): #2 _JsonStringStringifier.stringify (dart:convert/json.dart:968:5)
I/flutter (23022): #3 JsonEncoder.convert (dart:convert/json.dart:345:30)
I/flutter (23022): #4 JsonCodec.encode (dart:convert/json.dart:231:45)
I/flutter (23022): #5 DefaultTransformer.transformRequest (package:dio/src/transformer.dart:77:21)
I/flutter (23022): #6 DioMixin._transformData (package:dio/src/dio_mixin.dart:735:39)
I/flutter (23022): #7 DioMixin._dispatchRequest (package:dio/src/dio_mixin.dart:656:26)
I/flutter (23022): #8 DioMixin.fetch.<anonymous closure> (package:dio/src/dio_mixin.dart:605:7)
I/flutter (23022): #9 DioMixin.fetch._requestInterceptorWrapper.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:dio/src/dio_mixin.dart:517:28)
I/flutter (23022): #10 DioMixin.checkIfNeedEnqueue (package:dio/src/dio_mixin.dart:789:22)
I/flutter (23022): #11 DioMixin.fetch._requestInterceptorWrapper.<ano
This is my file:
https://github.com/bRUNS123/hydra
I hope someone can help me!
This is my function to upload:
void _uploadFile(filePath) async {
try {
String filename = p.basename(filePath!.path.split('/').last);
dio.FormData.fromMap({
'files': {
await dio.MultipartFile.fromFile(
filePath.path,
filename: filename,
contentType: MediaType(
'image',
'jpeg',
),
),
},
'app_label': 'files',
'app_model': 'file',
});
await Dio()
.post('http://10.0.2.2:8000/objects/', data: FormData)
.then((value) {
// if (value.toString() == '1') {
// print('La foto se ha subido correctamente');
// } else {
// print('Hubo un error');
// }
});
} catch (e) {
print('El error es: $e');
}
}
Thanks for reading and i hope someone can help me!
have a nice day!
PS: i already check my server with postman.

Use MultipartRequest class from http package instead (easiest way).
try {
MultipartRequest request = MultipartRequest(
'POST',
Uri.parse("http://10.0.2.2:8000/objects/"),
);
request.files.add(
MultipartFile.fromBytes(
'files',
(await File(filePath).readAsBytes()),
filename: p.basename(filePath.split('/').last);,
),
);
request.fields.addAll(
{
'app_label': 'files',
'app_model': 'file',
},
);
// Parse JSON Response from server {"success" : true, "message" : "..."}
var json = jsonDecode(
String.fromCharCodes(
await (await request.send()).stream.toBytes(),
),
);
} catch (e) {
debugPrint(e.toString());
}

Related

Why doesn't my method work in DioError catch in Flutter/Dart?

I am making a request to my database like this:
//Airtable (find a record)
void airtableFind() async {
try {
final response = await Dio().get(
'https://api.airtable.com/v0/'+projectBase+'/'+recordName,
queryParameters: {
'filterByFormula': 'SEARCH('+'"'+username+'"'+',{Name})' // Searches the value 'Cactus' in the {'Short description'} field.
},
options: Options(
contentType: 'Application/json',
headers: {
'Authorization': 'Bearer'+' '+apiKey,
'Accept': 'Application/json',
},
),
);
// TODO: Whatever you want to do with the response. A good practice is to transform it into models and than work with them
// print(response);
// print(response.data['records'][0]['id']);
idString = response.data['records'][0]['id'];
// if (idString.isNotEmpty) (
// showInvalidUsernameDialog(context)
// // TODO: Need to inform about success
// );
} on DioError catch (e) {
// TODO: Error handling
if (e.response != null) {
// print(e.response.data);
print(e);
showInvalidUsernameDialog(context);
} else {
// print(e.request);
print(e.message);
showInvalidUsernameDialog(context);
}
}
}
If my user enters the correct word (username), then everything works correctly. But there is always a risk that a person is mistaken. And I want to indicate this with the showInvalidUsernameDialog(context); dialog box, but for some reason it does not pop up.
I see errors in the console:
I/flutter(4484): DioError [DioErrorType.response]: Http status error [422]
I/flutter ( 4484): Source stack:
I/flutter(4484): #0 DioMixin.fetch(package:dio/src/dio_mixin.dart:488:35)
I/flutter ( 4484): #1 DioMixin.request (package:dio/src/dio_mixin.dart:483:12)
I/flutter ( 4484): #2 DioMixin.patch (package:dio/src/dio_mixin.dart:249:12)
I/flutter(4484): #3 _RouteState.airtableUpdate(package:example/main.dart:1498:36)
I/flutter ( 4484): #4 _RouteState.build.<anonymous closure> (package:example/main.dart:1617:13)
I/flutter ( 4484): #5 _RouteState.build.<anonymous closure> (package:example/main.dart:1612:24)
I/flutter(4484): #6 EditableTextState._finalizeEditing (package:flutter/src/widgets/editable_text.dart:2148:18)
I/flutter(4484): #7 EditableTextState.performAction(package:flutter/src/widgets/editable_text.dart:1999:9)
I/flutter(4484): #8 TextInput._handleTextInputInvocation(package:flutter/src/services/text_input.dart:1746:37)
I/flutter ( 4484): #9 MethodChannel._handleAsMethodCall (package:flutter/src/services/platform_channel.dart:404:55)
I/flutter ( 4484): #10 MethodChannel.setMethodCallHandler.<anonymous closure> (package:flutter/src/services/platform_chan
E/flutter ( 4484): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0
E/flutter ( 4484): #0 List.[] (dart:core-patch/growable_array.dart:264:36)
E/flutter ( 4484): #1 _RouteState.airtableFind (package:example/main.dart:1473:42)
E/flutter ( 4484): <asynchronous suspension>
E/flutter ( 4484):
And that's to be expected, since I'm deliberately entering the wrong username. But I want to get not only a list of errors in the console, but also a dialog box. Why doesn't it appear?
The dialog box call method is correct. I put it in the part of the code that fires when the username is valid. It appears exactly as intended.
But why doesn't this method work in this part of the code?
on DioError catch (e) {
// TODO: Error handling
if (e.response != null) {
// print(e.response.data);
print(e);
showInvalidUsernameDialog(context);
} else {
// print(e.request);
print(e.message);
showInvalidUsernameDialog(context);
}
And how can I make this dialog appear in case of an error?
Edit 1. _RouteState.airtableFind (package:example/main.dart:1473:42) is referring to idString = response.data['records'][0]['id'];. This happens when my user enters their login incorrectly.
Use catch directly and check if its of type DioError. This is a known behaviour.. Its not catching 400 or 500 errors
https://github.com/flutterchina/dio/issues/1198
try{
}catch(e){
print(e.toString());
}
or
try{
}catch(e){
if(e is DioError)
{
}
}

Flutter Riverpod WidgetTest not exceeding past loading state

UPDATE: Rewrote Test in a same way I test another consumer widget, which actually works, but it still doesn't work for my test and I can't get my head around why :(
Current approach:
void main() {
final List<Exercise> _mockExercises = [
Exercise(
userID: 'uid123',
title: 'Übung1',
repetitions: 10,
isCompleted: false,
isVideo: false,
unit: 'Sekunden',
description: 'Some description',
exerciseID: '42',
imageUrl: 'https://via.placeholder.com/150',
thumbUrl: 'https://via.placeholder.com/150'),
Exercise(
userID: 'uid123',
title: 'Übung2',
repetitions: 20,
isCompleted: false,
isVideo: false,
unit: 'Sekunden',
description: 'Some description2',
exerciseID: '43',
imageUrl: 'https://via.placeholder.com/150',
thumbUrl: 'https://via.placeholder.com/150'),
];
testWidgets('user exercise list - pump', (WidgetTester tester) async {
await mockNetworkImagesFor(() async {
await tester.pumpWidget(ProviderScope(
child: MyApp(),
/// overrides: provide fake asyncvalue data to stream
overrides: [
exerciseCollectionStream
.overrideWithValue(AsyncValue.data(_mockExercises))
],
));
await tester.pump();
// The first frame is a loading state.
expect(find.byType(Loading), findsOneWidget);
await tester.pumpAndSettle();
// await Future.delayed(Duration(seconds: 2));
// await tester.pumpAndSettle();
// No-longer loading
expect(find.byType(Loading), findsNothing);
});
});
}
I'm trying to write a widget test for a Listview Widget and I never get past the loading state of the "Asyncvalue".when state in my test and it is stuck in loading.
I tried to approach the test like in the Riverpod docs or as explained here: https://codewithandrea.com/videos/flutter-state-management-riverpod/
But I got stuck :-/
We have Loading() Widget, that we test against to see if it disappears, but it doesn't..
That's the code of the test:
class ExerciseRepo {
// ignore: missing_return
Future<List<Exercise>> exerciseList() {
// should get data from database
}
}
final exerciseRepoProvider = Provider((ref) => ExerciseRepo());
final exerciseListProvider = FutureProvider<List<Exercise>>((ref) {
final repo = ref.watch(exerciseRepoProvider);
return repo.exerciseList();
});
class MockExercisesRepository extends Mock implements ExerciseRepo {
#override
Future<List<Exercise>> exerciseList() {
return Future.value([
Exercise(
title: 'Übung1',
repetitions: 10,
isCompleted: false,
isVideo: false,
unit: 'Sekunden',
description: 'Some description',
exerciseID: '42',
imageUrl: 'https://via.placeholder.com/150',
thumbUrl: 'https://via.placeholder.com/150'),
Exercise(
title: 'Übung2',
repetitions: 20,
isCompleted: false,
isVideo: false,
unit: 'Sekunden',
description: 'Some description2',
exerciseID: '43',
imageUrl: 'https://via.placeholder.com/150',
thumbUrl: 'https://via.placeholder.com/150'),
]);
}
}
void main() {
testWidgets('override repositoryProvider', (WidgetTester tester) async {
await mockNetworkImagesFor(() async {
await tester.pumpWidget(
ProviderScope(
overrides: [
exerciseListProvider.overrideWithProvider(
Provider((ref) => MockExercisesRepository))
],
child: MaterialApp(
home: Builder(builder: (context) {
return UserExerciseList();
}),
),
),
);
// The first frame is a loading state.
expect(find.byType(Loading), findsOneWidget);
await tester.pump();
await tester.pumpAndSettle();
// await Future.delayed(Duration(seconds: 3));
await tester.pumpAndSettle();
// No-longer loading
expect(find.byType(Loading), findsNothing);
});
});
}
The error message is:
The following TestFailure object was thrown running a test:
Expected: no matching nodes in the widget tree
Actual: _WidgetTypeFinder:<exactly one widget with type "Loading" (ignoring offstage widgets):
Loading>
Which: means one was found but none were expected
When the exception was thrown, this was the stack:
#4 main.<anonymous closure>.<anonymous closure> (file:///.../test/widget_exercise_list_test.dart:77:7)
<asynchronous suspension>
#5 main.<anonymous closure>.<anonymous closure> (file:///.../test/widget_exercise_list_test.dart)
#10 HttpOverrides.runZoned (dart:_http/overrides.dart:55:26)
#11 mockNetworkImagesFor (package:network_image_mock/src/network_image_mock.dart:9:24)
#12 main.<anonymous closure> (file:///.../test/widget_exercise_list_test.dart:54:11)
#13 testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:146:29)
<asynchronous suspension>
#14 testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart)
#15 TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:784:19)
<asynchronous suspension>
#18 TestWidgetsFlutterBinding._runTest (package:flutter_test/src/binding.dart:764:14)
#19 AutomatedTestWidgetsFlutterBinding.runTest.<anonymous closure> (package:flutter_test/src/binding.dart:1173:24)
#20 FakeAsync.run.<anonymous closure>.<anonymous closure> (package:fake_async/fake_async.dart:178:54)
#25 withClock (package:clock/src/default.dart:48:10)
#26 FakeAsync.run.<anonymous closure> (package:fake_async/fake_async.dart:178:22)
#31 FakeAsync.run (package:fake_async/fake_async.dart:178:7)
#32 AutomatedTestWidgetsFlutterBinding.runTest (package:flutter_test/src/binding.dart:1170:15)
#33 testWidgets.<anonymous closure> (package:flutter_test/src/widget_tester.dart:138:24)
#34 Declarer.test.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart:175:19)
<asynchronous suspension>
#35 Declarer.test.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart)
#40 Declarer.test.<anonymous closure> (package:test_api/src/backend/declarer.dart:173:13)
#41 Invoker.waitForOutstandingCallbacks.<anonymous closure> (package:test_api/src/backend/invoker.dart:231:15)
#46 Invoker.waitForOutstandingCallbacks (package:test_api/src/backend/invoker.dart:228:5)
#47 Invoker._onRun.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/invoker.dart:383:17)
<asynchronous suspension>
#48 Invoker._onRun.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/invoker.dart)
#53 Invoker._onRun.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/invoker.dart:370:9)
#54 Invoker._guardIfGuarded (package:test_api/src/backend/invoker.dart:415:15)
#55 Invoker._onRun.<anonymous closure> (package:test_api/src/backend/invoker.dart:369:7)
#62 Invoker._onRun (package:test_api/src/backend/invoker.dart:368:11)
#63 LiveTestController.run (package:test_api/src/backend/live_test_controller.dart:153:11)
#64 RemoteListener._runLiveTest.<anonymous closure> (package:test_api/src/remote_listener.dart:256:16)
#69 RemoteListener._runLiveTest (package:test_api/src/remote_listener.dart:255:5)
#70 RemoteListener._serializeTest.<anonymous closure> (package:test_api/src/remote_listener.dart:208:7)
#88 _GuaranteeSink.add (package:stream_channel/src/guarantee_channel.dart:125:12)
#89 new _MultiChannel.<anonymous closure> (package:stream_channel/src/multi_channel.dart:159:31)
#93 CastStreamSubscription._onData (dart:_internal/async_cast.dart:85:11)
#127 new _WebSocketImpl._fromSocket.<anonymous closure> (dart:_http/websocket_impl.dart:1145:21)
#135 _WebSocketProtocolTransformer._messageFrameEnd (dart:_http/websocket_impl.dart:338:23)
#136 _WebSocketProtocolTransformer.add (dart:_http/websocket_impl.dart:232:46)
#146 _Socket._onData (dart:io-patch/socket_patch.dart:2044:41)
#155 new _RawSocket.<anonymous closure> (dart:io-patch/socket_patch.dart:1580:33)
#156 _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:1076:14)
(elided 115 frames from dart:async and package:stack_trace)
This was caught by the test expectation on the following line:
file:///.../test/widget_exercise_list_test.dart line 77
The test description was:
override repositoryProvider
════════════════════════════════════════════════════════════════════════════════════════════════════
Test failed. See exception logs above.
The test description was: override repositoryProvider
That's the relevant part of the UserExerciseList()
#override
Widget build(BuildContext context, ScopedReader watch) {
AsyncValue<List<Exercise>> userExercisesList =
watch(exerciseCollectionStream);
return userExercisesList.when(
error: (error, stack) => ErrorInfo(error, stack),
loading: () => Loading(),
data: (List<Exercise> exercises) {
I also replaced Future with stream in my tests, didn't work either :-/ Any help is highly appreciated!
Many thanks!
I had to try out using several pumps to get a my mock data to return and change the state.
await tester.pumpWidget(ProviderScope(child: const MyApp()));
await tester.pump(Duration(seconds: 1));
await tester.pump(Duration(seconds: 1));
await tester.pump(Duration(seconds: 1));
expect(find.text("Sample Text"), findsOneWidget);
pumpAndSettle did not work.

Flutter tester..tap not working. How to solve "Bad state: No element" error?

I'm writing a widget test in my Flutter app. I'able to find the button using key or text or widget type but when I tap it, it gives Bad State No element error. Below is my test source code. I can also see the element in tester object while debugging under allWidgets item.
class MockSpeechRecognizer extends Mock implements SpeechRecognizer {}
void main() {
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() {
const MethodChannel('plugins.flutter.io/shared_preferences')
.setMockMethodCallHandler((MethodCall methodCall) async {
if (methodCall.method == 'getAll') {
return <String, dynamic>{}; // set initial values here if desired
}
return null;
});
setupLocator();
});
group('DashboardView Test | ', () {
testWidgets('Build Dashboard view and change keyword', (WidgetTester tester) async {
final Preferences preferences=Preferences();
preferences.keyword='hello';
final MockSpeechRecognizer speechService = MockSpeechRecognizer();
when(speechService.isServiceRunning).thenReturn(true);
locator.unregister<SpeechRecognizer>();
locator.registerLazySingleton<SpeechRecognizer>(() => speechService);
locator<LocalStorageService>().setUserPreferences(preferences);
// Build our app and trigger a frame.
binding.window.physicalSizeTestValue = Size(600, 300);
await tester.pumpWidget(MaterialApp(home:Dashboard()));
await tester.pumpAndSettle();
expect(find.byType(Dashboard),findsOneWidget);
await tester.tap(find.byKey(const Key('ChangeKeyword')));
});
});
}
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following StateError was thrown running a test:
Bad state: No element
When the exception was thrown, this was the stack:
#0 Iterable.single (dart:core/iterable.dart:554:25)
#1 WidgetController._getElementPoint (package:flutter_test/src/controller.dart:646:47)
#2 WidgetController.getCenter (package:flutter_test/src/controller.dart:618:12)
#3 WidgetController.tap (package:flutter_test/src/controller.dart:256:18)
#4 main.<anonymous closure>.<anonymous closure> (file:///E:/Siak/Meow/meow-phone-finder/test/Widgets/dashboardView_test.dart:52:20)
<asynchronous suspension>
#5 main.<anonymous closure>.<anonymous closure> (file:///E:/Siak/Meow/meow-phone-finder/test/Widgets/dashboardView_test.dart)
#6 testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:140:29)
<asynchronous suspension>
#7 testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart
Where do you define the Button, have you set the Key parameter?
await tester.pumpWidget(MaterialApp(home:
Container(child:
Button(
key: Key("ChangeKeyword"),
onTap: () => {},
child: Text("Press me"),
),
),
));

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.

Flutter - Map JSON

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?