flutter - 当函数作为参数传递时,为什么按钮颜色会变为禁用按钮颜色?
问题描述
我遇到了最近对颤动按钮的更改,我正在使用提升按钮。当我将函数作为参数传递给要设置为高架按钮的 onTap 变量的值时,它的颜色会更改为禁用按钮颜色或当我们将 null 分配给 onTap 时使用的颜色,如下所示。
添加以下样式属性不会更改颜色:
style: ElevatedButton.styleFrom(
primary: Colors.white,
onPrimary: Colors.amberAccent,)
但是,如果我们使用 ButtonStyle() 方法,它会改变颜色:
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(Colors.white),
),
- 当函数作为参数传递时,为什么颜色会变为禁用的按钮颜色?
- 为什么 ButtonStyle() 有效,而不是 ElevatedButton.styleFrom()?
这是代码:
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int i = 0;
updatePage(int value) {
setState(() {
i = value;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
MyButton(
s: '10',
f: updatePage(10),
),
MyButton(
s: '20',
f: updatePage(20),
),
],
);
}
}
class MyButton extends StatelessWidget {
final String s;
final Function f;
MyButton({this.s, this.f});
@override
Widget build(BuildContext context) {
return Container(
width: 70,
height: 40,
child: ElevatedButton(
child: Text(s),
onPressed: f,
style: ElevatedButton.styleFrom(
primary: Colors.white,
),
),
);
}
}
谢谢你。
解决方案
你能提供更多信息吗?
我尝试运行以下代码,但看不到“禁用颜色”。您也可以尝试在dartpad上运行此代码
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
void foo() {
print("hello world");
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SizedBox.expand(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.white,
onPrimary: Colors.amberAccent,
),
onPressed: foo,
child: Text("Elevated Button 1"),
),
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(Colors.white),
),
onPressed: foo,
child: Text("Elevated Button 2", style: TextStyle(color: Colors.amberAccent),),
),
],
),
),
),
);
}
}
推荐阅读
- ios - X 轴动作奇怪 - 图表 iOS
- java - 快速关闭等效的java lambda
- r - 如何在 R 中的 Plotly 中使直方图条具有不同的颜色
- laravel - 根据子存在和列值过滤多对多关系
- get - 使用 API 获取 Dailymotion 视频与 Dailymotion 本身完全相同的顺序
- jquery - 如何比较和匹配来自不同元素的字符串?
- python - Pandas 在同一个表中合并多个列,产生意外的输出
- regex - 正则表达式仅匹配关键字
- javascript - 仅选择javascript中的输入字段
- spring - Spring Cloud Kubernetes FeignClient 错误