Flutter: How to Read Text Files from asset and show it to container
1,022
You need to load the data before displaying it by either using a StatefulWidget or FutureBuilder.
Here's an example using a StatefulWidget:
class MyWidget extends StatefulWidget {
const MyWidget({Key? key}): super(key: key);
@override
State<StatefulWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
String? data;
void _loadData() async {
final _loadedData = await rootBundle.loadString('lib/asset/textfile/cs_one.txt');
setState(() {
data = _loadedData;
});
}
@override
void initState() {
super.initState();
_loadData();
}
@override
Widget build(BuildContext context) {
return Center(
child: Text(data ?? 'empty'),
);
}
}
Author by
Emranul_Rakib
Updated on January 01, 2023Comments
-
Emranul_Rakib over 1 year
I want to Read Text Files from asset and show it to my container widget in my flutter app. When I run the app the container shows no text, just a blank white page. I have tried this way:
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class cs_one extends StatelessWidget { @override Widget build(BuildContext context) { final appTitle = 'Read Text File'; return MaterialApp( title: appTitle, home: Scaffold( appBar: AppBar( title: Text(appTitle), ), body: a() ), ); } } class a extends StatelessWidget { String _data; Future<void> _loadData() async { final _loadedData = await rootBundle.loadString('lib/asset/textfile/cs_one.txt'); _data = _loadedData; } @override Widget build(BuildContext context) { return Container( child: Text(_data), ); } }
pubsepec.YAML file:
# To add assets to your application, add an assets section, like this: assets: - image/background.jpg - image/icon.png - lib/asset/textfile/cs_one.txt
What do I solve this?
-
Emranul_Rakib over 2 yearsThanks a lot! It works.
-
tazboy about 2 yearsDoes it need to be async when loading a local file?