【问题标题】:Flutter error - The specific widget that could not find a Material ancestor was:Flutter 错误 - 找不到 Material 祖先的特定小部件是:
【发布时间】:2020-02-28 14:24:50
【问题描述】:

我正在使用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 小部件替换为 Text 小部件,则效果很好。

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

【问题讨论】:

    标签: flutter dart flutter-layout iconbutton


    【解决方案1】:

    如果你用 Scaffold 包装你的堆栈(或一般的父级),你会得到这个错误。

    在这种情况下,如果你用 Material Widget 包裹你的 IconButton,我相信它会解决这个问题:

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

    【讨论】:

      【解决方案2】:

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

      图标按钮是打印在 Material 小部件上的图片,它会做出反应 通过填充颜色(墨水)来触摸。

      [..]

      要求其祖先之一是 Material 小部件。

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

      你不使用 MaterialApp 作为祖先有什么原因吗?

      【讨论】:

        猜你喜欢
        • 2021-02-24
        • 2019-03-26
        • 2021-03-31
        • 2021-04-29
        • 1970-01-01
        • 2020-08-08
        • 2020-11-23
        • 2021-10-08
        • 2021-12-22
        相关资源
        最近更新 更多