Flutter 错误The argument type 'Color' can't be assigned to the parameter type 'MaterialStateProperty?'.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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM