按下按钮时如何显示警报对话框?

How to show alertdialog when button is pressed?

以下是我的 homepage.dart 的一部分,运行 没问题,但是点击 IconButton 没有任何反应。

 ...
 return Scaffold(
  appBar: AppBar(
    title: Text('Lorem Ipsum'),
    leading: IconButton(      
      icon: Icon(Icons.info),
      onPressed: () => AboutWidget(),
    ),
  ),
  body: ...

这是我的 about_widget.dart 文件,其中定义了我的 AboutWidget。 我做错了什么?

 import 'package:flutter/material.dart';
class AboutWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text('data'),
    );
  }
}

你必须调用showDialog函数

AppBar(
  title: Text('Lorem Ipsum'),
  leading: IconButton(
    icon: Icon(Icons.info),
    onPressed: () => showDialog(
      context: context,
      builder: (context) => AboutWidget(),
    ),
  ),
)

按下您要呼叫的按钮 AboutWidget()。它是一个无状态的小部件。所以它需要在你的应用程序的构建方法中构建。 在按钮上单击这不会显示对话框。而是使用 showDialog 方法,并在其中使用警报对话框在屏幕上显示对话框。

使用 Flutter 原生 showDialog 函数显示对话框。

对于你的代码,你可以试试这个:

return Scaffold(
  appBar: AppBar(
    title: Text('Lorem Ipsum'),
    leading: IconButton(      
      icon: Icon(Icons.info),
      onPressed: () => showDialog(
        context: context,
        builder: (context){
          return AboutWidget();
        }
      ),
    ),
  ),
);

所以当按钮被按下时,你应该调用showDialog方法。