flutter определяет координаты нажатой точки кнопки

Я делаю кнопку с двумя боковыми действиями: сначала уменьшаю количество элементов, а второй увеличиваю количество элементов, мне нужно получить координаты нажатой точки кнопки.

Я использовал GestureDetector с onTapDown, но у него есть задержка.

Спасибо.

      GestureDetector(
          onTapDown: _handleTapDown
)

void _handleTapDown(TapDownDetails details) {
    final RenderBox referenceBox = context.findRenderObject() as RenderBox;
    setState(() {
      final touchPoint = referenceBox.globalToLocal(details.globalPosition);
      if (touchPoint.dx <= width of btn) {
        print(touchPoint.dx);
      } else {
        print("-----${touchPoint.dx}");
      }
    });
  }

текущий код

          Container(
        height: 30,
        child: TextButton(
          style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(Design.appColor),
              padding: MaterialStateProperty.all(EdgeInsets.symmetric(vertical: 8, horizontal: 10)),
              shape: MaterialStateProperty.all(RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0),
              ))
          ),
          onPressed: (){
          },
          child: Container(
            child: RichText(
              text:  TextSpan(
                text: "",
                children:[
                  WidgetSpan(
                    alignment: PlaceholderAlignment.middle,
                    child: Icon(Icons.remove, size: 14, color: Colors.white),
                  ),
                  TextSpan(
                    text: "  ${widget.model[index].sale?.minPrice ?? widget.model[index].sale?.price} ₽  ",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                        fontFamily: "Inter"
                    ),
                  ),
                  WidgetSpan(
                    alignment: PlaceholderAlignment.middle,
                    child: Icon(Icons.add, size: 14, color: Colors.white),
                  )
                ],
              ),
            ),
          ),
        ),
      );

3 ответа

Поскольку вы также используете , GestureDetector.onTapне поможет вам получить подробную информацию, поэтому мы будем использовать onPanDown. Все, что вам нужно сделать, это обернуть TextButtonв GestureDetectorкак это:

      Container(
  height: 30,
  child: GestureDetector(
    onPanDown: (details) {
      // You're looking for these values. 
      final globalPosition = details.globalPosition;
      final globalDx = globalPosition.dx;
      final globalDy = globalPosition.dy;
      
      final localPosition = details.localPosition;
      final localDx = localPosition.dx;
      final localDy = localPosition.dy;
    },
    child: TextButton(...), // Your TextButton code goes here. 
  ),
)

Вы можете использовать GestureDetector:

      GestureDetector(
        onTapDown: (TapDownDetails details) => print(details.localPosition),
        onTapUp: (TapUpDetails details) => print(details.localPosition),
        child: Container(
    ...

Но вам нужно будет удалить TextButtonпотому что это будет мешать onTapDownа также onTapUpзакрытия.

Скриншот:

Я думаю, вам следует использовать другой подход для обработки вашего дела. Это базовый пример, чтобы дать вам представление, не стесняйтесь экспериментировать с макетом и его значениями.


Код:

      int _price = 90;
  
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Material(
          color: Colors.green[400],
          child: SizedBox(
            width: 100,
            height: 40,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _buildIcon(
                  onPressed: () => setState(() => _price--),
                  icon: Icon(Icons.remove),
                ),
                Text('€ $_price'),
                _buildIcon(
                  onPressed: () => setState(() => _price++),
                  icon: Icon(Icons.add),
                ),
              ],
            ),
          ),
        ),
      ),
    ),
  );
}
  
Widget _buildIcon({required VoidCallback onPressed, required Icon icon}) {
  return InkWell(
    onTap: onPressed,
    child: Center(child: icon),
  );
}
Другие вопросы по тегам