dylansong
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: fireship dart full course tags: dart,flutter,fireship description: fireship dart full course --- #### 运行时类型 - `(num1 + num2) is int` 返回boolean - `runtimeType` 属性返回运行时类型 ![](https://d.pr/i/QXX8E6.png) --- #### NULL SAFETY > variables cannot be null ![](https://d.pr/i/TRiLtB.png) > 除非你声明它们可空,它们的值都不能为空 ##### 所以以下代码没问题 ```=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 ![](https://d.pr/i/GoW4bz.png) ![](https://d.pr/i/YbVd3U.png) - 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(); } ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully