flutter开发中future的使用点滴(汇总)

行业 归档:201907
普通
浏览:3033
2019-07-28 21:08:45
汇总了flutter开发中可能会遇到的一些future特性,有不正确之处,欢迎交流,QQ号码:301109640

只有一个文件,就直接上代码了,实现了一个基本的Column测试布局,使用了一系列的button。future的测试结果信息,print输出到了控制台。

使用截图:

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:math';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutter future'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: <Widget>[
              SizedBox(
                height: 10.0,
              ),
              ConstrainedBox(
                constraints: const BoxConstraints(minWidth: double.infinity),
                child: FlatButton(
                  child: Text('Simple future'),
                  shape: new RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  color: Colors.orange,
                  textColor: Colors.white,
                  onPressed: () async {
                    print("Future started");
                    var futureValue = await myFuture1();
                    print(futureValue);
                  },
                ),
              ),
              SizedBox(
                height: 10.0,
              ),
              ConstrainedBox(
                constraints: const BoxConstraints(minWidth: double.infinity),
                child: FlatButton(
                  child: Text('Duration future'),
                  shape: new RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  color: Colors.orange,
                  textColor: Colors.white,
                  onPressed: () async {
                    print("Future started");
                    var futureValue = await myFuture2();
                    print(futureValue);
                  },
                ),
              ),
              SizedBox(
                height: 10.0,
              ),
              ConstrainedBox(
                constraints: const BoxConstraints(minWidth: double.infinity),
                child: FlatButton(
                  child: Text('Future then'),
                  shape: new RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  color: Colors.orange,
                  textColor: Colors.white,
                  onPressed: () async {
                    print("Future started");
                    myFuture2().then((value) {
                      print("return value '$value'");
                      print("Future finished - THEN");
                    });
                    print('Future now here');
                  },
                ),
              ),
              SizedBox(
                height: 10.0,
              ),
              ConstrainedBox(
                constraints: const BoxConstraints(minWidth: double.infinity),
                child: FlatButton(
                  child: Text('Future error'),
                  shape: new RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  color: Colors.orange,
                  textColor: Colors.white,
                  onPressed: () async {
                    print("Future started");
                    myFutureError().then(
                      (value) {
                        print("return value '$value'");
                        print("Future finished - THEN");
                      },
                      onError: (error) {
                        print(error);
                      },
                    );
                    print('Future now here');
                  },
                ),
              ),
              SizedBox(
                height: 10.0,
              ),
              ConstrainedBox(
                constraints: const BoxConstraints(minWidth: double.infinity),
                child: FlatButton(
                  child: Text('Future Exception'),
                  shape: new RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  color: Colors.orange,
                  textColor: Colors.white,
                  onPressed: () async {
                    print("Future started");
                    myFutureException().then((value) {
                      print("return value '$value'");
                      print("Future finished - THEN");
                    }).catchError((error) {
                      print(error);
                    });
                    print('Future now here');
                  },
                ),
              ),
              SizedBox(
                height: 10.0,
              ),
              ConstrainedBox(
                constraints: const BoxConstraints(minWidth: double.infinity),
                child: FlatButton(
                  child: Text('MultipleDownloads'),
                  shape: new RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  color: Colors.orange,
                  textColor: Colors.white,
                  onPressed: () async {
                    runMultipleDownloads();
                  },
                ),
              ),
              SizedBox(
                height: 10.0,
              ),
              ConstrainedBox(
                constraints: const BoxConstraints(minWidth: double.infinity),
                child: FlatButton(
                  child: Text('Future TimeOut'),
                  shape: new RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  color: Colors.orange,
                  textColor: Colors.white,
                  onPressed: () async {
                    var futureValue = await myTimeoutFuture().timeout(
                      Duration(seconds: 2),
                      onTimeout: () {
                        print('this future has timed out');
                        return 'This is my timeout value';
                      },
                    );
                    print("Future complete: $futureValue");
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  //myFuture1
  Future<String> myFuture1() async {
    return Future.value("This future is complete");
  }

  // myFuture2
  Future<String> myFuture2() async {
    await Future.delayed(Duration(seconds: 1));
    return "This future is complete";
  }

  // myFutureError
  Future<String> myFutureError() async {
    await Future.delayed(Duration(seconds: 1));
    return Future.error("This is an error");
  }

  // myFutureException
  Future<String> myFutureException() async {
    await Future.delayed(Duration(seconds: 1));
    throw Exception('Exception from error');
  }

  // downloadFile
  Future<bool> downloadFile(int id, int duration) async {
    await Future.delayed(Duration(seconds: duration));
    print("Download complele for $id");
    return true;
  }

  // runMultipleDownloads
  Future runMultipleDownloads() async {
    var futures = List<Future>();
    for (var i = 0; i < 10; i++) {
      futures.add(downloadFile(i, Random(i).nextInt(10)));
    }
    print('start downloads...');
    await Future.wait(futures);
    print('All downloads complete');
  }

  // myTimeoutFuture
  Future<String> myTimeoutFuture() async {
    await Future.delayed(Duration(seconds: 5));
    return "Future complete";
  }
}
注意事项
  • 此文章对你有帮助,对作者表示感谢(微信):
  • 本文地址:https://22v.net/article/3247/
  • 转载本文时,请注明转载自“SamBlog”的字样。
  • 如此文章有损您的合法权益,请使用页面底部的邮箱与我取得联系。
分类目录
文章归档
友情站点