Flutter - 只要用户按下小部件即可更改文本样式

Flutter - Change text style as long as the user pressing the widget

我有一个简单的 Text 小部件,当用户抬起手指颜色时,它应该“亮起”(只要用户按下它就会更改文本和图标颜色)恢复为默认值。 我知道它与 GestureDetectoronLongPressStart& 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,),
        ],
    ),
),

我怎样才能实现这种逻辑?

在没有测试的情况下,我会尝试在 longPressStart 上设置一个变量并在 longPressEnd 上取消设置。 然后,行的 child-array 可以是这样的:

if(longPressVariable == true) then return [TextWithStyle1] else return [TextWithStyle2]

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";
});