美文网首页
dart语言基础语法

dart语言基础语法

作者: 这都是大棚的瓜 | 来源:发表于2021-11-14 20:41 被阅读0次
    1. var 、dynamic、Object、final、const

    var 接收任意类型的变量,但是一旦赋值后不能再改变其类型

    //var 接收任意类型的变量
      var a="hello";
      a = 3; //一旦赋值后不能再改变其类型 这一行会报错
    
    // 使用var声明变量的同时未进行初始化,此变量的类型会被推断为dynamic动态类型
      var aa;
      aa="111";
      aa=9;//这一行不会报错,此时已经是动态类型dynamic
    

    dynamic 动态类型,赋值后可以再次改变类型

     dynamic b = 3;
     b = "haha";
    

    Object是所有对象的基类

    Object c = 10;
    c = "hello";
    

    final和const 只能被赋值一次

    final str1 = "kobe"; //编译时常量
    const str2 = "paul"; //第一次使用时被初始化
    
    2.函数
    //函数如果没指定返回类型 则默认是dynamic 函数返回值没有类型推断
    method2() {}
    
    //定义一个函数类型CALLBACK,它的返回值类型为bool 没有参数。
    typedef bool CALLBACK();
    
    //对于只包含一个表达式的函数 使用简写语法如下
    bool isEmpty(String str) => str.length == 0;
    

    //定义一个函数变量
    var say = (int a, int b) => a + b;
    
    //函数作为变量使用
      var sum = say(10, 10);
      print("sum: $sum");
    

    //这个函数有个参数callback 它是一个参数。其他地方调用excute,传入的是一个函数
    void excute(var callback) {
      callback(10, 20);
    }
    
     //函数作为参数传递
      excute((a, b) => print(a + b));
    

    //可选参数
    String getName(String name1, String name2, [String? name3]) {
      var res = name1 + name2;
      if (name3 != null) {
        res = res + name3;
      }
      return res;
    }
    
    //调用可选参数
      print(getName("kobe ", "james"));
      print(getName("kobe ", "james ", "paul"));
    

    //命名参数
    void setFlag({bool? b1, bool? b2}) {}
    
    //调用命名参数
      setFlag(b1: false, b2: true);
    
    3. 异步支持
    //Future.then
    void method11() {
      //延时2s后打印hello world
      //第一个参数为Duration对象,Duration构造时里面是指定命名参数;第二个参数为函数对象
      Future.delayed(new Duration(seconds: 2), () {
        return "hello world";
      }).then((value) => {print(value)});
    }
    
    //Future.catchError用于捕获异常
    void method12() {
      Future.delayed(new Duration(seconds: 2), () {
        throw AssertionError("Error");
      }).then((value) => {print(value)}).catchError((e) {
        print(e);
      });
    }
    
    //Future.catchError用于捕获异常
    void method12() {
      Future.delayed(new Duration(seconds: 2), () {
        throw AssertionError("Error");
      }).then((value) => {print(value)}).catchError((e) {
        print(e);
      });
    }
    
    //then方法还有一个可选参数onError,也可以用它来捕获异常
    void method13() {
      Future.delayed(new Duration(seconds: 2), () {
        throw AssertionError("Error");
      }).then((value) => print(value), onError: (e) {
        print(e);
      });
    }
    
    //Future.whenComplete 无论成功和失败均会调用
    void method14() {
      Future.delayed(new Duration(seconds: 2), () {
        throw AssertionError("Error");
      }).then((value) => print("执行成功:$value")).catchError((e) {
        print("执行失败:$e");
      }).whenComplete(() => print("无论成功还是失败均会调这里"));
    }
    
    4.多个异步任务处理
    //Future.wait 等待多个异步任务全都执行完后再操作
    void method15() {
      Future.wait([
        Future.delayed(new Duration(seconds: 2), () {
          return "hello";
        }),
        Future.delayed(new Duration(seconds: 4), () {
          return " world";
        })
      ]).then((value) => print(value[0] + value[1]), onError: (e) {
        print(e);
      });
    }
    

    //定义了三个方法 返回值均为Future对象
    Future<String> login(String userName, String pwd) {
      return Future<String>.delayed(new Duration(seconds: 2), () {
        print("login:" + new DateTime.now().millisecondsSinceEpoch.toString());
        return userName + pwd;
      });
    }
    
    Future<String> getUserInfo(String id) {
      return Future<String>.delayed(new Duration(seconds: 2), () {
        print(
            "getUserInfo:" + new DateTime.now().millisecondsSinceEpoch.toString());
        return "userinfo userinfo userinfo";
      });
    }
    
    Future saveUserInfo(String userInfo) {
      return Future(() {
        print(
            "saveUserInfo:" + new DateTime.now().millisecondsSinceEpoch.toString());
      });
    }
    
    //使用回调地狱连续执行上面三个任务 可读性差
    task1() {
      login("关羽", "123456")
          .then((id) => getUserInfo(id).then((userInfo) => saveUserInfo(userInfo)));
    }
    
    //使用async/await消除回调地狱 async表示这个方法是异步的
    // await后面接Future 表示等待该异步任务完成 异步任务完成后才会往下运行
    task2() async {
      print("task start:" + new DateTime.now().millisecondsSinceEpoch.toString());
      String id = await login("赵云", "123456");
      String userInfo = await getUserInfo(id);
      await saveUserInfo(userInfo);
      //执行接下来的操作
      print("task end:" + new DateTime.now().millisecondsSinceEpoch.toString());
    }
    

    //Stream 用于接收异步事件数据
    task3() {
      Stream.fromFutures([
        Future.delayed(new Duration(seconds: 2), () {
          print("event 1 " + new DateTime.now().millisecondsSinceEpoch.toString());
          return "1";
        }),
        Future.delayed(new Duration(seconds: 2), () {
          print("event 2 " + new DateTime.now().millisecondsSinceEpoch.toString());
          throw AssertionError("error");
        }),
        Future.delayed(new Duration(seconds: 2), () {
          print("event 2 " + new DateTime.now().millisecondsSinceEpoch.toString());
          return "3";
        })
      ]).listen((event) {
        //监听每个Future的返回结果
        print(event);
      }, onError: (e) {
        //监听执行Futrue时的错误及异常
        print(e);
      }, onDone: () {
        //所有异步事件执行完毕后的回调
        print("event done");
      });
    }
    

    相关文章

      网友评论

          本文标题:dart语言基础语法

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