什么是未来,我将如何使用它? [英] What is a Future and how do I use it?

查看:136
本文介绍了什么是未来,我将如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误:

A value of type 'Future<int>' can't be assigned to a variable of type 'int'

它可能是另一种类型,而不是int,但是基本上模式是

It might be another type instead of int, but basically the pattern is

A value of type 'Future<T>' can't be assigned to a variable of type 'T'

所以...

  • Future到底是什么?
  • 我如何获得想要获得的实际价值?
  • 当我只有Future<T>时,我该使用什么小部件来显示我的值?
  • What exactly is a Future?
  • How do I get the actual value I want to get?
  • What widget do I use to display my value when all I have is a Future<T>?

推荐答案

如果您熟悉

In case you are familiar with Task<T> or Promise<T> and the async/ await pattern, then you can skip right to the "How to use a Future with the widgets in Flutter" section.

文档说:

代表延迟计算的对象.

An object representing a delayed computation.

那是正确的.它也有点抽象和枯燥.通常,函数返回结果.依序.该函数将被调用,运行并返回结果.在此之前,呼叫者等待.某些功能(尤其是当它们访问诸如硬件或网络之类的资源时)花费一些时间.想象从网络服务器上加载头像图片,从数据库中加载用户数据,或者仅从设备内存中加载多种语言的应用程序文本.那可能很慢.

That is correct. It's also a little abstract and dry. Normally, a function returns a result. Sequentially. The function is called, runs and returns it's result. Until then, the caller waits. Some functions, especially when they access resources like hardware or network, take a little time to do so. Imagine an avatar picture being loaded from a web server, a user's data being loaded from a database or just the texts of the app in multiple languages being loaded from device memory. That might be slow.

默认情况下,大多数应用程序只有一个控制流.当阻止此流时(例如,通过等待耗时的计算或资源访问),应用程序将冻结.如果年龄足够大,您可能会记得这是标准配置,但是在当今世界,这将被视为错误.即使花费一些时间,我们也会得到一些动画效果.一个微调器,一个沙漏,也许是一个进度条.但是,应用程序如何运行并显示动画却仍然等待结果呢?答案是:异步操作.代码等待某些操作时仍在运行的操作.现在,编译器如何知道,它是否应该实际上停止所有操作并等待结果,还是继续所有后台工作并仅在这种情况下等待?好吧,它不能自己弄清楚这一点.我们必须告诉.

Most applications by default have a single flow of control. When this flow is blocked, for example by waiting for a computation or resource access that takes time, the application just freezes. You may remember this as standard if you are old enough, but in today's world that would be seen as a bug. Even if something takes time, we get a little animation. A spinner, an hourglass, maybe a progress bar. But how can an application run and show an animation and yet still wait for the result? The answer is: asynchronous operations. Operations that still run while your code waits for something. Now how does the compiler know, whether it should actually stop everything and wait for a result or continue with all the background work and wait only in this instance? Well, it cannot figure that out on it's own. We have to tell it.

这是通过称为的问题.它不特定于找到该文档.

This is achieved through a pattern known as async and await. It's not specific to flutter or dart, it exists under the same name in many other languages. You can find the documentation for Dart here.

由于花费一些时间的方法无法立即返回,因此它将返回完成时传递值的承诺.

Since a method that takes some time cannot return immediately, it will return the promise of delivering a value when it's done.

这称为Future.因此,从数据库中加载数字的承诺会返回Future<int>,而从互联网搜索中返回电影列表的承诺可能会返回Future<List<Movie>>. Future<T>是将来 会给您的T.

That is called a Future. So the promise to load a number from the database would return a Future<int> while the promise to return a list of movies from an internet search might return a Future<List<Movie>>. A Future<T> is something that in the future will give you a T.

让我们尝试不同的解释:

Lets try a different explanation:

Future表示异步操作的结果,并且可以具有两种状态:未完成或已完成.

A future represents the result of an asynchronous operation, and can have two states: uncompleted or completed.

很可能是因为您不是出于娱乐目的而这样做,实际上您需要该Future<T>的结果才能在您的应用程序中进行.您需要显示数据库中的号码或找到的电影列表.因此,您要等待,直到结果出现为止.这是await出现的地方:

Most likely, as you aren't doing this just for fun, you actually need the results of that Future<T> to progress in your application. You need to display the number from the database or the list of movies found. So you want to wait, until the result is there. This is where await comes in:

