我有一个像孩子一样有图像的按钮。我想要它,以便在按下按钮时,图像变为另一个,当用户停止按下按钮时,它会返回到原始图像。
基本上我希望它像凸起的按钮一样,但是具有凸起和按压状态的自定义图像。
以下是相关代码:
class LoginButton extends StatefulWidget {
@override
_LoginButtonState createState() => new _LoginButtonState();
}
class _LoginButtonState extends State<LoginButton> {
void _onClicked() {
setState(() {
//I don't know what I should put here to cause the image to redraw
//only on button press
});
}
@override
Widget build(BuildContext context) {
var assetImage = new AssetImage("assets/loginscreen/btn.png");
var image = new Image(image: assetImage, height: 50.0, width: 330.0);
return new Container(
height: image.height,
width: image.width,
child: new FlatButton(
onPressed: _onClicked,
child: new ConstrainedBox(
constraints: new BoxConstraints.expand(),
child: image,
),
),
);
}
}
答案 0 :(得分:1)
您可以将默认图像定义为类_LoginButtonState
的属性,如此
class _LoginButtonState extends State<LoginButton> {
String _myImage = "assets/loginscreen/btn.png"; ... }
现在,您的_onClick
方法应该包含状态的更改,只需使用if条件将_myImage
的字符串更改为新图像
void _onClicked() {
setState(() {
if (_myImage == "assets/loginscreen/btn.png"){
_myImage = "<my new asset>"; //change myImage to the other one
}
else {
_myImage = "assets/loginscreen/btn.png"; //change myImage back to the original one
}
});
}
并在您的小部件构建中:
var assetImage = new AssetImage(_myImage);
<强> ============================================ =============================== 强>
更新
我已经成功地使用GesutureDetector
对你想要实现的目标做了类似的想法,在这里我用颜色测试它,但它不应该改变图像的链接,尽管我认为重新绘制图像会比改变颜色慢。
以下是我使用的完整代码:
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: new MyApp (),
));
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
var _myColor = Colors.blue;
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text ("Tap me!"),
centerTitle: true,
),
body: new GestureDetector(
onTapDown:(TapDownDetails details) { setState(() {
_myColor = Colors.orange;
});
},
onTapUp: (TapUpDetails details) {
setState(() {
_myColor = Colors.blue;
});
},
child: new Container (
color: _myColor,
),
),
);
}
}
答案 1 :(得分:0)
对我来说,我想要一个没有额外填充的按钮,当我按下按钮时它会变暗! 这是对我有用的代码:
Container(
height: image.height,
width: image.width,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('/images/image.jpeg'),
),
),
child: new FlatButton(
padding: EdgeInsets.all(0.0),
onPressed: () {},
child: null),
),
贷记https://www.youtube.com/watch?v=Ze-BZBv85Ck!这部影片对此有帮助! :)