Emranul_Rakib
Emranul_Rakib

Reputation: 81

Flutter: How to Read Text Files from asset and show it to container

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?

Upvotes: 4

Views: 3794

Answers (1)

Will Hlas
Will Hlas

Reputation: 1341

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'),
    );
  }
}

Upvotes: 5

Related Questions