Flutter通过回调传递字符串

时间:2019-07-10 11:20:01

标签: flutter dart

这是简单的代码,用于显示具有重叠支持的小部件,在其中的onReplay中,我想获取字符串作为消息来显示,例如使用toast

showOverlayNotification((context) {
  return MessageNotification(
    message: messages[3],
    onReplay: (message) {
      OverlaySupportEntry.of(context).dismiss();
      toast(message);
    },
  );
}, duration: Duration(milliseconds: 4000));

我实现的将消息作为字符串传递的代码不正确,我得到了

  

错误:最终变量'onReply'必须初始化。

我该如何解决这个问题?

typedef StringToVoidFunc = void Function(String);
const messages = [
  ...
];

class MessageNotification extends StatelessWidget {
  //final VoidCallback onReplay;
  final StringToVoidFunc onReply;
  final String message;

  const MessageNotification({
    Key key,
    this.onReplay,
    @required this.message,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: InkWell(
        onTap: (){
          if (onReplay != null) onReplay("sample pass message");
        },
        child: Center(
          child: Text(
            'ssss',
            style: TextStyle(
              fontSize: 26.0,
            ),
          ),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您在类型错误中输入了错误

更改此

final StringToVoidFunc onReply;

final StringToVoidFunc onReplay;

错误已解决。