如何在Flutter中向子小部件传递上下文。

5

我有一个有状态的小部件W1,它调用了一个无状态的小部件W2

W2具有onTap功能。我想在W2的onTap()中显示提示对话框。

onTap:() {Alert(context: context, title:'Hi');},

我没有收到任何错误提示,但是在点击时没有看到任何警报。我尝试将上下文作为参数传递给W2,但我仍然没有看到任何对话框。 从W2显示对话框的正确方法是什么? 我正在使用rflutter_alert包Link 谢谢

“Alert”只是一个“Widget”(一个类)。您刚刚调用了构造函数来创建“Alert”的实例。因此,您必须将此实例传递给名为“showDialog”的函数,以实际呈现小部件。 - Crazy Lazy Cat
3个回答

2
在结尾添加.show()解决了它。
onTap:() {Alert(context: context, title:'Hi').show();}

这在rflutter_alert包中有清晰的文档记录,但我不知何故错过了它。


1

您需要使用showDialog(context: context, builder: (BuildContext context) => Alert(context: context, title:'Hi'));来包装您的Alert(context: context, title:'Hi');

以下是示例:

Future<void> _neverSatisfied() async {
  return showDialog<void>(
    context: context,
    barrierDismissible: false, // user must tap button!
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text('Rewind and remember'),
        content: SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              Text('You will never be satisfied.'),
              Text('You\’re like me. I’m never satisfied.'),
            ],
          ),
        ),
        actions: <Widget>[
          FlatButton(
            child: Text('Regret'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}

无论如何,关于如何传递context的问题,如果您正在创建一个StatelessStateful小部件,则不需要传递context,您可以从build(BuildContext context){}中获取它。

0

在 onTap 函数的调用中传递上下文:

onTap:(context) {Alert(context: context, title:'Hi');},

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接