When Flutter encounters throttling and anti shake ideas and process optimization

  • 2021-11-01 04:32:54
  • OfStack

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 Dart language, which is used to help developers develop high-performance and 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 one set of codes.

Flutter is based on Dart language. Main advantages:

Free and open source
Take advantage of state-preserving hot overloading (Hot Reload), a new responsive framework, rich controls, and integrated development tools for rapid development.
An appealing and flexible interface design is achieved through a combinable set of controls, a rich animation library, and a hierarchical and extensible architecture.
With the help of portable GPU accelerated rendering engine and high-performance native ARM code runtime, we can achieve high-quality user experience across devices and platforms.
Improve efficiency: Develop Android and iOS simultaneously with one set of code.
Strong extensibility: The Flutter framework itself provides rich Material Design and Cupertino (iOS-flavor) style controls, and the freely extensible controls are not limited by mobile phone platform controls.

However, I believe that web front-end developers have encountered throttling and anti-shake problems more or less. Function throttling and function anti-shake, both of which are a means to optimize the efficiency of code execution. In a given time, the number of times the code is executed is not 1, but the more the better. On the contrary, frequent triggering or execution of code will cause a lot of redrawing and other problems, which will affect browser or machine resources. Therefore, the number of code executions should be controlled in a reasonable range. It can not only save browser CPU resources, but also make page browsing smoother, and will not be stuck due to the execution of js. This is what function throttling and function anti-shake do.

Recently, in an empty cargo management App developed by me for a domestic aviation, the process is optimized by simply using the idea of throttling and anti-shake.

Throttling and anti-shake

Function throttling means that js method only runs once in a fixed time. For example, a person blinks once in a fixed time.

Function anti-shake means that in the case of frequent triggering, only enough idle time can execute the code once. For example, taking the bus in life means that if someone swipes his card one after another to get on the bus within a certain time, the driver will not drive. Drivers drive only when others don't swipe their cards.

Throttling of Flutter

Function throttling, simply speaking, is to make a function unable to be called continuously in a very short time interval. Only when the last function is executed after the time interval specified by you can the next call of the function be made.

Put it into the business to analyze the throttle function:


class MyStatefulWidgetState extends State<OrderPageEdit> {
 bool canScanning; // Can you scan 
 // Scan control flow 
 final Stream<dynamic> _barScanner =
  EventChannel('com.freshport.freshport/barcode').receiveBroadcastStream();
 StreamSubscription<dynamic> _barScannerSubscription;

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

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

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

 // Scanning acquisition 
 scanning(goodsCode) async {
 final result = await fetch.fetch(url: 'www.nicai.com');
 setState(() {
  canScanning = true;
 });
 if (result.result) {
 } else {}
 }
}

Explain this code under 1, because this item has the operation of scanning barcode to move goods to the warehouse. Our expectation is to scan once and read from the database to increase to 1 goods in the list. Therefore, even before this, it cannot be read even if it is scanned. Therefore, I added an flag flag bit to the listening function of _ barScanner. This flag bit is used to judge whether it is in reading. After reading, I set flag to true. At this time, you can continue scanning.

Of course, my throttle function does not have an obvious untriggerable time like some trapping functions. The untriggerable time of this function is the loading time.

Anti-shake of Flutter

The definition of anti-shake function is that after triggering an event several times, the event handling function only executes once, and it is executed at the end of triggering operation. Its principle is to delay the processing function. If the event is triggered again before the set delay comes, the last delay operation timer will be cleared and timed again.

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

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


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

 @override
 void initState() {
 super.initState();
 }

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

 @override
 Widget build(BuildContext context) {
 return TextField(
  controller: _textController,
  decoration: InputDecoration(
   contentPadding: EdgeInsets.all(5.0),
   hintText: " Please enter the product code ",
   prefixIcon: Icon(Icons.search, color: Colors.black),
   focusedBorder: OutlineInputBorder(
    borderSide: BorderSide(color: Colors.black),
   ),
   border:
    OutlineInputBorder(borderRadius: BorderRadius.circular(3.0))),
  onChanged: (String text) {
   // Limit plus throttle 
   if (text.trim().length < 5) return;
   setState(() {
   timer?.cancel();
   timer = new Timer(durationTime, () {
    // Search function 
   });
   });
  });
 }
}

As shown in the code, first set an Timer object. When the input box TextField continues to input, it will directly trigger the cancel event of the Timer object, which will cancel, and then assign a new timing function with a period of 3s to Timer again. This timing function triggers when no information is entered in 3s. But if you type again within 3 seconds, this timing function will be cancelled and a new timing function with a period of 3s will be assigned.

This is the practical application of anti-shake function.

Closing

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

Summarize


Related articles: