更好的解决方案:
expand_hit_test: ^1.0.0
可能会出现分离在不同文件的情况
TapRegionSurface和TapRegion配合使用 扩大点击热区,
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("adsasd"),),
body: Center(
child: Builder(
builder: (context2) {
return CustomExpandTapArea(onTap: (){
print("121212");
Navigator.of(context2).push(MaterialPageRoute(builder: (context){
return Scaffold(
appBar: AppBar(title: Text("adsasd"),),
body: Center(
child: Container(
color: Colors.blue,
width: 100,
height: 100,
),
),
);
}));
}, child: Container(
color: Colors.blue,
width: 100,
height: 100,
),);
}
),
),
),
);
}
}
class CustomExpandTapArea extends StatelessWidget {
final Function onTap;
final double extraNumber;
final Widget child;
final GlobalKey childKey = GlobalKey();
CustomExpandTapArea({super.key, required this.onTap, this.extraNumber = 20, required this.child});
//其实本质就是TapRegion的用法
@override
Widget build(BuildContext context) {
return TapRegionSurface(
child: Container(
padding: const EdgeInsets.all(50),
color: Colors.red,
child: Container(
color: Colors.green,
child: TapRegion(
onTapOutside: (PointerDownEvent event){
RenderBox? tapedRenderBox = childKey.currentContext?.findRenderObject() as RenderBox?;
Offset? globalPosition = tapedRenderBox?.localToGlobal(Offset.zero);
Rect renderBoxFrame = Rect.fromLTWH(globalPosition?.dx ?? 0, globalPosition?.dy ?? 0, tapedRenderBox?.size.width ?? 0, tapedRenderBox?.size.height ?? 0);
Rect extraRenderBoxFrame = renderBoxFrame.inflate(extraNumber);
print("asdasdas===${extraRenderBoxFrame.contains(event.position)}");
if(extraRenderBoxFrame.contains(event.position)) {
onTap();
}
print("点击在区域外");
},
onTapInside: (PointerDownEvent event){
onTap();
print("在区域内点击");
}, child: Center(child: Container(key: childKey,child: child)),
),
),
),
);
}
}