owned this note
owned this note
Published
Linked with GitHub
---
title: fireship dart full course
tags: dart,flutter,fireship
description: fireship dart full course
---
#### 运行时类型
- `(num1 + num2) is int` 返回boolean
- `runtimeType` 属性返回运行时类型

---
#### NULL SAFETY
> variables cannot be null

> 除非你声明它们可空,它们的值都不能为空
##### 所以以下代码没问题
```=dart
void main() {
int? age = null;
print(age);
Animal animal = Animal();
animal.sayName();
}
```
---
##### late 关键词
> assign a non-nullable value later
```dart=
void main() {
Animal animal = Animal();
animal.sayName();
}
class Animal{
late final String? name;
void sayName(){
name = 'xiaosong';
print(name);
}
}
```
---
#### 随机整数
```=dart
import "dart:math";
void main(){
for(var i=0;i<=10;i++){
print(i);
var r = new Random();
int rn = r.nextInt(100);
if(rn>50){
print(rn);
break;
}else{
print(rn);
continue;
}
}
}
```
> 重点
```
import "dart:math";
var r = new Random();
int rn = r.nextInt(100);
```
---
#### assert 断言
- 调试的时候很有用,生产环境不运行
- assert函数第一个参数是一个返回boolean的表达式
- 第二个参数是一个可选文本参数,如断言失败会print出来
```=dart
void main(){
int age = 32;
int res = 100;
assert(age==res,'age should be $res');
print('good');
}
```
___
#### 一些操作符
##### ??=
> assign value if null,otherwise use current value
```dart=
import "dart:math";
void main(){
String? name;
name = 'xiaosong';
name ??='zhang';
print('name is $name');
}
```
---
##### ??
```
import "dart:math";
void main(){
String? name;
var res = name ?? 'elive';
print('result is $res');
}
```
---
##### 三元操作符 boolean ? a : b
```
String color = 'blue';
var isThisBlue = color == 'blue' ? 'Yep, blue it is' : 'Nah, it aint blue';
```
---
#### cascade
> call method,but return original object;
- old
```dart=
void main(){
Robot cleanRobot = Robot();
cleanRobot.name = 'clean';
cleanRobot.age = 5;
print('robot name is ${cleanRobot.name}');
}
class Robot {
late final String name;
late final int age;
}
```
- with cascade
```dart=
void main(){
Robot cleanRobot = Robot()
..name = 'clean new'
..age = 4;
print('robot name is ${cleanRobot.name}');
}
class Robot {
late final String name;
late final int age;
}
```
---
#### typecast
```dart=
void main(){
var phoneNumber = 23 as double;
print(phoneNumber is double);
print(phoneNumber);
}
```
---
#### function 定义
> 以下写法合法
```dart=
void main(){
shout();
}
shout(){
print('shout!!');
}
```
---
#### function 返回值
```dart=
void main(){
print(shout());
}
String shout(){
print('shout!!');
return 'shout string!';
}
```
---
#### function parameter
```dart=
void main(){
print(shout('dylan'));
}
String shout(String name){
return 'good morning $name';
}
```
---
#### function default parameter
- 定义的时候需要在对象里面
- 可以不传参
- 如果传,则不需要在对象里面
```dart=
void main(){
print(shout());
print(shout(name:'xiaosong'));
}
String shout({String name = 'world'}){
return 'good morning $name';
}
```
```dart=
void main(){
shout('xiaosong', address:'wilmot',age:3);
}
shout(String name,{int age=32,String address='196a st'}){
print(name);
print(age);
print(address);
}
```
---
#### function 多个参数
> 可以按顺序传
```
void main(){
print(shout('xiaosong',42));
}
shout(String name, int age){
print(name);
print(age);
}
```
#### function,对象中定义的参数
- 传参需要显示指定参数名
- 要么required,要么指定默认值
```dart=
void main(){
shout(name:'xiaosong');
}
shout({required String name,address='196a st'}){
print(name);
print(address);
}
```
---
#### arrow function
> => xxx is just a syntaxic sugar to avoid { return xxx; }
- 箭头函数右侧是返回值
- 箭头函数不像ts可以有多行语句,如果涉及多行语句,可以直接用curly函数
- 箭头函数经常作为参数传递到另外一个函数里面 callIt(Function callback)
---
### arrow function 的几种定义方法
- 类似dart普通函数定义,只是箭头替换curly
```dart=
void main(){
Robot myRobot = Robot()
..age = 5;
print(myRobot.calculate());
}
class Robot{
late final int age;
calculate()=> '$age years old';
}
```
- 完全匿名函数
```dart=
void main(){
myHandler(()=>'hello');
}
myHandler(Function callback){
print(callback());
}
```
- 类似定义对象
```dart=
void main(){
myHandler(()=>'hello world!');
}
Function myHandler = (Function callback){
print(callback());
};
```
---
### iterables
- List
- Map
- Set
---
#### List
> List inherits from Iterable


