Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous function implementation in flutter

So, I am learning about anonymous functions in dart which I know helps to reduce and simplify the code when passing a function as an argument to another function. Now, what I want to know is how exactly is this used in building an application using flutter. I am here seeking some practical implementation in actual flutter applications.

like image 483
Kalash Babu Acharya Avatar asked Jun 22 '26 05:06

Kalash Babu Acharya


1 Answers

Imagine you wanted to implement a CustomButton to reuse it across your entire app. In that case, it typically makes sense for it to return a callback function and handle the event where the button is being used. To do so, you pass an onPressed function to the button, which will be invoked by the button's internal onPressed function.

class CustomButton extends StatelessWidget {
  const CustomButton({
    required this.onPressed,
    required this.title,
  });

  final void Function() onPressed;
  final String title;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(title),
    );
  }
}

Using it:

CustomButton(
  onPressed: () => Navigator.pushNamed(context, '/pageTwo'),
  title: 'Navigate',
)

The CustomButton can now push, pop, or do all kinds of things. It is way more flexible than if you implemented a button without a callback function:

class ForwardButton extends StatelessWidget {
  const ForwardButton({
    required this.destination,
    required this.title,
  });

  final String destination;
  final String title;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () => Navigator.pushNamed(context, destination),
      child: Text(title),
    );
  }
}
ForwardButton(
  destination: '/pageTwo',
  title: 'Navigate',
)

If you wanted the ForwardButton to do things other than Navigator.pushNamed, you'd need to add more logic or arguments to the constructor, and it'll quickly become messy.

like image 196
minhqdao Avatar answered Jun 23 '26 20:06

minhqdao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!