SoFunction
Updated on 2025-04-10

When Flutter encounters throttling and anti-shake ideas and process optimization

Preface

On Google I/O '17, Google introduced us to Flutter — a new open source library for creating mobile applications.

What is Flutter? It is a mobile application development framework developed by Google using the Dart language to help developers develop high-performance, high-quality native applications on iOS and Android platforms. Flutter is a cross-platform free open source UI framework, and iOS and Android can share a set of code.

Flutter is written in the Dart language. Key advantages:

Free open source
Rapid development with the features of keeping hot reload (Hot Reload), a new responsive framework, rich controls, and integrated development tools.
Able to achieve infectious flexible interface design with a collection of composable controls, a rich animation library, and a layered and extensible architecture.
Achieve high-quality user experience across devices and platforms with portable GPU-accelerated rendering engines and high-performance native ARM code runtimes.
Improve efficiency: Use a set of code to develop both Android and iOS.
Very extensible: The Flutter framework itself provides a wealth of Material Design and Cupertino (iOS-flavor) style controls, which can freely expand controls without being restricted by mobile platform controls.

However, I believe that web front-end developers have encountered problems of throttling and anti-shake to a greater or lesser extent. Function throttling and function anti-shake are both ways to optimize the efficiency of code execution. Within a certain period of time, the more code is executed, the better. On the contrary, frequent triggering or executing code will cause a large number of redrawing and other problems, affecting browser or machine resources. Therefore, the number of code execution times is controlled within a reasonable range. It can not only save browser CPU resources, but also make page browsing smoother, and will not cause lag due to js execution. This is what function throttling and function anti-shake do.

In a recent air cargo management app developed by me for a domestic aviation, I simply used the ideas about throttling and anti-shake to optimize the process.

Throttle and anti-shake

Function throttling means that the js method only runs once within a certain period of time. For example, a person's eyes blinks once within a certain period of time.

Function anti-shake means that when frequently triggered, the code will be executed only once if there is enough free time. For example, taking the bus in life means that if someone swipes his card to get on the bus one after another, the driver will not drive. Only when others have not swiped their cards, the driver will drive.

Flutter's throttling

Function throttling, simply put, makes a function unable to be called continuously within a very short time interval. Only when the last function has been executed after the time interval specified by you can the next call to the function be made.

Put it into the business to analyze the throttling function:

class MyStatefulWidgetState extends State<OrderPageEdit> {
 bool canScanning; //Is it possible to scan //Scan control flow final Stream<dynamic> _barScanner =
  EventChannel('/barcode').receiveBroadcastStream();
 StreamSubscription<dynamic> _barScannerSubscription;

 @override
 void initState() {
 ();
 _barScannerSubscription = _barScanner.listen((data) {
  if (!canScanning) return;
  setState(() {
  canScanning = false;
  });
  scanning(data);
 });
 }

 @override
 void dispose() {
 _barScannerSubscription.cancel();
 ();
 }

 @override
 Widget build(BuildContext context) {
 return Widget;
 }

 //Scan the face to get scanning(goodsCode) async {
 final result = await (url: '');
 setState(() {
  canScanning = true;
 });
 if () {
 } else {}
 }
}

Let me explain this code, because this project has the operation of scanning barcodes to move goods into warehouses. Our expectation is to scan once, read from the database and add it to a cargo in the list. Therefore, it cannot be read even if scanned before this. Therefore, I add a flag flag to the _barScanner listening function. This flag is used to determine whether it is being read. After the reading is completed, the flag is set to true. You can continue scanning at this time.

Of course, my throttling function does not have obvious untriggered time like some interceptor functions. The untriggered time of this function is the loading time.

Flutter's anti-shake

The anti-shake function is defined as the event handling function is executed only once after multiple trigger events and is executed at the end of the trigger operation. The principle is to perform delay operation on the processing function. If the event is triggered again before the set delay arrives, the last delay operation timer will be cleared and the timing will be re-timed.

Anti-shake functions are mostly used to handle real-time search, drag and drop, login username and password format verification. In the js environment, we generally use the timing function setTimeout for anti-shake processing. By the same principle, in Flutter, we will process the timing function (or delay function).

In the time-time search corresponding to an input box, I used anti-shake processing:

class MyStatefulWidgetState extends State<GoodsCodeList> {
 //Search input final TextEditingController _textController = TextEditingController();
 //Set the anti-shake period to 3s Duration durationTime = Duration(seconds: 3);
 Timer timer;

 @override
 void initState() {
 ();
 }

 @override
 void dispose() {
 _textController.clear();
 timer?.cancel();
 ();
 }

 @override
 Widget build(BuildContext context) {
 return TextField(
  controller: _textController,
  decoration: InputDecoration(
   contentPadding: (5.0),
   hintText: "Please enter the product code",
   prefixIcon: Icon(, color: ),
   focusedBorder: OutlineInputBorder(
    borderSide: BorderSide(color: ),
   ),
   border:
    OutlineInputBorder(borderRadius: (3.0))),
  onChanged: (String text) {
   //Limits and throttling   if (().length < 5) return;
   setState(() {
   timer?.cancel();
   timer = new Timer(durationTime, () {
    //Search function   });
   });
  });
 }
}

As shown in the code, first set a Timer object. When the input box TextField continues to input, the cancel event of the Timer object will be triggered, which will cancel it, and then the Timer will be assigned a new timer with a period of 3s. This timing function will be triggered when no information is entered in 3s. However, if you input it again within three seconds, the timing function will be cancelled and then the new timing function with a period of 3s will be assigned.

This is the practical application of the anti-shake function.

ending

We often come into contact with function throttling and anti-shake in js code because in js, DOM operations (onresize, onscroll, etc.) are the most performance-consuming, but in some scenarios the same event will be triggered multiple times. In order to reduce operations, the concepts of anti-shake and throttling are created. In fact, in many developments, we can still use anti-shake and throttling to reduce unnecessary operations and ajax requests.

Summarize

The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.