Outline
When you call an API
in Flutter
, you use the http
package normally. For how to call API
using the http
package in Flutter
, please refer to the link below.
When you test the code implemented with the http
package, the Contains invalid characters
error often occurs. In this blog post, I will introduce how to fix the Contains invalid characters
error that occurs when you test the code implemented with the http
package.
Contains invalid characters error
When you write the test code, if the Response
contains a language other than English, the Contains invalid characters
error occurs as follows.
when(mockHttpClient.post(
Uri.parse('${ENV.apiServer}/api/logout'),
headers: anyNamed('headers'),
)).thenAnswer((_) async => http.Response('''{
"success": true,
"data": {
"message": "ログアウトしました。"
},
"errors": null
}''', 200));
In this blog post, I returned a Response
that contains Japanese. When you run this test code, you can see that the Contains invalid characters
error occurs as follows.
Invalid argument (string): Contains invalid characters.: "{\n \"success\": true,\n \"data\": {\n \"message\": \"ログアウトしました。\"\n },\n \"errors\": null\n }"
dart:convert Latin1Codec.encode
package:http/src/response.dart 37:49 new Response
How to fix
To fix this problem, you need to encode
the Response
using http.Response.bytes
and utf8.encode
as follows.
when(mockHttpClient.post(
Uri.parse('${ENV.apiServer}/api/logout'),
headers: anyNamed('headers'),
)).thenAnswer((_) async => http.Response.bytes(utf8.encode('''{
"success": true,
"data": {
"message": "ログアウトしました。"
},
"errors": null
}'''), 200));
When you modify the test code like this and run it, you can see that the test code is passed without any problems.
Completed
Done! We’ve seen how to fix the Contains invalid characters
error that occurs when you test the feature implemented by the http
package in Flutter
. If you have a Contains invalid characters
error, please refer to this blog post to fix it.
Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!
App promotion
Deku
.Deku
created the applications with Flutter.If you have interested, please try to download them for free.