Future<List<Movie>> result = loadMoviesFromSearch(input);

// right here, you need the result. So you wait for it:
List<Movie> movies = await result;

但是,等一下,我们还没来回吗?我们不是又在等待结果吗?是的,的确如此.如果程序与顺序流没有某种相似之处,它们将完全混乱.但是要点是,使用关键字await告诉编译器,在这一点上,尽管我们要等待结果,但我们不希望应用程序冻结.我们希望所有其他正在运行的操作(例如动画)继续进行.

But wait, haven't we come full circle? Aren't we waiting on the result again? Yes, indeed we are. Programs would be utterly chaotic if they did not have some resemblence of sequential flow. But the point is that using the keyword await we have told the compiler, that at this point, while we want to wait for the result, we do not want our application to just freeze. We want all the other running operations like for example animations to continue.

但是,您只能在本身标记为async的函数中使用await关键字并返回Future<T>.因为当您await执行某些操作时,正在等待的函数将无法立即返回其结果.您只能退还所拥有的东西,如果您必须等待,则必须退还保证书,以便以后交付.

However, you can only use the awaitkeyword in functions that themselves are marked as async and return a Future<T>. Because when you await something, then the function that is awaiting can no longer return their result immediately. You can only return what you have, if you have to wait for it, you have to return a promise to deliver it later.

Future<Pizza> getPizza() async {
    Future<PizzaBox> delivery = orderPizza();        

    var pizzaBox = await delivery;

    var pizza = pizzaBox.unwrap();
    
    return pizza;   
}

我们的getPizza函数必须等待,所以比萨饼必须立即返回将来会出现的承诺,而不是立即返回Pizza. >.现在,您可以依次在某处await getPizza函数.

Our getPizza function has to wait for the pizza, so instead of returning Pizza immediately, it has to return the promise that a pizza will be there in the future. Now you can, in turn, await the getPizza function somewhere.

扑朔迷离的所有小部件都希望有真实值.不久以后就没有价值的承诺了.当按钮需要文本时,它不能使用承诺文本稍后会出现的承诺.它需要显示按钮 now ,所以它需要文本 now .

All the widgets in flutter expect real values. Not some promise of a value to come at a later time. When a button needs a text, it cannot use a promise that text will come later. It needs to display the button now, so it needs the text now.

但是有时候,您所拥有的只是一个Future<T>.这就是 FutureBuilder 出现的地方.您可以在以下情况下使用它您有未来,可以在等待时显示一件事(例如进度指示器),在完成时显示另一件事(例如结果).

But sometimes, all you have is a Future<T>. That is where FutureBuilder comes in. You can use it when you have a future, to display one thing while you are waiting for it (for example a progress indicator) and another thing when it's done (for example the result).

让我们看一下我们的披萨示例.您想订购披萨,想要在等待时显示进度指示器,想要在交货后查看结果,并且可能在出现错误时显示错误消息:

Let's take a look at our pizza example. You want to order pizza, you want a progress indicator while you wait for it, you want to see the result once it's delivered, and maybe show an error message when there is an error:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

/// ordering a pizza takes 5 seconds and then gives you a pizza salami with extra cheese
Future<String> orderPizza() {
  return Future<String>.delayed(Duration(seconds: 5), () async => 'Pizza Salami, Extra Cheese');
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: Scaffold(
        body: Center(
          child: PizzaOrder(),
        ),
      ),
    );
  }
}

class PizzaOrder extends StatefulWidget {
  @override
  _PizzaOrderState createState() => _PizzaOrderState();
}

class _PizzaOrderState extends State<PizzaOrder> {
  Future<String> delivery;

  @override
  Widget build(BuildContext context) {
    return Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          RaisedButton(
            onPressed: delivery != null ? null : () => setState(() { delivery = orderPizza(); }),
            child: Text('Order Pizza Now')
          ),
          delivery == null
            ? Text('No delivery scheduled')
            : FutureBuilder(
              future: delivery,
              builder: (context, snapshot) {
                if(snapshot.hasData) {
                  return Text('Delivery done: ${snapshot.data}');
                } else if(snapshot.hasError) {
                  return Text('Delivery error: ${snapshot.error.toString()}');
                } else {
                  return CircularProgressIndicator();
                }
              })
        ]);
  }
}

这是您使用FutureBuilder显示未来结果的方式.

This is how you use a FutureBuilder to display the result of your future once you have it.

这篇关于什么是未来,我将如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