在MaterialStateProperty.resolveWith中使用状态<Color>

问题描述 投票:0回答:1

我想弄清楚是否有办法在其他地方使用下面的状态。

TextButton(
onPressed: () {},
style: ButtonStyle(
  backgroundColor: MaterialStateProperty.resolveWith<Color>(
    (states) { /*can we use this 'states' on other widget?*/
      if (states.contains(MaterialState.hovered)) {
        return Colors.red;
      }
      return Colors.white;
    },
  ),
),
child: Text(
  "change red color when hover",
    ),
);

有没有一种方法可以让我们在其他地方/小部件中使用状态?

flutter dart flutter-animation
1个回答
0
投票

如果您想监听属性当前的状态,那么您可以考虑使用 Stream

class HoverState {
  final _state = StreamController<MaterialState>.broadcast();
  Stream<MaterialState> get showState => _state.stream;

  setCondition(MaterialState state) {
    _state.sink.add(state);
  }

  disposeCondition() {
    _state.close();
  }
}

...在您的小部件上,您可以使用以下方式更新流:

// Initialize class containing Stream broadcast
HoverState hoverState = HoverState();

...

(states) { /*can we use this 'states' on other widget?*/
  if (states.contains(MaterialState.hovered)) {
    return Colors.red;
  }
  return Colors.white;

  // Update state in Stream
  hoverState.setCount(states);
},
© www.soinside.com 2019 - 2024. All rights reserved.