flutter : Passing assetpath as a string and load asset value

152

The Problem is solved. I solved it this way:

class cs_one extends StatefulWidget {
final String assetPath;
const cs_one({Key? key, required this.assetPath}) : super(key: key);

@override
_cs_oneState createState() => _cs_oneState(assetPath );
}

class _cs_oneState extends State<cs_one> {

String? data;
String path='';
_cs_oneState(String assetPath){
 this.path=assetPath;
}

void _loadData() async {
final _loadedData =
await rootBundle.loadString(path);
setState(() {
  data = _loadedData;
 });
}
Share:
152
Emranul_Rakib
Author by

Emranul_Rakib

Updated on January 01, 2023

Comments

  • Emranul_Rakib
    Emranul_Rakib over 1 year

    I want to show text in a container by loading assets( textfile) from the asset path which I have received from another class as a string. But after running the container shows empty. I have tried this way.

    assetpath String:

      final String assetPath = 'lib/asset/textfile/cs_one.txt';
    

    class one( sending assetpath as a string ):

    Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => cs_one( assetPath : assetPath) ),
              );
    

    class two ( receiving assetpath from class one and loading data ) :

     class cs_one extends StatefulWidget {
     final String assetPath;
     const cs_one({Key? key, required this.assetPath}) : super(key: key);
    
     @override
     _cs_oneState createState() => _cs_oneState( );
     }
    
     class _cs_oneState extends State<cs_one> {
    
     String? data;
      static String? get assetPath => assetPath;
    
    void _loadData() async {
    final _loadedData =
    await rootBundle.loadString(assetPath!);
    setState(() {
      data = _loadedData;
    });
    }
    
    @override
    void initState() {
    super.initState();
    _loadData();
    }
    

    Showing text in widget:

    body:  SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Container(
            margin: EdgeInsets.all(15),
            width: 360,
            child: Text(data ?? 'empty'),
          ))),