Flutter 错误 - 找不到 Material 祖先的特定小部件是:

Flutter error - The specific widget that could not find a Material ancestor was:

我正在使用 Align 小部件在屏幕底部中央放置一个图标按钮。

但是,我收到以下错误并且我无法解决它:

The specific widget that could not find a Material ancestor was: IconButton

我的代码:

return Stack(
  children: <Widget>[
    Container(
      child: GoogleMap(
        initialCameraPosition:
        CameraPosition(target: LatLng(1,1), zoom: 15),
        onMapCreated: (map) {
          mapReady;
        },),
    ),
    Align(
      alignment:Alignment.bottomCenter,
      child: IconButton(
          icon: Icon(Icons.next_week), onPressed: (){}),
    )
  ],

如果我将 IconButton 小部件替换为例如文本小部件,则效果很好。

能否解释一下为什么它不起作用,为什么 IconButton 需要 Material 祖先?

因为根据 IconButton 的文档 (https://api.flutter.dev/flutter/material/IconButton-class.html)

An icon button is a picture printed on a Material widget that reacts to touches by filling with color (ink).

[..]

Requires one of its ancestors to be a Material widget.

IconButton 最有可能使用 ThemeData 以及 MaterialApp 通常提供的其他内容。

你有没有使用 MaterialApp 作为祖先的原因?

如果你用脚手架包裹你的堆栈(或一般的父级),你将不会得到这个错误。

在这种情况下,如果您用 Material 小部件包装 IconButton,我相信它会解决问题:

  Align(
    alignment: Alignment.bottomCenter,
    child: Material(
        child: IconButton(icon: Icon(Icons.next_week), onPressed: () {})),
  )