Flutter: debounce 避免高频率事件

it2022-05-05  139

原文

函数

import 'dart:async'; Function debounce(Function fn, [int t = 30]) { Timer _debounce; return () { // 还在时间之内,抛弃上一次 if (_debounce?.isActive ?? false) _debounce.cancel(); _debounce = Timer(Duration(milliseconds: t), () { fn(); }); }; } RaisedButton( onPressed: debounce(() { print(1); }, 3000), child: Text('Test'), )

rxdart

import 'package:rxdart/rxdart.dart'; final _counterSubject = BehaviorSubject<int>(); @override void initState() { super.initState(); _counterSubject.debounceTime(Duration(seconds: 2)).listen((int i) { print(i); }); } RaisedButton( onPressed: () { _counterSubject.add(1); }, child: Text('Test'), )

转载于:https://www.cnblogs.com/ajanuw/p/11148708.html


最新回复(0)