1. 程式人生 > 實用技巧 >flutter -忽略點選事件

flutter -忽略點選事件

absorbPointer開啟absorbing:本身可以接收點選事件,但不會把事件傳遞給子元件。

ignorePointer開啟ignoring:本身和子元件都不能接收點選事件。

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';


void main() => runApp(MaterialApp(
  title: '啦啦啦啦',
  theme: ThemeData(primarySwatch: Colors.red, primaryColor: Colors.green),
  home: PointerIgnorePage(),)
);

class PointerIgnorePage extends StatefulWidget { @override State<StatefulWidget> createState() => PointerIgnorePageState(); } class PointerIgnorePageState extends State<PointerIgnorePage> { bool _ifIgnore = false; @override Widget build(BuildContext context) { return
Scaffold( appBar: AppBar(title: Text('測試忽略點選事件'),), body: Container( alignment: Alignment.center, child: Column( children: <Widget>[ Switch( value: _ifIgnore, onChanged: (value)
=> setState((){_ifIgnore = value;}), ), GestureDetector( onTap: () => print('外層tap1'), child: IgnorePointer( ignoring: _ifIgnore, child: FlatButton(child: Text('點我'), onPressed: () => print('點選了button1'),), ), ), GestureDetector( onTap: () => print('外層tap2'), child: AbsorbPointer( absorbing: _ifIgnore, child: FlatButton(child: Text('點我'), onPressed: () => print('點選了button2'),), ), ), ], ), ), ); } }

關閉_ifIgnore,二者本身都能接收點選事件,child優先接收點選事件,所以分別輸出button1/button2。

開啟_ifIgnore,只有absorbPointer才能接收點選事件,但其內部button無法接收點選事件,所以能輸出tap2。而ignorePointer則完全無法接收點選事件,所以tap1無法輸出。