每日筆記

前言

今天有以下幾個主題:

  1. Networking & http
  2. JSON & serialization

Networking & http

  1. 使用 http package
  2. Future is a core Dart class for working with async operations. A Future object represents a potential value or error that will be available at some time in the future.
  3. The http.Response class contains the data received from a successful http call.
  4.  “If this work takes more than 16 milliseconds, your users experience jank.”
    這句話體現了使用者體驗的重要性,而開發過程注重效能是為了避免使用者體驗 jank。
  5. 因此,運算量大、負擔較重的部分應該要放到 background 去處理,以免造成使用者體驗下降。
  6.  以前有了解過 http request,那現在先大致分為 statusCode, header, body 去處理應該就夠了。
  7. .cast() 方法用於將 List 的元素類型轉換為指定的類型。在這裡,它將解析後的 JSON 數據中的每個元素都轉換為 Map<String, dynamic> 類型。這樣做是為了確保 List 中的每個元素都是一個鍵值對(key-value pair)的映射,其中鍵(key)是字符串,值(value)可以是任何動態(dynamic)類型。
  8. .map() 可以想成是 for item in items, 而會有一個函數針對 item 做處理,最終所有處理完的 item 會變成一個 Iterable 類別的東西,所以要用toList() function 把它們裝進一個 List 裡。
  9. 這邊做補充,cast() function 回傳的東西其實是 Iterable 類別。如果對於 Iterable 類別不清楚,先搞清楚有助於了解與其相關的操作。包括 map, cast, toList 都是如此。
  10. parsed.map<Photo>((json) => Photo.fromJson(json)).toList(); 就是先對parsed 裡的每個東西做迭代處理(.map<Photo>((json) => Photo.fromJson(json))),然後再把處理完的東西轉變成 List(.toList()),而因為有宣告 map<Photo>,因此迭代出來的元素會是Photo 型別(類別),轉成 List 後,List 內的東西也是 Photo 類別。
  1. serialization 的意思:
    Encoding and serialization are the same thing—turning a data structure into a string. Decoding and deserialization are the opposite process—turning a string into a data structure. However, serialization also commonly refers to the entire process of translating data structures to and from a more easily readable format.
  2.  官方提供了兩種方法可以處理 JSON:
    〉Manual serialization
    〉Automated serialization using code generation

Leave a Comment

Your email address will not be published. Required fields are marked *