Ven
Ven

Reputation: 13

Flutter change color of Container inside GestureDetector when it is focused

I am trying to use GestureDetector to display a button using a Container, since I don't like the splash animation from the FlatButton nor Inkwell, what i want to do is to make the user know when the color is being pressed or focused by making the background color of the Container darker, I am using this code below, but I know that this will change the color when pressed and not come back to the regular color when not being pressed. Is there a way to code it so the color changes to darker only when pressed or focusing, and changes back to the regular color when released pressing.

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  bool isTouching = true;

  handleTouch(bool confirmTouch) {
    setState(() {
      isTouching = confirmTouch;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        body: new GestureDetector(
          onTap: () {
            handleTouch(false);
          },
          child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.fromLTRB(25, 15, 20, 8),
                  height: 58,
                  width: 58,
                  child: Icon(
                    Icons.add,
                    color: Colors.white,
                    size: 28,
                  ),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(100),
                    color: isTouching == true ? Colors.green : Colors.red,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Upvotes: 0

Views: 2566

Answers (1)

Mobina
Mobina

Reputation: 7109

Wrap your container with a Listener and use onPointerDown and onPointerUp:

Listener(
    child: Container(
        margin: EdgeInsets.fromLTRB(25, 15, 20, 8),
        height: 58,
        width: 58,
        child: Icon(
            Icons.add,
            color: Colors.white,
            size: 28,
        ),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(100),
            color: isTouching == true ? Colors.green : Colors.red,
        ),
    ),
    onPointerDown: (event) => setState(() {
        isTouching = true;
    }),
    onPointerUp: (event) => setState(() {
        isTouching = false;
    }),
),

Upvotes: 3

Related Questions