Search code examples
flutterdartgesturedetector

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


I have a simple Text Widget that it's supposed to "light up" (change the text and icon color for as long as the user is pressing down on it) when the user lifts up his finger color reverts to default. I know that it has something to do with GestureDetector, onLongPressStart& onLongPressEndbut I can't figure out how to exactly go from there!

This is the widget:

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,),
        ],
    ),
),

How exactly can I achieve that kind of logic ?


Solution

  • 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),
              ],
            ),
          ),
        );
      }
    }
    

    When you are changing the already defined variable inside the setState it rebuilds the widget with new Value, in this Case it is textColor but you can have many others like this other example.

    suppose we have following variables defined before build function:

    Color textColor = Colors.black;
    String text = "initial Text";
    

    setState function will look like this:

    setState((){
      textColor = Colors.red;
      text = "new Text";
    });