【问题标题】:How to show correct Icon in IconButton Flutter如何在 IconButton Flutter 中显示正确的图标
【发布时间】:2022-01-25 04:16:45
【问题描述】:

我在 AppBar 中有一个按钮,我想在点击时更改其图标,但没有任何效果。 如果你检查onPressed里面的图标类型,那么根据应该是哪个按钮触发条件,但它不显示。

bool toggle = true;
late Widget searchWidget = IconButton(
  onPressed: (){
    setState(() {
      toggle = !toggle;
    });
  },
  icon: toggle ? const Icon(Icons.search) : const Icon(Icons.cancel),
);    
@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      actions: [
        searchWidget,
        ],
      title: searchBar
    ),
    body: displayBody,
    bottomNavigationBar: _bottomMenu,
  );
}

【问题讨论】:

    标签: flutter flutter-layout


    【解决方案1】:

    searchWidget 更改为获取更新 UI 的方法,

     Widget searchWidget() => IconButton(
            onPressed: () {
              setState(() {
                toggle = !toggle;
              });
            },
            icon: toggle ? const Icon(Icons.search) : const Icon(Icons.cancel),
          );
    

    并使用喜欢

      actions: [
              searchWidget(),
            ],
    

    【讨论】:

    • 哇!谢谢你。不确定为什么它不适用于该字段?
    • 我的假设是 searchWidget 首先被初始化为 IconButton,改变内部元素不是改变没有影响,因为它不是一个方法,late keyword with declaration 也被称为Lazy initialization
    猜你喜欢
    • 2021-08-31
    • 2019-05-24
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    相关资源
    最近更新 更多