Flutter how to use Future return value as if variable

后端 未结 5 997
离开以前
离开以前 2021-02-18 23:50

I want to get Future return value and use it like variable. I have this Future function

  Future _fetchUserInfo(String id)          


        
5条回答
  •  名媛妹妹
    2021-02-19 00:26

    Just adding more explanation/description over the above answers

    When a function returns a Future, it means that it takes a while for its result to be ready, and the result will be available in the future.

    Calling a function that returns a Future, will not block your code, that’s why that function is called asynchronous. Instead, it will immediately return a Future object, which is at first uncompleted.

    Future means that the result of the asynchronous operation will be of type T. For example, if a function returns Future, this means that in the future, it will provide a string to you.

    The result of the Future is available only when the Future is completed. You can access the result of the Future using either of the following keywords:

    1. then

    2. await

    Suppose that the getNews function returns an instance of Future.

    Future getNews() async {
      final response = await http.get(url);
      return response.body;
    }
    

    You can consume the result of this function in either of the following ways:

    getNews().then((news) {
      print(news);
    });
    

    or

    String news = await getNews();
    print(news);
    

    Note that the await keyword can only be used in the body of an async function:

    Future foo() async {
      String news = await getNews();
      print(news);
    }
    

    The result of an async function must be a Future.

    Credit and For more info, see: https://medium.com/@meysam.mahfouzi/understanding-future-in-dart-3c3eea5a22fb

提交回复
热议问题