Flutter 子组件回调父组件传递的方法

10 min read
class ButtonWidget extends StatefulWidget {
  // callback for the button
  final VoidCallback onPressed;
  final String label;
  final Color bgColor;

  const ButtonWidget({
    Key? key,
    required this.onPressed,
    required this.label,
    this.bgColor = Colors.grey,
  }) : super(key: key);

  @override
  State<ButtonWidget> createState() => _ButtonWidgetState();
}

class _ButtonWidgetState extends State<ButtonWidget> {
  @override
  Widget build(BuildContext context) {
    return OutlinedButton(
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.all(
          widget.bgColor,
        ),
      ),
      child: Text(
        widget.label,
        style: const TextStyle(color: Colors.white),
      ),
      onPressed: () {
        widget.onPressed();
      },
    );
  }
}
  • VoidCallback 回调方法类型