我有一个简单的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,),
],
),
),我到底该如何实现这种逻辑呢?
发布于 2020-10-22 23:05:20
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中更改已定义的变量时,它将使用新值重新构建小部件,在本例中为textColor,但您也可以有许多其他类似于此示例的变量。
假设我们在构建函数之前定义了以下变量:
Color textColor = Colors.black;
String text = "initial Text";setState函数将如下所示:
setState((){
textColor = Colors.red;
text = "new Text";
});发布于 2020-10-22 22:59:39
在没有测试的情况下,我会尝试在longPressStart上设置一个变量,并在longPressEnd上取消设置它。然后,行的子数组可以是这样的:
if(longPressVariable == true) then return [TextWithStyle1] else return [TextWithStyle2]
https://stackoverflow.com/questions/64484852
复制相似问题