Flutter ElevatedButton自定义边框圆角报类型不匹配错误
报错原因
类型不匹配错误,核心是API用法混淆:ElevatedButton.styleFrom是Flutter提供的按钮样式快捷构造方法,其shape参数的类型为OutlinedBorder,直接接收边框形状实例即可。MaterialStateProperty是直接通过ButtonStyle()原生构造函数自定义样式时才需要的包装类型,强行套在styleFrom的参数上就会触发类型不匹配报错。
修正方案
移除shape参数外层的MaterialStateProperty.all包裹,直接传入RoundedRectangleBorder实例即可,修正后代码如下:
Padding( padding: const EdgeInsets.all(20.0), child: ElevatedButton( style: ElevatedButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0)), elevation: 0, // Flutter 3.0及以上版本请将primary替换为backgroundColor primary: Colors.white, minimumSize: const Size.fromHeight(50)), onPressed: () { Navigator.pushNamed(context, '/home'); // Navigator.of(context).pushReplacementNamed('/home'); }, child: const Text( "Start", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 18, color: Color.fromRGBO(86, 96, 49, 1)), )), ),
补充说明
- 若不使用
styleFrom快捷方法,直接传ButtonStyle()实例自定义样式,此时shape参数才需要MaterialStateProperty包装,示例写法:shape: MaterialStateProperty.all<RoundedRectangleBorder>(RoundedRectangleBorder(borderRadius: BorderRadius.circular(10))) styleFrom内部已经完成了不同交互状态下的样式适配逻辑,所有入参直接传对应类型的普通值即可,无需额外包装状态属性。
内容的提问来源于stack exchange,提问作者MûHammad UMar
相关产品推荐
相关产品推荐

