How Flutter uses Completer to implement anti-shake function _Android_ Script House

How does Flutter use Completer for anti-shake

Updated: March 12, 2024 16:23:11 Author: Lu SAN
Buffering is used to ensure that all triggers in time are merged into a single request. In Flutter, we can use Completer to implement buffering. Let's take a look at the implementation method

In Flutter, Completer can be used to implement anti-shake functionality. Buffeting is used to ensure that all triggers within the time are combined into a single request. For successive event triggers (such as keyboard input by the user, successive button clicks), the actual action is performed only if the event is not triggered again within the specified delay time.

Here is an example of how to implement asynchronous shake prevention using Completer, as follows:

import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Drag to Sort', home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { final List<String> _items = List<String>.generate(10, (i) => 'Item $i'); bool _isReorderable = false; @override void initState() { // TODO: implement initState super.initState(); var debouncer = Debouncer(delay: Duration(seconds: 1)); debouncer.run(() => print('Action 1')); debouncer.run(() => print('Action 2')); debouncer.run(() => print('Action 3')); Future.delayed(Duration(seconds: 2), () {debouncer.run(() => print('Action after delay')); // Delayed (duration (seconds: 2), () {debouncer.run(() => print(' action after delay')); }); } @override Widget build(BuildContext context) { return Scaffold( // backgroundColor: Colors.blueAccent, appBar: AppBar( title: Text('Test'), ), body: Column(children: [ _buildContainer(Colors.lightBlue,const Flexible( child: Text(" This is a project ",maxLines: 1,overflow: TextOverflow.ellipsis,))), _buildContainer(Colors.red, const Flexible(fit: FlexFit.tight, child: Text(" This is a project ",maxLines: 1,overflow: TextOverflow.ellipsis,))), _buildContainer(Colors.purple, Flexible( fit: FlexFit.tight, child: Text(" This is a project "* 6,maxLines: 1,overflow: TextOverflow.ellipsis,)), _buildContainer(Colors.blue, Expanded(child: Text(" This is a project "* 6,maxLines: 1,overflow: TextOverflow.ellipsis,))),],); } Container _buildContainer(Color color,Widget child) { return Container( height: 56, color: color, child: Row(children: [const SizedBox(width:16), const Text(" Source: "), child, const SizedBox(width: 8), Container( padding: EdgeInsets.all(5), decoration: const BoxDecoration( color: Colors.cyan, borderRadius: BorderRadius.all(Radius.circular(6)) ), child: The Text (" project "),), const SizedBox (width: 16),],),); } } class Debouncer { final Duration delay; Completer? _lastCompleter; Timer? _timer; Debouncer({required this.delay}); void run(Function action) {// Cancel if (_lastCompleter!) = null && ! _lastCompleter! .isCompleted) { _lastCompleter! .completeError('Cancelled'); } _lastCompleter = Completer(); // Reset the timer? .cancel(); _timer = Timer(delay, () { action(); _lastCompleter! .complete(); }); // Handle the cancel operation _lastCompleter! .future.catchError((error) {print(' Operation cancelled '); }); }}

Print as follows:

In this example:

  • DebouncerClass contains anti-shake logic.runMethod accepts an action to be executed and ensures that in successive calls, only the last call will be executed after a specified delay.
  • whenrunWhen a method is called continuously, it passesCompleterCancel the previous unfinished action and restart the timer.
  • The last action is performed only when the delay time has passed and there are no new calls.

This approach effectively limits how often events (such as user input, button clicks, etc.) are processed, thereby optimizing performance and resource utilization. In practical applications, you may need to adjust the delay time and processing logic according to the specific situation.

This is the end of the article on how Flutter uses the Completer to implement the Flutter Flutter Flutter anti-shake feature, more Flutter Completer anti-shake content please search for previous articles of Script House or continue to browse the related articles below hope that you will support Script House in the future!

Related article

Latest comments