美文网首页Flutter基础
Flutter 异步编程

Flutter 异步编程

作者: 奔跑的杰尼龟zxl | 来源:发表于2019-04-09 23:22 被阅读0次
    定时器简要使用
    import 'dart:async';
    void main(){
      print('开始定时器');
      Timer timer = new Timer(const Duration(seconds: 3 ),(){
          print('延迟三秒执行...');
      });
      // 结束 timer.cancel
      print('结束定时器');
    
      //  开始定时器
      //  结束定时器
      //  延迟三秒执行...
    }
    
    /// dart是单线程模型...
    
    async使用
    import 'dart:async';
    void main(){
      printNews();
      methodOne();
    }
    
    void printNews() async{
      String news = await fetchInfo();
      print(news);
    }
    
    void methodOne(){
      print('methodOne 执行任务');
    }
    
    Future fetchInfo(){
      Stream stream = new Stream.periodic(const Duration(seconds: 3),(T) => "goods news");
      return stream.first;
    }
    
    // methodOne 执行任务
    // ......等待3秒种
    // goods news
    // Process finished with exit code 0
    
    异步查看
    void main(){
      print('t1: '+ DateTime.now().toString());
      testAsync();
      print('t2: '+ DateTime.now().toString());
    }
    
    void testAsync() async {
      int result = await Future.delayed(Duration(seconds: 3),(){
        return Future.value(200);
      });
      print('t3:' + DateTime.now().toString());
      print(result);
    }
    
    //t1: 2019-04-09 23:21:27.741782
    //t2: 2019-04-09 23:21:27.753891
    //等待3秒
    //t3:2019-04-09 23:21:30.764490
    //200
    

    在Future结束的时候我们需要进行一系列的操作,then().catchError() 模式
    try-catch, try-catch有个finally代码块,而future.whenComplete 类似于finally

    void main(){
      var random = new Random(47);
      Future.delayed(Duration(seconds: 3),(){
        if(random.nextBool()){
          return 100;
        }else {
          throw 'boom';
        }
      }).then(print).catchError(print).whenComplete((){
        print('done');
      });
    
    // 延迟3秒
    //  100
    //  done
    }
    

    Time设置超时

    void main(){
      Future.delayed(Duration(seconds: 3),(){
        return 1;
      }).timeout(Duration(seconds: 2)).then(print)
          .catchError(print);
      // TimeoutException after 0:00:02.000000: Future not completed
      // Process finished with exit code 0
    }
    

    相关文章

      网友评论

        本文标题:Flutter 异步编程

        本文链接:https://www.haomeiwen.com/subject/kigwiqtx.html