要实现按下时改变RaisedButton的颜色,可以使用InkWell和StatefulWidget来实现。以下是一个示例代码:
import 'package:flutter/material.dart';
class ColorChangingButton extends StatefulWidget {
@override
_ColorChangingButtonState createState() => _ColorChangingButtonState();
}
class _ColorChangingButtonState extends State {
Color buttonColor = Colors.blue;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
setState(() {
buttonColor = Colors.red; // 按下时改变颜色为红色
});
},
onTapCancel: () {
setState(() {
buttonColor = Colors.blue; // 取消点击时恢复颜色为蓝色
});
},
child: Container(
height: 50,
decoration: BoxDecoration(
color: buttonColor,
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: Text(
'Press Me',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
);
}
}
void main() {
runApp(MaterialApp(
home: Scaffold(
body: Center(
child: ColorChangingButton(),
),
),
));
}
在这个示例中,我们使用了InkWell包裹RaisedButton,通过给InkWell的onTap和onTapCancel属性设置回调函数来改变按钮的颜色。在按下时,按钮的颜色会变为红色,取消点击时会恢复为蓝色。注意,我们使用StatefulWidget来管理按钮的状态,并在setState函数中更新按钮的颜色。