【问题标题】:Flutter - Passing Function to StatelessWidget not workingFlutter - 将函数传递给 StatelessWidget 不起作用
【发布时间】:2020-01-09 16:35:25
【问题描述】:

我正在尝试制作一个通用的 ConfirmWidget,但它不起作用。这是我的代码: 我的想法是在调用我的自定义小部件时传递“任何功能”。

class ConfirmWidget extends StatelessWidget {
  final BuildContext context;
  final String mensaje;
  final Function btnSi;

  ConfirmWidget({this.context, this.mensaje, this.btnSi});

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new AlertDialog(
      title: new Text(mensaje),
      actions: <Widget>[
        new FlatButton(
          onPressed: () => Navigator.of(context).pop(false),
          child: new Text("No"),
        ),
        new FlatButton(
          onPressed: () {
            btnSi == null ? Navigator.of(context).pop(true):btnSi;
          },
          child: new Text("Si"),
        ),
      ],
    );
  }
}

正在使用我的小部件:

Future<bool> confirmCancelar(BuildContext context) {
    return showDialog(
      barrierDismissible: false,
      context: context,
      builder: (_) => new ConfirmWidget(
        mensaje: "¿Está seguro de cancelar la operación?",
        context: context,
        btnSi:()=>Navigator.pop(context),
      ),
    );
  }

有什么建议吗?提前致谢。

【问题讨论】:

  • 不传函数,不如传值,用它来判断动作。
  • 什么不起作用?对话框没有关闭?
  • 我正在传递我自己的函数,但是... > 问题是我没有正确调用该函数。这是正确的方法: >...现在可以使用了...谢谢大家

标签: flutter flutter-layout


【解决方案1】:

由于您没有将其直接绑定到 onPressed 事件,因此您需要调用该函数。 试试这个:

    new FlatButton(
      onPressed: () {
        btnSi == null ? Navigator.of(context).pop(true):btnSi();
      },
      child: new Text("Si"),
    )

【讨论】:

    【解决方案2】:

    尝试将Function 更改为VoidCallback。我有一个示例小部件。

    class CircleIconButton extends StatelessWidget {
      final double size;
      final VoidCallback onPressed;
      final IconData icon;
      final Color iconColor;
    
      CircleIconButton(
          {this.size = 32, @required this.icon, @required this.onPressed, this.iconColor = Colors.blue});
    
      @override
      Widget build(BuildContext context) {
        return ClipRRect(
          borderRadius: BorderRadius.circular(size * 2),
          child: Material(
            child: InkWell(
              onTap: this.onPressed,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Icon(
                  icon,
                  color: iconColor,
                  size: size * 0.66, // 66% width for icon
                ),
              ),
            ),
          ),
        );
      }
    }
    

    习惯了

    CircleIconButton(
                icon: Icons.search,
                onPressed: _searchProduct,
              )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 2021-02-10
      • 2019-08-25
      • 2017-02-11
      相关资源
      最近更新 更多