Skip to content

Instantly share code, notes, and snippets.

@yenru
Created March 27, 2019 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yenru/3a279e3528c1319cd919f7be432c4113 to your computer and use it in GitHub Desktop.
Save yenru/3a279e3528c1319cd919f7be432c4113 to your computer and use it in GitHub Desktop.
// 建立 Flutter Class
// 1、建構子
// 1-1、直接輸入參數值
Object(this.param1, this.param2);
Object obj = new Object(param1, param2);
// 1-2、以 key-value 的方式輸入參數值
Object({this.param1, this.param2});
Object obj = new Object('param1': param1, 'param2': param2);
// 2、常見的實作方法
// 2-1、從JSON轉成物件
Object.fromJson(Map<String, dynamic> json) {}
// 2-2、從物件轉成JSON
Map<String, dynamic> toJson() {}
/////////////////////////////////////////////////////////////
// Flutter JSON物件操作方法
// JSON字串轉Map物件
String jsonStr = '{"prog":["Flutter","Kotlin","Swift"]}';
Map<String, dynamic> jsonObj = json.decode(jsonStr);
// Map中的dynamic轉List<dynamic>(弱型別轉換)
List<dynamic> prog1 = jsonObj['prog'] as List;
List<dynamic> prog2 = jsonObj['prog'].toList();
// Map中的dynamic轉List<String>(強型別轉換)
List<String> prog = jsonObj['prog'].cast<String>();
// 變更List內容的型態
List<Widget> list = prog.map((name) => Text(name)).toList();
// 將List、Map或Set變更成Map結構
Map<String, String> map = new Map.fromIterable(prog, key: (e) => e['no'], value: (e) => e['exp']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment