[Flutter] Fix broken Korean or Japanese in server data

2023-03-10 hit count image

Let's see how to fix the broken Korean or Japanese when getting the JSON data from the server via the http package in Flutter.

Outline

In Flutter, when sending or getting between the server and the app, the http package is normally used.

At this time, when the Korean or Japanese in the JSON data from the server is displayed on the app, the characters are broken sometimes. In this blog post, I will introduce how to fix the broken Korean or Japanese characters in the JSON data from the server via the http package.

Get data by http package

In Flutter, normally we get the data from the server by using the http package like the following.

import 'package:http/http.dart' as http;
...
final httpClient = http.Client();
...
final url = Uri.parse('${ENV.apiServer}/data');
final response = await httpClient.post(
  url,
  headers: {
    'Authorization': 'Bearer $token',
    'Content-Type': 'application/json; charset=UTF-8',
  },
  body: jsonEncode(
    {
      ...
    },
  ),
);

final data = jsonDecode(response.body);
print(data['error_message']);

At this time, if the data is English, the characters are shown well like the following.

flutter: server error

Data includes Korean or Japanese

However, if the server data has Korean or Japanese, the characters are broken like the following. In this blog post, let’s take a look at the case that the characters are the server error(サーバーエラー) is received in Japanse.

# flutter: サーバーエラー
flutter: サーバーエラー

utf8.decode

If you see the characters on the data received from the server are broken, you can fix it by using utf8.decode like the following.

import 'dart:convert';
...
final response = await httpClient.post(
  ...
);

final data = jsonDecode(utf8.decode(response.bodyBytes));
print(data['error_message']);

After modifying the code like this, you can see the data is shown well like the following.

flutter: サーバーエラー

Completed

Done! we’ve seen how to fix the broken Korean or Japanese in the data, which is from the server via the http package, by using utf8.decode. If you see the characters are broken that is the server data, try to use utf8.decode to fix it.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts