我还没有真正尝试过,但是根据我使用颤振的经验,
我想说您可以在小部件树的顶部创建一个手势检测器,该检测器将在用户点击屏幕时进行捕捉。
例如,您可以记录一个带有时间戳的 int 并在继承的小部件中更新此值(可能必须在手势检测器之上)
最后,任何需要监听的小部件都可以有一个计时器,该计时器每隔 x 时间检查一次时间,并比较是否在 1 到 10 秒之前进行了触摸。
继承的小部件可能是这样的:
class MyInherited extends StatefulWidget {
static MyInheritedData of(BuildContext context) =>
context.inheritFromWidgetOfExactType(MyInheritedData) as MyInheritedData;
const MyInherited({Key key, this.child}) : super(key: key);
final Widget child;
@override
_MyInheritedState createState() => _MyInheritedState();
}
class _MyInheritedState extends State<MyInherited> {
String myField;
void onMyFieldChange(String newValue) {
myField = newValue;
}
@override
Widget build(BuildContext context) {
return MyInheritedData(
myField: myField,
onMyFieldChange: onMyFieldChange,
child: widget.child,
);
}
}
class MyInheritedData extends InheritedWidget {
final String myField;
final ValueChanged<String> onMyFieldChange;
MyInheritedData({
Key key,
this.myField,
this.onMyFieldChange,
Widget child,
}) : super(key: key, child: child);
@override
bool updateShouldNotify(MyInheritedData oldWidget) {
return oldWidget.myField != myField ||
oldWidget.onMyFieldChange != onMyFieldChange;
}
}
小部件树的顶部看起来像这样:
GestureDetector(
onTap: (){
// Update the value of your field
}
最后,当你需要监听这个变化时,你可以像这样添加一个计时器:
Timer timer;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
timer = Timer.periodic(Duration(seconds: 10), (Timer t) {
// Get your inherited widget here and check the value, compare it and act as you pleased
});
});
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
我知道这可能不是一个完美的例子,但希望你能找到正确的道路!我没有时间做出更强有力的答案,但想发表我的观点。
感谢作者在这个问题中的正确答案,因为我从他的回复 Flutter: How to correctly use an Inherited Widget? 中获取了继承的小部件示例