聚焦时,颤振会更改GestureDetector内的Container的颜色

时间:2020-07-29 22:10:52

标签: flutter dart

我正在尝试使用GestureDetector使用容器显示按钮,因为我不喜欢FlatButtonInkwell的启动动画,我想做的是为了通过使Container的背景色变暗来使用户知道何时按下或聚焦该颜色,我在下面使用此代码,但是我知道这将在按下时改变颜色,并且不会返回到不按时的常规颜色。有没有一种编码方法,因此只有在按下或聚焦时颜色才会变深,而在松开按下时颜色会变回常规颜色。

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

1 个答案:

答案 0 :(得分:3)

Listener包裹容器,并使用onPointerDownonPointerUp

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