loadString and Invalid UTF-8 byte

2,691 views
Skip to first unread message

Steepe Hare

unread,
Apr 24, 2021, 1:55:58 PM4/24/21
to Flutter Development (flutter-dev)
I have an absolutely correct text file (it can be viewed in any text editor).
Why when I use this code:

class _RulesPageState extends State<RulesPage> {
String filePath = "assets/eng_rules.txt";
String fileText = "";

readFile() async {
String text = await rootBundle.loadString(filePath);
setState(() {
fileText = text;
});
}

@override

I receive the error:
E/flutter (28342): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: FormatException: Invalid UTF-8 byte (at offset 0)

Suzuki Tomohiro

unread,
Apr 24, 2021, 4:07:12 PM4/24/21
to Steepe Hare, Flutter Development (flutter-dev)
Q1 What happens if the content of the file is empty (file exists but is empty)?

Q2 What happens if you specify nonexistent file such as “assets/foobar.txt”?

--
You received this message because you are subscribed to the Google Groups "Flutter Development (flutter-dev)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/flutter-dev/e84432b7-9ec2-4459-a3cd-6fcf5a9aef50n%40googlegroups.com.

Steepe Hare

unread,
Apr 25, 2021, 12:48:30 PM4/25/21
to Flutter Development (flutter-dev)
> What happens if the content of the file is empty (file exists but is empty)?

No errors


> What happens if you specify nonexistent file such as “assets/foobar.txt”?

E/flutter ( 9229): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Unable to load asset: assets/foobar.txt

Suzuki Tomohiro

unread,
Apr 25, 2021, 12:58:56 PM4/25/21
to Steepe Hare, Flutter Development (flutter-dev)
Good. Now I think the problem is the content of the file. Can you share the file as an attachment? (You can truncate it as long as the same error occurs)

Steepe Hare

unread,
Apr 27, 2021, 8:18:27 AM4/27/21
to Flutter Development (flutter-dev)
I don't know why, but the file was saved as UTF-16LE.
When I saved it as UTF-8, Flutter could read it without errors.

Thank you.

Suzuki Tomohiro

unread,
Apr 27, 2021, 8:31:17 AM4/27/21
to Steepe Hare, Flutter Development (flutter-dev)
Nice. Glad to hear you figured it out. You’re welcome.

Reply all
Reply to author
Forward
0 new messages