如何在Flutter中访问/更改窗口小部件的属性

时间:2020-04-21 05:27:17

标签: flutter dart

我有一个包含3个图标的菜单按钮,我想将鼠标悬停在当前页面的图标上。

小部件的代码为:

class MenuButton extends StatelessWidget {
  int current;

  MenuButton({@required this.current}) {}

  @override
  Widget build(BuildContext context) {
    Widget cirMenu = FabCircularMenu(
      children: <Widget>[
        IconButton(
            icon: Image.asset('img/performance.png'),
            onPressed: () {
              print('Favorite');
            }),
        IconButton(
            icon: Image.asset('img/shop.png'),
            onPressed: () {
              print('Home');
            }),
        IconButton(
            icon: Image.asset('img/category.png'),
            onPressed: () {
              print('Favorite');
            })
      ],
      ringDiameter: 230,
      ringWidth: 90,
      animationCurve: Cubic(1, 1.65, .62, .83),
    );
 return cirMenu;
}

我想将鼠标悬停在当前页面的图像上,但是我不知道如何访问Widget属性。最终的功能应该是这样的(尽管它没有编译),只是添加了一个条件来更改图像:

 if (current == 0) {
  cirMenu.children[0].Icon = Image.asset('img/performance-hover.png');
}

if (current == 1) {
  cirMenu.children[1].Icon = Image.asset('img/shop-hover.png');
}

if (current == 2) {
  cirMenu.children[2].Icon = Image.asset('img/category-hover.png');
}
return cirMenu;

我该怎么做?

2 个答案:

答案 0 :(得分:1)

如果您只想发送消息,则可以使用tooltip中已经存在的IconButton()属性 像这样

IconButton(
      icon: Image.asset('img/performance.png'),
      onPressed: () {
        print('Favorite');
      }, tooltip: 'Favorite')

如果您希望在悬停时更改颜色,可以更改hoverColor属性

IconButton(
      icon: Image.asset('img/performance.png'),
      onPressed: () {
        print('Favorite');
      }, hoverColor: Colors.red)

答案 1 :(得分:1)

构建后,您将无法修改其属性。这是一成不变的。换句话说,每次要更改它时,都需要重新构建它。

一种可能的解决方案是修改您的代码以在每次重建时使用适当的背景。

  Image getBackground(int current) {
    if (current == 0) {
      return Image.asset('img/performance-hover.png');
    }

    if (current == 1) {
      return Image.asset('img/shop-hover.png');
    }

    if (current == 2) {
      return Image.asset('img/category-hover.png');
    }
    //handle other indices
  }

然后,根据您期望的结果,可以在构造MenuButton时使用此方法。

记住-您无需(甚至不能)在构建小部件时对其进行修改。数据(即索引或图像)必须从窗口小部件树的顶部流到底部。