Flutter IgnorePointer 组件是 Flutter 中用于忽略用户触摸事件的组件

16 min read

IgnorePointer 组件是 Flutter 中用于忽略用户触摸事件的组件。当 IgnorePointer 组件包裹在某个组件内部时,它会忽略包裹在它内部的所有组件的用户触摸事件。例如:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _isIgnoringPointer = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter IgnorePointer Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // A button that toggles the value of _isIgnoringPointer.
            RaisedButton(
              onPressed: () {
                setState(() {
                  _isIgnoringPointer = !_isIgnoringPointer;
                });
              },
              child: Text(_isIgnoringPointer ? 'Unignore' : 'Ignore'),
            ),
            // An IgnorePointer widget that ignores touch events if _isIgnoringPointer is true.
            IgnorePointer(
              ignoring: _isIgnoringPointer,
              child: RaisedButton(
                onPressed: () {
                  print('Button pressed');
                },
                child: Text('Button'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}