如何解决Flutter-只要用户按下窗口小部件即可更改文本样式
我有一个简单的Text
小部件,当用户抬起手指时,它应该会“点亮”(更改文本和图标的颜色,直到用户按下它的时间)默认。
我知道这与GestureDetector
,onLongPressstart
和onLongPressEnd
有关,但是我不知道该怎么去那里!
这是小部件:
GestureDetector(
onLongPressstart: /** change text & icon color */,onLongPressEnd: /** revert to default text & icon color */,child: Row(
children: [
Text("visit us"),SizedBox(width: 6.0),Icon(feathericons.arrowRightCircle,),],
我究竟该如何实现这种逻辑?
解决方法
class MyWidget extends StatefulWidget {
MyWidget({Key key,this.title}) : super(key: key);
final String title;
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
Color textColor = Colors.black;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),),body: GestureDetector(
onLongPressStart: (val){
setState((){
textColor = Colors.red;
});
},onLongPressEnd: (val){
setState((){
textColor = Colors.black;
});
},child: Row(
children: [
Text("visit us",style:TextStyle(color:textColor)),SizedBox(width: 6.0),],);
}
}
当您在setState中更改已经定义的变量时,它将使用新的Value重建小部件,在本例中为textColor
,但您可以像其他示例一样拥有许多其他功能。
假设我们在构建函数之前定义了以下变量:
Color textColor = Colors.black;
String text = "initial Text";
setState
函数将如下所示:
setState((){
textColor = Colors.red;
text = "new Text";
});
,
未经测试,我会尝试在longPressStart上设置一个变量,并在longPressEnd上将其取消设置。 然后,该行的子数组可以类似于:
if(longPressVariable == true) then return [TextWithStyle1] else return [TextWithStyle2]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。