Flutter开发笔记14 - http请求与Future开发

GitHub 地址:https://github.com/LINGLemon/FlutterFutureDemo

1、需在pubspec.yaml中导入http插件包

dependencies:
 http: ^0.12.0+1

然后执行flutter packages get

2、test1:future小demo


  // 1、测试future
  _test1() {
    print('t1:' + DateTime.now().toString());
    _testFuture();
    print('t2:' + DateTime.now().toString());
  }

  _testFuture() async {
    int result = await Future.delayed(Duration(milliseconds: 2000), () {
      return Future.value(123);
    });
    print('t3:' + DateTime.now().toString());
  }

以上执行顺序是t1,t2,t3,其中_testFuture()是异步执行的结果。

3、测试future timeout


  // 2、测试future timeout
  _test2() {
    Future.delayed(Duration(seconds: 3), () {
      return 1;
    }).timeout(Duration(seconds: 2)).then(print).catchError(print);
  }

这里,终端会直接显示错误信息。

4、future的成功返回,与抛出错误信息与捕获future的异常

3种,一种成功,两种抛出错误:

  Future _testFuture3() {
//    throw Error();
//    return Future.value('Success');
    return Future.error('error');
  }

 


  // 3、捕获future的异常
  _test3() {
    _testFuture3().then((s) {
      print(s);
    }, onError: (e) {
      print('onError: ');
      print(e);
    }).catchError((e) {
      print('catchError: ');
      print(e); // onError与catchError同时存在,只会调用onError
    });
  }

5、future.whenComplete


  // 4、future.whenComplete
  _test4() {
    var random = Random();
    Future.delayed(Duration(seconds: 2), () {
      if (random.nextBool()) {
        return 100;
      } else {
        throw 'boom!';
      }
    }).then(print).catchError(print).whenComplete(() {
      print('_test4 done!');
    });
  }

 

你可能感兴趣的:(Android,iOS,Flutter,Flutter开发笔记)