dart 未在所有屏幕上触发点击的手势检测器

rsaldnfx  于 2023-01-10  发布在  其他
关注(0)|答案(2)|浏览(125)

我正在学习flutter,我刚刚创建了一个应用程序,当用户点击屏幕上除AppBar以外的任何部分时,它将更新计数器变量。但是,GestureDetector不会检测屏幕上除文本本身以外的任何点击

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("i am a title"),
          backgroundColor: Colors.teal,
          leading: const Icon(
            Icons.home,
            color: Colors.white,
          ),
        ),
        body: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: const [
              Expanded(
                child: Clicks(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Clicks extends StatefulWidget {
  const Clicks({super.key});

  @override
  State<Clicks> createState() => _ClicksState();
}

class _ClicksState extends State<Clicks> {
  int count = 0;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => setState(
        () {
          count++;
        },
      ),
      child: Center(
        child: Text("total number of clicking on scren is $count "),
      ),
    );
  }
}
bxgwgixi

bxgwgixi1#

GestureDetector将检测其 child 的任何手势-在本例中为Text小部件。
如果你想探测一切,用一个手势探测器包裹入口支架。
在这种情况下,您必须重构代码:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Clicks();
  }
}

class Clicks extends StatefulWidget {
  const Clicks({super.key});

  @override
  State<Clicks> createState() => _ClicksState();
}

class _ClicksState extends State<Clicks> {
  int count = 0;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("i am a title"),
          backgroundColor: Colors.teal,
          leading: const Icon(
            Icons.home,
            color: Colors.white,
          ),
        ),
        body: GestureDetector(
          onTap: () {
            setState(() {
              count++;
            });
          },
          child: SafeArea(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Expanded(
                  child: Text("clicked a total of $count times"),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
db2dz4w8

db2dz4w82#

尝试以下更改:

GestureDetector(
  behavior: HitTestBehavior.translucent,
  onTap: () => setState(
    () {
      count++;
    },
  ),
  child: Center(
    child: Text("total number of clicking on scren is $count "),
  ),
);

相关问题