Home > other >  Event Listeners in flutter
Event Listeners in flutter

Time:11-20

Is there a way I can listen to a button click in flutter? I want to know if the button is clicked in another class that creates a object of that button.

What i want to do is let MyButtonRow know when MyButton is clicked, since it involves changing variables in MyButtonRow.

The functionality i am looking for is similar to .setEventListener in JavaScript

So here's the code

class MyButtonRow extends StatefulWidget {
  const MyButtonRow({Key? key}) : super(key: key);

  @override
  _MyButtonRowState createState() => _MyButtonRowState();
}

class _MyButtonRowState extends State<MyButtonRow> {
  @override
  Widget build(BuildContext context) {
    return Container(width: MediaQuery.of(context).size.width,
        child: Row(children: <Widget>[MyButtonTile()],));
  }
}



class MyButtonTile extends StatefulWidget {
  const MyButtonTile({Key? key}) : super(key: key);

  @override
  _MyButtonTileState createState() => _MyButtonTileState();
}

class _MyButtonTileState extends State<MyButtonTile> {
  @override
  Widget build(BuildContext context) {
    return TextButton(onPressed: (){
      //notify MyButtonRow about the click
    }, child: Text("hello"));
  }
}

CodePudding user response:

Firstly you declare onTap function on your child widget and then just pass the onTap function from where you define the MyButtonTile

class MyButtonRow extends StatefulWidget {
  const MyButtonRow({Key? key}) : super(key: key);

  @override
  _MyButtonRowState createState() => _MyButtonRowState();
}

class _MyButtonRowState extends State<MyButtonRow> {
  @override
  Widget build(BuildContext context) {
    return Container(width: MediaQuery.of(context).size.width,
        child: Row(children: <Widget>[MyButtonTile(onTap: (){
                   print("Notify me");
    })],));
  }
}

class MyButtonTile extends StatelessWidget {
  final Function onTap;
   MyButtonTile({this.onTap});
  
  @override
  Widget build(BuildContext context) {
    return TextButton(onPressed:onTap,//notify MyButtonRow about the click
        child: Text("hello"));
  }
}
  • Related