Before we talk about multithreading, let’s look at an example: here is an animation, click the button below the animation to perform a time-consuming task, I take printing a number as an example

import 'package:flutter/material.dart';

class Page2 extends StatefulWidget {
  @override
  _Page2State createState() => _Page2State();
}

class _Page2State extends State<Page2> with SingleTickerProviderStateMixin {

  Animation<double> _animation;
  AnimationController _controller;

  _myPrint(int num) {
    for (int i = 0; i < num; i++) {
      print('$i'); }}_startMyEvent() {
    _myPrint(10000);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(duration: Duration(seconds: 2), vsync: this);
    _animation = Tween<double>(begin: 0.end: 1).animate(_controller).. addStatusListener((status) {if(status == AnimationStatus.completed) { _controller.repeat(); }}); _controller.forward(); } @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('title'),),body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              RotationTransition(
                turns: _animation,
                child: Container(width: 100.height: 100.color: Colors.red),
              ),
              SizedBox(height: 30,),
              FlatButton(
                onPressed: (){
                  _startMyEvent();
                },
                child: Text('Start printing'() [() (() (() (() (() () (() () () () ( }}Copy the code

Click the “Start printing” button and we find that the animation freezes and rotates normally after printing

Let’s put the printed code into the Future for asynchronous execution

_myPrint(int num) {
    for (int i = 0; i < num; i++) {
      print('$i'); }}_startMyEvent() {
    Future((){
      _myPrint(10000);
    });
  }
Copy the code

Dart is known to be a single-threaded model, but it does not mean that all the work of Flutter is done in the same thread. The network requests we are most familiar with are actually multithreaded services invoked by Flutter at the system level. In this case, the ISOLATE in Flutter is used. Compute is the encapsulation of isolate. We can use compute directly as follows:

_myPrint(int num) {
    for (int i = 0; i < num; i++) {
      print('$i'); }}_startMyEvent() {
    compute(_myPrint, 10000);
  }
Copy the code

The first parameter in compute is the name of the method, the second parameter is the parameter to be passed, and when we click the button again, we see that the animation doesn’t lag, and in real life, if we have a time-consuming operation, we can use compute to start a new thread to perform the time-consuming operation.

The salty Fish technical team has a detailed introduction to multi-threading