Android Flutter Dart语言入门

本文介绍Dart语言的基础概念,包括变量声明、类型、final与const关键字、函数声明及异步编程支持。深入探讨dynamic与Object的区别,final和const的使用场景,以及Future和Stream在处理异步操作中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Dart 文章

1. Dart概览与基础

变量声明
var t;
t = "hi world";
// 下面代码在dart中会报错,因为变量t的类型已经确定为String,
// 类型一旦确定后则不能再更改其类型。
t = 1000;
dynamic和Object

Object 是Dart所有对象的根基类

dynamic与var一样都是关键词,声明的变量可以赋值任意对象

dynamic与Object不同的是,dynamic声明的对象编译器会提供所有可能的组合, 而Object声明的对象只能使用Object的属性与方法, 否则编译器会报错

相同之处在于,他们声明的变量可以在后期改变赋值类型

final和const

如果未打算更改一个变量,那么使用 finalconst

被final或者const修饰的变量,变量类型可以省略

函数

Dart函数声明如果没有显式声明返回值类型时会默认当做dynamic处理,注意,函数返回值没有类型推断

// 不指定返回类型,此时默认为dynamic,不是bool
isNoble(int atomicNumber) {
  return _nobleGases[atomicNumber] != null;
}

可选的位置参数

// 包装一组函数参数,用[]标记为可选的位置参数
String say(String from, String msg, [String device]) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  return result;
}

// 结果是: Bob says Howdy
say('Bob', 'Howdy'); 

// 结果是:Bob says Howdy with a smoke signal
say('Bob', 'Howdy', 'smoke signal'); 
异步支持

asyncawait关键词支持了异步编程,允许写出和同步代码很像的异步代码

Dart中的async/await 和JavaScript中的async/await功能和用法是一模一样

Future

Future与JavaScript中的Promise非常相似,表示一个异步操作的最终完成(或失败)及其结果值的表示

一个Future只会对应一个结果,要么成功,要么失败

Future 的所有API的返回值仍然是一个Future对象,所以可以很方便的进行链式调用


// Future.then

// 2秒后返回结果字符串"hi world!"
Future.delayed(new Duration(seconds: 2),(){
   return "hi world!";
}).then((data){
   print(data);
});
// Future.wait
// 等两个异步任务都执行成功时,将两个异步任务的结果拼接打印出来
// 执行上面代码,4秒后你会在控制台中看到“hello world”
Future.wait([
  // 2秒后返回结果  
  Future.delayed(new Duration(seconds: 2), () {
    return "hello";
  }),
  // 4秒后返回结果  
  Future.delayed(new Duration(seconds: 4), () {
    return " world";
  })
]).then((results){
  print(results[0]+results[1]);
}).catchError((e){
  print(e);
});

使用Future消除Callback Hell

// Future 的所有API的返回值仍然是一个Future对象,所以可以很方便的进行链式调用”
login("alice","******").then((id){
      return getUserInfo(id);
}).then((userInfo){
    return saveUserInfo(userInfo);
}).then((e){
   //执行接下来的操作 
}).catchError((e){
  //错误处理  
  print(e);
});

还有一种很牛的异步代码写成同步代码样式的方法

我们通过async/await将一个异步流用同步的代码表示出来

task() async {
   try{
    String id = await login("alice","******");
    String userInfo = await getUserInfo(id);
    await saveUserInfo(userInfo);
    //执行接下来的操作   
   } catch(e){
    //错误处理   
    print(e);   
   }  
}

其实,无论是在JavaScript还是Dart中,async/await都只是一个语法糖,编译器或解释器最终都会将其转化为一个Promise(Future)的调用链

Stream

Stream 也是用于接收异步事件数据,和Future 不同的是,它可以接收多个异步操作的结果(成功或失败)

Stream.fromFutures([
  // 1秒后返回结果
  Future.delayed(new Duration(seconds: 1), () {
    return "hello 1";
  }),
  // 抛出一个异常
  Future.delayed(new Duration(seconds: 2),(){
    throw AssertionError("Error");
  }),
  // 3秒后返回结果
  Future.delayed(new Duration(seconds: 3), () {
    return "hello 3";
  })
]).listen((data){
   print(data);
}, onError: (e){
   print(e.message);
},onDone: (){

});

// 上述代码依次输出:
I/flutter (17666): hello 1
I/flutter (17666): Error
I/flutter (17666): hello 3

参考文章:Dart语言简介

持续补充…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

初心一点

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值