How to run function in child widget FLUTTER

Issue

In my main.dart I have StatefulWidget and class extends State and functions to write and read string to local file:

  Future<void> _writeDataToFile(favs) async {
    final _dirPath = await _getDirPath();
    final _myFile = File('$_dirPath/fav.txt');
    await _myFile.writeAsString("||${_myVariable}||");
  }

  Future<void> _readData() async {
    final dirPath = await _getDirPath();
    final myFile = File('$dirPath/fav.txt');
    final data = await myFile.readAsString(encoding: utf8);

    setState(() {
      _content = data;
    });
  }

I run widget from separated file with:

itemBuilder: (context, index) => allRadioList(articles[index], context, _content),

How Can i run _readData() with state change from allRadioList widget.

Here’s my allRadioList(articles[index], context, _content) code:

Widget allRadioList(Article article, BuildContext context, String contentt) {
  return Card(
      child: ListTile(
    title: Text(article.title),
    subtitle: Text(contentt),
    leading: CircleAvatar(backgroundImage: NetworkImage("https://image.tmdb.org/t/p/w300/${article.urlToImage}")),
    trailing: IconButton(
      icon: contentt.contains(article.id.toString()) ? Icon(Icons.star_border_outlined, color: Colors.yellow) : Icon(Icons.star_border_outlined, color: Colors.white),
      tooltip: 'My Tootltip',
      onPressed: () {
        _writeDataToFile(article.id.toString());
        _readData();
      },
    ),
  ));
}

Solution

Functions are objects, so you can pass them as function parameter and call it in your function

// (){} is a anonymous function (with no name)
itemBuilder: (context, index) => allRadioList(articles[index], context, _content,onPressed: (){
        _writeDataToFile(articles[index].id.toString());
        _readData();
}),

and

Widget allRadioList(Article article, BuildContext context, String contentt,{Funtion onPressed}) {
  return Card(
      child: ListTile(
    title: Text(article.title),
    subtitle: Text(contentt),
    leading: CircleAvatar(backgroundImage: NetworkImage("https://image.tmdb.org/t/p/w300/${article.urlToImage}")),
    trailing: IconButton(
      icon: contentt.contains(article.id.toString()) ? Icon(Icons.star_border_outlined, color: Colors.yellow) : Icon(Icons.star_border_outlined, color: Colors.white),
      tooltip: 'My Tootltip',
      onPressed: onPressed,
    ),
  ));
}

Answered By – Sahil Hariyani

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *