Old iron remember to forward, Brother Mao will present more Flutter good articles~~~~

WeChat flutter training group ducafecat

original

https://medium.com/flutterdevs/exploring-asynchronous-programming-in-dart-flutter-25f341af32f

text

Asynchronous programming is an equivalent type of programming that allows a unit of work to run independently of the basic application thread. When the work is complete, it tells the main thread. UI widgets accessible in the Flutter structure use Dart's asynchronous programming highlights to achieve extraordinary results, help maintain code coordination, and prevent UI security on the client.

In this blog, we will explore asynchronous programming in Dart & Flutter. We will look at how the asynchronous code pattern can help prepare user interaction and recover data from the network, and see the actions of several asynchronous Flutter widgets in your Flutter application.

Asynchronous programming

It is an equal execution type attached to the chain of events during the programming cycle. For those who are new to asynchronous programming, this is another technique for accelerating the improvement cycle. Nevertheless, we cannot use asynchronous programming on all instances. It is effective when you are looking for frankness rather than productivity. In order to process basic, autonomous information, asynchronous programming is an extraordinary decision.

Various perspectives are the ideal counterparts to Flutter from various perspectives, at any event, for asynchronous programming. Even if Dart is single-threaded, it can be associated with different codes that run in discrete threads. Using synchronous code in Dart will cause delays and hinder the execution of the entire program. Nevertheless, asynchronous programming solves this problem. In addition, this hint improves the execution of the application and the responsiveness of the application.

Why we should use asynchronous programming

Here are some applications of asynchronous programming:

  • Improve work performance and increase work efficiency and responsiveness. Your application, especially when you have long-running activities, does not need to prevent execution. In this case, you can perform other work while waiting for the result of the long-term task
  • Assemble the code in a perfect and easy-to-understand way, which is fundamentally better than the standard code created by traditional threads, and handles the code better. You write less code, and your code will be better than using asynchronous programming in the past Strategies, such as using pure assignment to be more feasible
  • You can use the latest upgrade of the language highlight, such as async / await was presented in a flutter. It appears in a flutter
  • Some improvements have been made to the elements, such as improvements to each async, and a summary of the async types, such as Value.

Future

The way of working in the future is basically the same as Promise in Javascript. It has two expressions: unfinished and completed. The completed future is either valuable or error-prone. The unfinished future is waiting for the asynchronous activity of the function to complete or throwing an error.

This class has several constructors:

  • Future. Means that the Duration object is used as a competitor to show the time span and function of execution after delay
  • Encoding memory caching means storing compressed pictures in memory in their original state
  • Future. means making the future end in error

Use Await/Async

Asynchronous and await methods in Dart are basically the same as in different dialects, but regardless of whether you have any knowledge of asynchronous programming with asynchrony/await, you should think it is easy to understand here.

=> Async function: Functions form the basis of asynchronous programming. There are asynchronous modifiers in the body of these asynchronous functions. Here is an example of synthetic asynchronous work:

void flutter() async {
  print('Flutter Devs');
}

=> Await expression: It allows you to write asynchronous code as if it were synchronous. In summary, the waiting pronunciation has the structure given below:

void main() async {
  await flutter();
  print('flutter Devs done');
}

User interaction event

Perhaps the simplest model for asynchronously processing user input is to use callbacks to respond to connection events on button widgets:

FlatButton(
  child: Text("Data"),
  onPressed: () {
    print("pressed button");
  },
)

Like most Flutter components, the FlatButton component provides a comfortable interface, called onPressed, for buttons that respond quickly. Here, we have passed a mysterious callback capacity to the boundary, which does nothing but print a message to the console. When the client presses catch, the onPressed event is closed, and when the occasional loop can be reached, an unknown function will be executed.

In the background, there is an event flow, and every time another event is added to it, the callback work is called with any relevant information. In this case, the basic catch button has no relevant information, so the callback has no boundaries.

Asynchronous network calls using callbacks

Perhaps the most famous example of asynchronous programming involves obtaining information over the network, for example, via REST services over HTTP:

import 'package:http/http.dart' as http;final future = http.get("https://flutterdevs.com");future.then((response) {
  if (response.statusCode == 200) {
    print("Response received.");
  }
});

The Http package is one of the most famous Dart package repurchases, Pub. I have incorporated an import assertion here to draw attention to average examples of naming imports using http names as keywords. These helpers keep many high-level functions, constants, and factors of the package from conflicting with your code, just like clarifying where functions like get() come from.

The code model shows a classic example of devouring the future. When http.get() is called, the call to it immediately returns an inappropriate Future example. Recall that getting results via HTTP requires a lot of energy, and we don't need to keep the application lazy while on the sidelines. This is why we immediately moved the future back and continued to execute the following lines of code. These next lines use the at that then () strategy of the Future example to get a callback function that will be executed when the REST response occurs sooner or later. In case the inevitable response HTTP status code is 200 (success), we can print a straightforward message to the debug console.

How about improving this example? This model stores the future in the last variable and gets then (), but unless you have a valid reason to keep this future case, skipping this part is average, just like in the corresponding model:

http.get("https://flutterdevs.com").then((response) {
  if (response.statusCode == 200) {
    print("Response received.");
  }
  else {
    print("Response not received");
  }
});

Since the call to get () takes steps on the Future, you can directly call its then () strategy without saving a future reference in a variable. The code is slightly simplified on these lines, but at the same time it can be deciphered. It is feasible to link some valuable recycling registrations to our future, such as:

http.get("https://flutterdevs.com").then((response) {
  if (response.statusCode == 200) {
    print("Response received.");
  }
  else {
    print("Response not received");
  }
}).catchError(() {
  print("Error!");
}).whenComplete(() {
  print("Future complete.");
});

At present, we have set up a callback function. When the HTTP call is closed, an error will be executed instead of the response of catchError. Another callback function will run without considering how to use whenComplete () to complete in the future. This tying technique is conceivable, because every strategy will bring us a reference for the future.

Asynchronous network call without callback

Dart provides an alternative example for solving asynchronous calls. This example looks more like accustomed synchronous code, which can make careful reading and reasoning easier. Asynchronous/waiting punctuation handles a lot of future logistics for you:

Future<String> getData() async {
  final response = await http.get("https://flutterdevs.com");
  return response.body;
}

When you realize that an asynchronous call will be performed inside a function, such as http.get (), you can stamp the function with the async keyword. Asynchronous work consistently returns to the future, you can use the await keyword in its body. In this case, we realize that REST calls will return string information, so we use generics to represent the return type: Future <string>.

You can wait for any function that returns to the future. The getData() function will suspend execution after waiting for a clear run, and return the future to the caller. The code waits closely for the response; it waits for the future completion of the network call. Then, when the response is absurd, execution continues, and the Response object is specified as the last factor, and then getData () returns Response.body, which is a string. You don't have to explicitly return the future from getData(), because the result of this is that the main purpose of await is returned. When you have the string information, you return it, and Dart ends the future with the value.

In order to catch errors when using await, you can use Dart's standard try/catch including:
Future<String> getData() async {
  try {
    final response = await http.get("https://flutterdevs.com");
    return response.body;
  } catch (excute) {
    print("Error: $excute");
  }
}

In this version, we place the code that can throw exemptions to the try block. In the case where everything is easy, we will get a response and return string information, similar to in the earlier model. If an error occurs, the catch block will execute everything considered and pass us a reference to the exemption. Since we haven't added a clear return announcement to the maximum of getData(), Dart will add a specific return null statement there, which will end the future with a null value.

Note that if the network call succeeds, the return will occur in the try block, so the implicit return will not be called.

Callback functions have their uses, and they can be a special way to handle asynchronous communication in simple situations, for example, in response to a client squeeze capture. For more confusing situations, for example, when you need to schedule some asynchronous calls, and each asynchronous call depends on the result of the previous call, Dart's asynchronous/awaiting syntax structure can help you try not to schedule callbacks, which implies here or there. Call back the fire of hell.

FutureBuilder

A FutureBuilder assembles itself according to the given future conditions. For this model, we should expect you to have a function called getData() which returns Future<string>.

class MyStatelessWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: getData(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        }        if (snapshot.hasData) {
          return Text(snapshot.data);
        }        return Container();
      },
    );
  }
}

This custom stateless widget returns a FutureBuilder. If the future returned by getData() has not ended, it will display an advancement pointer. If the future has ended, it will display this information. In case these two things are incorrect, an empty container will be fully considered. You suggest that FutureBuilder pay attention to the boundaries of the future, and then give it a build job that is required for every modification. The build callback gets the typical BuildContext contention, which is a normal situation for all Flutter build activities. It also gets the appearance of AsyncSnapshot. You can use AsyncSnapshot to check the future state and restore any information.

There is a problem with this method. According to the official documentation of FutureBuilder, the future necessities have been prepared before the build step.

To solve this problem, we need to use a stateful widget instead:
class MyStatefulWidget extends StatefulWidget {
  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  Future<String> _dataFuture;  @override
  void initState() {
    super.initState();    _dataFuture = getData();
  }  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _dataFuture,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        }        if (snapshot.hasData) {
          return Text(snapshot.data);
        }        return Container();
      },
    );
  }
}

The adaptation of this widget received future information during initState(). When creating the widget's state object, the initState () technique will be called exactly once.

StreamBuilder

The flow is similar to the event pipeline. Information or error events are directed to one side, and they are passed to the listener on the other side. When you provide StreamBuilder with a reference to the current stream, it subscribes and extracts accordingly to refresh the vital content, and it relies on any information that needs to be a pipeline to assemble itself.

class MyStatelessWidget extends StatelessWidget {
  final Stream<String> dataStream;  const MyStatelessWidget({Key key, this.dataStream}) : super(key: key);  @override
  Widget build(BuildContext context) {
    return StreamBuilder<ConnectionState>(
      stream: dataStream,
      builder: (BuildContext context, AsyncSnapshot<ConnectionState> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        }        if (snapshot.hasData) {
          return Text(snapshot.data);
        }        return Container();
      },
    );
  }
}

to sum up

This article introduces the basic structure of Flutter "Asynchronous Programming in dart and Flutter", you can modify the code according to your choice. This is a small introduction to asynchronous programming user interaction in dart and flutter. From my side, it works using flutter.


© Cat brother

https://ducafecat.tech/

https://github.com/ducafecat

Past

Open source

GetX Quick Start

https://github.com/ducafecat/getx_quick_start

News client

https://github.com/ducafecat/flutter_learn_news

strapi manual translation

https://getstrapi.cn

WeChat discussion group ducafecat

Series collection

Translation

https://ducafecat.tech/categories/%E8%AF%91%E6%96%87/

Open source project

https://ducafecat.tech/categories/%E5%BC%80%E6%BA%90/

Dart programming language basics

https://space.bilibili.com/404904528/channel/detail?cid=111585

Getting started with Flutter zero foundation

https://space.bilibili.com/404904528/channel/detail?cid=123470

Flutter actual combat from scratch news client

https://space.bilibili.com/404904528/channel/detail?cid=106755

Flutter component development

https://space.bilibili.com/404904528/channel/detail?cid=144262

Flutter Bloc

https://space.bilibili.com/404904528/channel/detail?cid=177519

Flutter Getx4

https://space.bilibili.com/404904528/channel/detail?cid=177514

Docker Yapi

https://space.bilibili.com/404904528/channel/detail?cid=130578


独立开发者_猫哥
666 声望126 粉丝