- List支持不同类型元素
- 定义时候加泛型,则只支持一种类型元素
___
##### List一些操作
```dart=
List<int> myList = [1,4,5,9,12,15,19,20,22];
void main(){
List<int> newList = myList.sublist(2,6);
print('list length is ${newList.length}');
//list length is 4
print('the first item is ${newList[0]}');
//the first item is 5
print('the last item is ${newList[3]}');
//the last item is 15
print('the first item is ${myList.first}');
//the first item is 5
print('the first item is ${myList.last}');
//the last item is 15
var myList2 = List.filled(10,'g');
print(myList2);
//[g, g, g, g, g, g, g, g, g, g]
}
```
```dart=
List<int> myList = [1,4,5];
void main(){
List<int> myList = [1,4,5];
myList.add(23);
print(myList);
//[1, 4, 5, 23]
myList.removeLast();
print(myList);
[1, 4, 5]
}
```
```dart=
List<int> myList = [1,4,5];
void main(){
List<int> myList = [1,4,5];
myList.add(23);
print(myList);
//[1, 4, 5, 23]
myList.removeLast();
print(myList);
//[1, 4, 5]
myList.insert(0,1000);
print(myList);
//[1000, 1, 4, 5]
}
```
___
##### forEach和map
> forEach无返回值,map返回一个新数组
- forEach(Function callback)
`list.forEach((n)=>print(n));`
- map(Function callback)
`var doubled = list.map((n)=>n*2);`
---
##### for...in
```dart=
void main(){
List<int> myList = [1,4,5];
for(int i in myList){
print('item is: $i');
}
}
```
___
##### 类似js数组spread
```dart=
List<int> myList = [1,4,5];
var newList = [99,...myList];
var new2List = [...myList,99];
print(newList);
print(new2List);
```
```
List<int> myList = [1,4,5];
var newList = [99,...myList];
var new2List = [...myList,99];
print(newList);
print(new2List);
print([...newList,...new2List]);
```
___
##### 数组中逻辑判断
```dart=
bool isPublished = true;
var students = [
'a','b','c', if(isPublished) 'd'
];
print(students);
//[a, b, c]
```
```dart=
bool isPublished = true;
int age = 43;
var students = [
'a','b','c', 50>age ? 'big': 'small'
];
print(students);
//[a, b, c, big]
```
___
#### Map
- Map本身可以forEach,不可以for(* in *)
- Map的keys,values, entries 可以 for(* in *),不可以forEach
##### Map一些操作
```
Map<String,dynamic> book = {
'name': 'vanvouver1978',
'author': 'dylan',
'publish': 1985,
'isPublished': true
};
print(book.keys);
print(book.values);
print(book.values.toList()[0].runtimeType);
print(book.entries);
print(book['name']);
print(book['author']);
print(book['publish']);
print(book['isPublished']);
for(String bookKey in book.keys){
print('book key is $bookKey');
}
for(dynamic bookValue in book.values){
print('book value is $bookValue');
}
for (MapEntry b in book.entries) {
print('Key ${b.key}, Value ${b.value}');
}
book.forEach((k, v) => print("Key : $k, Value : $v"));
```
___
#### class
##### 构造函数 初始化需要+this
```dart=
void main(){
var robot = Robot(32,'xiaosong');
print(robot.age);
print(robot.name);
}
class Robot {
int age;
String name;
Robot(this.age,this.name);
}
```
___
##### 方法函数调用变量不需要+this
```dart=
void main(){
var robot = Robot(32,'xiaosong');
robot.introduce();
print(robot.age);
print(robot.name);
}
class Robot {
int age;
String name;
Robot(this.age,this.name);
introduce(){
print('my name is $name');
}
}
```
___
##### 有些成员变量需要late
```dart=
void main(){
Rectangle rect = Rectangle(30,40);
print('area ${rect.area}');
}
class Rectangle {
int width;
int height;
late int area;
Rectangle(this.width,this.height){
this.area = this.width * this.height;
}
}
```
___
##### 构造函数可选参数
```dart=
void main(){
Rectangle rect = Rectangle(30,40,'box');
print('area ${rect.area}');
print('rect name is ${rect.name}');
}
class Rectangle {
int width;
int height;
late int area;
String? name;
Rectangle(this.width,this.height,[this.name]){
this.area = this.width * this.height;
}
}
```
___
##### 构造函数命名参数
```dart=
void main(){
Circle myCircle = Circle(rad:3,name:'myCircle');
print(myCircle.rad);
}
class Circle {
int rad;
Circle({required this.rad, String? name});
}
```
> 构造函数前面加const,新建实例时候可以用const,注意成员需要final
```dart=
void main(){
const myCircle = Circle(rad:3,name:'myCircle');
print(myCircle.rad);
}
class Circle {
final int rad;
const Circle({required this.rad, String? name});
}
```
---
##### 方法构造函数
```dart=
void main(){
Position myPosition = Position.fromMap({'x':321,'y':231});
print(myPosition.x);
Position myAnotherPosition = Position.fromList([321,231]);
print(myAnotherPosition.y);
}
class Position {
int x = 0;
int y = 0;
Position.fromMap(Map mapData){
x = mapData['x'];
y = mapData['y'];
}
Position.fromList(List listData){
x = listData[0];
y = listData[1];
}
}
```
___
#### interface
```
class Elephant {
// Public interface
final String name;
// In the interface, but visible only in this library. (private)
final int _id = 23;
// Not in the interface, since this is a constructor.
Elephant(this.name);
// Public method.
sayHi() => 'My name is $name.';
// Private method.
_saySecret() => 'My ID is $_id.';
}
```
___
##### implements
```dart=
void main(){
const myPolice = Police('xiaosong',42);
myPolice.introduce();
}
class Police implements Person{
final int age;
final String name;
const Police(this.name,this.age):super();
introduce(){
print(name);
}
}
abstract class Person {
final int age;
final String name;
const Person(this.name,this.age);
void introduce();
}
```
___
##### flutter中常见的extends
```
class GreenFrog extends StatelessWidget{
const GreenFrog({Key? key}) : super(key:key);
@override
Widget build(BuildContext context){
return Container(color: const Color(0xFF2DBD3A));
}
}
```
___
##### 自己实现一个extends
```
void main(){
const myPolice = Police('dylan',42,'manager');
myPolice.introduce();
}
abstract class Person {
final String name;
final int age;
const Person(this.name,this.age);
void introduce(){
print(name);
print(age);
}
}
class Police extends Person{
final String name;
final int age;
final String title;
const Police(this.name,this.age,this.title): super(name,age);
@override
void introduce(){
super.introduce();
print(title);
}
}
```
___
##### 再实现一个
```
void main(){
Police myPolice = Police(name:'dylan', age:42, title:'manager');
myPolice.introduce();
}
abstract class Person {
final String name;
final int age;
const Person(this.name,this.age);
void introduce(){
print(name);
print(age);
}
}
class Police extends Person{
late final String name;
late final int age;
late final String title;
Police({required name,required age,required title}): super(name,age){
this.name = name;
this.age = age;
this.title = title;
}
@override
void introduce(){
super.introduce();
print(title);
}
}
```
___
##### 另外一种写法
```
void main(){
Police myPolice = Police(name:'dylan', age:43, title:'manager');
myPolice.introduce();
}
abstract class Person {
final String name;
final int age;
const Person(this.name,this.age);
void introduce(){
print(name);
print(age);
}
}
class Police extends Person{
late final String name;
late final int age;
late final String title;
Police({required this.name,required this.age,required this.title}): super(name,age);
@override
void introduce(){
super.introduce();
print(title);
}
}
```
___
##### 似乎这种写法更合理?
```
void main(){
Police myPolice = Police('dylan', 44, title:'manager');
myPolice.introduce();
}
abstract class Person {
final String name;
final int age;
const Person(this.name,this.age);
void introduce(){
print(name);
print(age);
}
}
class Police extends Person{
late final String name;
late final int age;
late final String title;
Police(this.name,this.age,{required this.title}): super(name,age);
@override
void introduce(){
super.introduce();
print(title);
}
}
```
___
#### mixin
- mixin写法类似于class,关键词换成mixin
- mixin没有构造函数
- mixin调用方法是with
- mixin可以通过get方法获取寄生类成员属性值
```dart=
void main(){
SuperMan mySuperMan = SuperMan('xiaosong',42);
mySuperMan.sayFast();
mySuperMan.sayStrong();
mySuperMan.sayName();
}
class Human{
String name;
int age;
Human(this.name,this.age);
void sayName(){
print('my name is $name');
}
}
mixin Strong{
int weight = 100;
String get name;
void sayStrong(){
print('i am ${this.weight}');
print('my name mixin is $name');
}
}
mixin Fast{
int speed = 120;
void sayFast(){
print('i am ${this.speed}');
}
}
class SuperMan extends Human with Strong,Fast{
String name;
int age;
SuperMan(this.name,this.age):super(name,age);
}
```
___
#### Generics
```
void main(){
Box<String> myBox = Box('hello world');
print(myBox.value);
print('return value is ${myBox.openBox()}');
Box<int> myBox2 = Box(32);
print(myBox2.value);
print('return value is ${myBox2.openBox()}');
Box<double> myBox3 = Box(3.2);
print(myBox3.value);
print('return value is ${myBox3.openBox()}');
Box<List<int>> myBox4 = Box([2,3,4,9,0]);
print(myBox4.value);
print('return value is ${myBox4.openBox()}');
}
class Box<T> {
T value;
Box(this.value);
T openBox(){
return value;
}
}
```
___
##### Future
- 可以写成then的形式
```dart=
void main(){
Future delay = Future.delayed(Duration(seconds:5));
delay.then((value)=>print('delayed')).catchError((e)=>print('erro!$e'));
}
```
- async函数定义在curly前
```dart=
Future<String> myFunc() async {
...
}
```
```dart=
void main() async{
MyFutureMessage myFutureMessage = MyFutureMessage('xiaosong');
String message = await myFutureMessage.showMessage();
print(message);
}
class MyFutureMessage {
String name;
MyFutureMessage(this.name);
Future<String> showMessage() async {
String result = await Future.value(name);
return 'my name is $result';
}
}
```
___
##### stream
- stream从`dart:async`中导入
- stream默认不是broadcast
- stream可以写到async中,以for in的形式
```
import 'dart:async';
void main() {
Stream myStream = Stream.fromIterable([1,4,5,3,2,9,2]).asBroadcastStream();
myStream.listen((v)=>print(v));
myStream.map((v)=>v*3).listen((v)=>print('triple is $v'));
}
```
___
```
import 'dart:async';
void main() {
void forInStream() async {
Stream myStream = Stream.fromIterable([1,4,5,3,2,9,2]).asBroadcastStream();
await for(int value in myStream) {
print(value);
}
}
forInStream();
}
```