dart 如何在Flutter中访问MaterialState集合?

dgsult0t  于 5个月前  发布在  Flutter
关注(0)|答案(2)|浏览(66)

我需要创建ElevatedButton,它使用SvgPicture来显示它里面的图标。我已经在ButtonStyle里面定义了foregroundColor来根据当前的MaterialState来解析颜色。然而,这个foregroundColor只应用于文本和图标部件。我如何才能以同样的方式为我的SvgPicture部件解析这个颜色?或者至少可以访问我的ElevatedButton的MaterialState集?
我试图研究Flutter如何为ElevatedButton存储一组MaterialState,但还没有找到它。此外,我遇到了MaterialStateMixin,据我所知,它的目的只是在GestureDetector,InkWell等的帮助下在Flutter中创建自定义按钮。

hc2pp10m

hc2pp10m1#

我相信你正在寻找的是MaterialStatesController,它暴露了小部件的材料状态Set<MaterialState>
https://api.flutter.dev/flutter/material/MaterialStatesController-class.html

class _SvgButtonState extends State<SvgButton> {
  late final _statesController = MaterialStatesController();

  @override
  void dispose() {
    _statesController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton.icon(
      label: const Text('Button'),
      statesController: _statesController,
      style: ...,
      icon: ValueListenableBuilder(
        valueListenable: _statesController,
        builder: (context, value, child) { // value is Set<MaterialState>
          return SvgPicture.asset(
            'assets/...',
            colorFilter: value.contains(...) ? ... : ...,
          );
        },
      ),
      onPressed: () {},
    );
  }
}

字符串

t1rydlwq

t1rydlwq2#

要访问Flutter中的MaterialState集合,您可以使用MaterialStateColor类。但是,需要注意的是,SvgPicture可能不会像Icon那样自动响应MaterialState的更改。在这种情况下,您可能需要手动管理SvgPicture的颜色更改。
这里有一个例子,你可以如何实现这一点:

ElevatedButton(
  onPressed: () {
    // Your button's onPressed logic
  },
  style: ButtonStyle(
    foregroundColor: MaterialStateColor.resolveWith((Set<MaterialState> states) {
      // Resolve color based on MaterialState
      if (states.contains(MaterialState.pressed)) {
        return Colors.red; // Change to the desired color
      }
      return Colors.blue; // Default color
    }),
  ),
  child: Row(
    mainAxisSize: MainAxisSize.min,
    children: [
      SvgPicture.asset(
        'assets/your_icon.svg',
        // Set the color manually based on MaterialState
        color: MaterialStateColor.resolveWith((Set<MaterialState> states) {
          if (states.contains(MaterialState.pressed)) {
            return Colors.red; // Change to the desired color
          }
          return Colors.blue; // Default color
        }),
      ),
      SizedBox(width: 8), // Adjust as needed
      Text('Button Text'),
    ],
  ),
)

字符串
在本例中,ElevatedButton的foregroundColor和SvgPicture的颜色都是基于MaterialState手动管理的。根据您的特定用例需要调整颜色和条件。请记住,SVG渲染可能不完全支持基于MaterialState的动态颜色更改,对于更复杂的场景,您可能需要使用替代方法或包。

相关问题