Flutter 容器不响应手势

Flutter container doesn't respond to gestures

如果我有空容器并设置 width/height 手势检测器不起作用,但如果我添加颜色之类的东西,它就会开始工作。

测试应用:

    import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  click(){
    _counter++;
    print('Clicked times: $_counter');
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new GestureDetector(
          onTap: click,
          child: new Container(
            width: 50.0,
            height: 50.0,
            //color: Colors.transparent,
          ),
        ),
      )
    );
  }
}

Expected behavior is that gesture detector works when I set it's child constraints. This is something that possibly happens with all Widgets and other detectors.

Simple use case example - I want to drag some Container that is lets say width/height 4.0, but its too small, so I could embed that into larger emptyContainer with with width/height 16.0 and center alignment and could drag that one.

Workaround: add transparent color.

日志

Doctor summary (to see all details, run flutter doctor -v): [✓] Flutter (Channel master, v0.4.1-pre.25, on Mac OS X 10.13.4 17E202, locale en-US) [✓] Android toolchain - develop for Android devices (Android SDK 27.0.3) [✓] iOS toolchain - develop for iOS devices (Xcode 9.3) [✓] Android Studio (version 3.1) [!] IntelliJ IDEA Ultimate Edition (version 2018.1.2) ✗ Flutter plugin not installed; this adds Flutter specific functionality. ✗ Dart plugin not installed; this adds Dart specific functionality. [✓] Connected devices (2 available)

! Doctor found issues in 1 category.

没有子项的有边界(高度和宽度)的容器只是一个占位符。因此,如果您用 GestureDetector 包装它,它将忽略点击或触摸,因为根据 GestureDetector class、By default a GestureDetector with an invisible child ignores touches; 的官方文档。这就是容器不会响应触摸/点击的原因。

如果你仍然希望空容器响应触摸,你可以使用behavior: HitTestBehavior.opaque 属性 of GestureDetector.

希望这能回答您的问题。