The following code does not display special characters and instead just returning the Unicode of the characters. For example instead of showing æ
the code is returning just u00e6
.
After some googling, I have tried adding 'Content-Type': 'multipart/form-data; charset=utf-8',
in the headers and even tried using utf8.decode()
inside the json.decode
and outside. The difference it made was when I used utf8.decode()
on dnContent
the dialog did not show.
My code:
Future<void> fetchDialogData() async {
var headers = AppConstants.apiHeaders;
var request = http.MultipartRequest(
'POST',
Uri.parse(
'${AppConstants.baseUrl}${AppConstants.homeSpecialMsgEndpoint}'));
request.fields.addAll(AppConstants.apiBody);
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
var responseBody = await response.stream.bytesToString();
final data = json.decode(responseBody);
final nestedDescriptionData =
data['response']['RESULT'][0]['description'];
print('MY DATA: $nestedDescriptionData');
final dnRegex = RegExp(r'"dn":"(.*?)"');
final match = dnRegex.firstMatch(nestedDescriptionData);
if (match != null) {
final dnContent = (match.group(1) ?? '').replaceAll(r'rn', 'n');
setState(() {
_dnContent = dnContent;
});
_showWelcomeDialog(_dnContent);
} else {}
} else {}
}
void _showWelcomeDialog(String dnContent) {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Welcome'),
content: Text(
dnContent,
style: const TextStyle(fontSize: 12),
),
actions: [
Align(
alignment: Alignment.bottomRight,
child: TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('close'),
),
),
],
);
},
);
}
2
Answers
Here are a few approaches for resolving the Unicode display problem:
json.decode()
with UTF-8 decoding:dart:convert
‘sjsonDecode
with explicit UTF-8 decoding:Additional Debugging Tips:
responseBody
before decoding to see its exact contentI think you should decode the data with
utf8.decode
before decoding into json.