Dart-3 使用庫 引入 按需加載-異步(基礎)

5) 使用庫 引入 按需加載

其中 pag.Calc.dart文件內(nèi)容,簡單的 相加求和 ,還有一個相減求差。

int add(int x,int y){
  return x+y;
}

class Calc {
  int x;
  int y;
  Calc(int x , int y){
    this.x = x;
    this.y = y;
  }
  minus(){
    print(this.x-this.y);
  }
}

主程序如下:


import 'dart:convert';
//import 'dart:math';

import 'pkg/Calc.dart'; //引入
import 'package:http/http.dart' as http;  //調(diào)用外部的包
// deferred 延時加載  使用時 加載
import 'dart:math' deferred as math; //調(diào)用dart自身的包

void main() async {
  int start = 1;
  int count = 2;
  int result = add(2, 4);
  print(result);    // 6
  var m = new Calc(5,85);
  m.minus(); //-80

  //簡單json序列化

  //官方↓↓↓↓↓↓↓
  //JSON.decode()僅返回一個Map<String, dynamic>,這意味著我們直到運行時才知道值的類型。
  // 通過這種方法,我們失去了大部分靜態(tài)類型語言特性:類型安全、自動補全和最重要的編譯時異常。
  // 這樣一來,我們的代碼可能會變得非常容易出錯

  //簡而言之 就像js處理數(shù)據(jù)一樣不夠嚴謹 沒有數(shù)據(jù)類型  TS就是為了解決這個問題
    var json1 = '''
        {
          "name": "John Smith",
          "email": "john@example.com"
        }
    ''';
    Map<String,dynamic> jsonp1 = json.decode(json1);
    assert(jsonp1 is Map);
    print("hello,${jsonp1["name"]}");   //hello,John Smith
    print("email,${jsonp1["email"]}");  //email,john@example.com

  //  模型類中序列化JSON

  var json2 = '''
        {
          "name": "John2 Smith",
          "email": "john2@example.com"
        }
    ''';
  Map userMap = json.decode(json2);
  var jsonp2 = new Jsonp2.fromJson(userMap);
    print("hello,${jsonp2.name}");    //hello,John2 Smith
    print("email,${jsonp2.email}");   //email,john2@example.com

  //  ---------------------------------
  var url = 'https://douban.uieee.com/v2/movie/top250?start=${start}&count=${count}';
  var response = await http.get(url);
  print('Response status: ${response.statusCode}');   //Response status: 200
  //  print('Response body: ${response.body}');
  var encoded = json.decode(response.body.toString());//json解析  轉(zhuǎn)對象 需引入 'dart:convert';
  print(encoded);   //打印數(shù)據(jù)
  print(await http.read('https://www.baidu.com')); //返回百度 html格式
  //  ------------------------------------

  //  引入了math庫
  math.loadLibrary(); //用于延時加載 使用時  告知需加載  按需加載
  var random = new math.Random();
  print(random.nextInt(10));

}
//json解析成實例對象

class Jsonp2 {
  final String name;
  final String email;
  Jsonp2(this.name,this.email);
  Jsonp2.fromJson(Map<String,dynamic> json):name = json["name"],email = json["email"];
  Map<String,dynamic> toJson()=>{
    'name':name,
    'email':email
  };
}

6) 異步

因為Dart是單線程,所以代碼在運行線程中阻塞的話,會使程序凍結,在Dart中Future表示異步操作的結果,異步操作可以允許程序在等待操作完成期間可以去完成其他工作。
最基本的異步表現(xiàn):

void main(){
  print('say hello');
  Future.delayed(new Duration(seconds: 5),(){
    print('吃飽了--這是異步');
  });
  print('play game');
  /*
    say hello
    play game
    //5秒后↓
    吃飽了--這是異步
  */
}

異步操作 同步調(diào)用 async...await

 void main() async {
  print('say hello');
  await Future.delayed(new Duration(seconds: 5),(){
    print('吃飽了--這是異步,但同步調(diào)用');
  });
  print('play game');
  Future.wait([
    //異步  程序同時進行
    Future.delayed(new Duration(seconds: 1),(){
      print('異步001');
    }),
    Future.delayed(new Duration(seconds: 2),(){
     print('異步002');
    }),
    Future.delayed(new Duration(seconds: 5),(){
     print('異步003');
    }),
    Future.delayed(new Duration(seconds: 4),(){
     print('異步004');
    }),
  ]).then((List result){  //then 同js中then  await +異步 執(zhí)行結束后 執(zhí)行
            //    在async函數(shù)中使用try-catch來捕獲異常(或者使用catchError())
    print('異步all over');
  });
    //  要想同時運行代碼,就要為一個web app或者一個worker創(chuàng)建一個isolate
   //所有Dart代碼都在一個擁有Dart代碼使用的所有內(nèi)存的isolate上下文中運行。Dart代碼在運行的時候,在同一隔離中的其他代碼不能運行。
   //如果你希望Dart代碼的多個部分同時運行,你可以將它們在不同的isolate中運行(Weba pps使用workers代替isolates)。多個isolate同時運行,通常是各自運行在各自的CPU上。isolate不共享內(nèi)存,它們可以交互的唯一方式就是互相發(fā)送消息。

  //同步寫法  此時 時間需累加 時間變長
  await Future.delayed(new Duration(seconds: 1),(){
    print('005');
  });
   await Future.delayed(new Duration(seconds: 2),(){
   print('006');
   });
   await Future.delayed(new Duration(seconds: 5),(){
   print('007');
   });
   await Future.delayed(new Duration(seconds: 4),(){
   print('008');
   });

   /*
      say hello
      吃飽了--這是異步,但同步調(diào)用
      play game
      異步001
      005
      異步002
      006
      異步004
      異步003
      異步all over
      007
      008
  */
}

太長啦,還不支持錨點,所以拆成三篇

參考

簡書: dart--future
Flutter中文網(wǎng)--json序列化

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容