简体   繁体   中英

How do I create a custom widget that takes a function as parameter and uses it?(flutter)

ElevatedButton customBTN(String test, Icon icon, Colors color, double height, double width, passedfunc ,)

  return ElevatedButton(
    style: ElevatedButton.styleFrom(),
    child: Text('a'),
    onPressed: **passedfunc**,
  );

You can use VoidCallback or Function as widget variable,

class MyW extends StatelessWidget {
  final VoidCallback? callback;
  const MyW({Key? key, this.callback}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(),
      child: Text('a'),
      onPressed: callback,
    );
  }
}

And whenever you use this widget you will get a callback function

MyW(
  callback: () {},
),

You can choose function or typedef for passing data.

class MyW extends StatelessWidget {
  final Function(int data) myFunc;
  final VoidCallback? callback;
  const MyW({
    Key? key,
    required this.myFunc,
    this.callback,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(),
      child: Text('a'),
      onPressed: () {
        myFunc(1);
        if (callback != null) callback!();
      },
    );
  }
}

And use case

MyW(
  callback: () {},
  myFunc: (data) {},
),

If you are using StatefulWidget call method using widget.YourFunction

Possible duplicate and more about passing function

class MyCustomWidget extends StatelessWidget {
  final Function onPress;
  const MyCustomWidget({Key? key, this.onPress}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(),
      child: Text('a'),
      onPressed: onPress.call, // or onPressed: () => onPress.call(),
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM