user54517
user54517

Reputation: 2420

Dart - how to pass a function as an argument

I want to pass a function as a parameter of a widget which contains a button (the function passed will be executed on the onPressed of the button)

myFunction1(){
   // do some things
}

myWidget(Function onPress){
    return FlatButton(
    onPressed : onPress,
    );
}

and then calling myWidget(myFunction1). But it doesn't work and I believe it's normal. The function is right executed and try to give a result. But I don't want the function to be executed now for it's result, I kind of want to pass the 'reference" of the function.

Upvotes: 0

Views: 307

Answers (2)

Parth Patel
Parth Patel

Reputation: 824

Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text('First Screen'),
  ),
  body: Center(
    child: myWidget(myFunction1),
  ),
 );
}

myFunction1() {
  print('called');
}

myWidget(Function onPressed) {
 return FlatButton(
   child: Text('FlatButton'),
   onPressed: onPressed,
 );
}

Upvotes: 1

Murat Aslan
Murat Aslan

Reputation: 1580

  Widget myWidget(Function onPress){
      return FlatButton(
          onPressed : onPress,
          child: Text('Button'),
      );
  }


 myWidget((){
//your code...
 });

Upvotes: 0

Related Questions