Flutter 错误The argument type 'Color' can't be assigned to the parameter type 'MaterialStateProperty<Color?>?'.dart(argument_type_not_assignable)

MaterialStateProperty<Color?>?和Color

  • 当为TextButton等button添加颜色时,使用ButtonStyle为其添加颜色
TextButton(
      onPressed: () {},
      child: Text('text'),
      style:
          ButtonStyle(backgroundColor:Colors.white),
    );
  • 这样设置会报错,如题

MaterialStateProperty.all() 方法是设置点击事件所有状态下的样式。
MaterialStateProperty.resolveWith() 可拦截分别设置不同状态下的样式。

  • 如果所有的状态时的颜色都相同,使用MaterialStateProperty.all(),如果不同状态要使用不同的颜色时,用MaterialStateProperty.resolveWith(),例如:
TextButton(
      onPressed: () {},
      child: Text('text'),
      style: ButtonStyle(
        //backgroundColor:MaterialStateProperty.all(Colors.white)
        backgroundColor: MaterialStateProperty.resolveWith(
          (states) {
            if (states.contains(MaterialState.focused) &&
                !states.contains(MaterialState.pressed)) {
              //获取焦点时的颜色
              return Colors.blue;
            } else if (states.contains(MaterialState.pressed)) {
              //按下时的颜色
              return Colors.deepPurple;
            }
            //默认状态使用灰色
            return Colors.grey;
          },
        ),
      ),
    );

参考:https://zhuanlan.zhihu.com/p/278330232

posted @ 2021-11-24 10:32  R1cardo  阅读(2981)  评论(0编辑  收藏  举报