我有一个按钮,上面有一个孩子的图像。我想要这样,以便在按下按钮时,图像更改为另一张图像,并且当用户停止按下按钮时,图像又回到了原始图像。
基本上,我希望它像凸起的按钮一样工作,但是具有用于凸起和按下状态的自定义图像。
以下是相关代码:
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,
),
),
);
}
}
您可以将默认图像定义为_LoginButtonState
此类的属性
class _LoginButtonState extends State<LoginButton> {
String _myImage = "assets/loginscreen/btn.png"; ... }
现在您的_onClick
方法应该包含状态的更改,只需_myImage
使用if条件即可将字符串更改为新图像
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,
),
),
);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句