<address id="r9vd9"><address id="r9vd9"><listing id="r9vd9"></listing></address></address>

      歡迎您光臨深圳塔燈網絡科技有限公司!
      電話圖標 余先生:13699882642

      網站百科

      為您解碼網站建設的點點滴滴

      Flutter初步探索(四)網絡連接

      發表日期:2018-12 文章編輯:小燈 瀏覽次數:3616

      Dart和Flutter提供了工具來完成訪問網絡連接的工作。

      一、指引

      1. 添加http
      2. 使用http包來生成網絡請求
      3. 轉換response到一個Dart對象
      4. 使用Flutter展示數據

      1. 添加http

      http 提供了最簡單的房還是來訪問網絡的數據。
      安裝http包,我們需要pubspec.yaml增加依賴。我們 可以在[pub website]找到最新的版本來安裝(https://pub.dartlang.org/packages/http#-installing-tab-).

      dependencies: http: <latest_version>

      2. 使用http包來生成網絡請求

      在這個例子里,我們使用在JSONPlaceholder REST API里面的 http.get()來發送一個請求。

      Future<http.Response> fetchPost() { return http.get('https://jsonplaceholder.typicode.com/posts/1'); }

      http.get()方法返回包含Response的一個Future

      • Future是Dart類的一個核心同步操作。它用于表示將來某個時候可用的潛在值或錯誤。

      • http.Response 類包含從成功的http調用接收的數據。

      3. 轉換response到一個Dart對象

      雖然很容易發送一個網絡請求,但是使用原始的Future<http.Response>并不是很便。為了讓我們的更容易處理,可以將http.Response轉換為我們自己的Dart對象。

      創建一個Post

      首先,我們需要創建一個包含來自網絡請求的數據的Post類。它還將包括一個工廠構造器,允許我們從json創建Post。

      手動轉換JSON只是其中一個選擇。有關更多信息,請參閱關于JSON和序列化。

      class Post { final int userId; final int id; final String title; final String body;Post({this.userId, this.id, this.title, this.body});factory Post.fromJson(Map<String, dynamic> json) { return Post( userId: json['userId'], id: json['id'], title: json['title'], body: json['body'], ); } }

      http.Response轉換為Post

      現在,我們將更新fetchPost函數以返回<Post>。為此,我們需要:

      1.將響應主體轉換為帶有dart包的jsonMap。
      2.如果服務器返回狀態碼為200的"OK"響應,則使用fromJson工廠將jsonMap轉換為Post。
      3.如果服務器返回意外響應,則拋出錯誤

      Future<Post> fetchPost() async { final response = await http.get('https://jsonplaceholder.typicode.com/posts/1');if (response.statusCode == 200) { // If server returns an OK response, parse the JSON return Post.fromJson(json.decode(response.body)); } else { // If that response was not OK, throw an error. throw Exception('Failed to load post'); } }

      萬歲!現在我們有了一個函數,我們可以調用它來從互聯網上獲取一篇文章!

      4. 使用Flutter展示數據

      為了使獲取的數據可以在屏幕上顯示,我們使用FutureBuilder控件。FutureBuilder 控件附帶了Flutter,使得使用異步數據源變得容易。

      我們必須提供兩個參數:
      1.在這個例子中,我們將調用Futrue中的fetchPost()函數

      1. 一個builder函數,告訴Flutter要呈現什么,這取決于Future的狀態:加載、成功或錯誤。
      FutureBuilder<Post>( future: fetchPost(), builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data.title); } else if (snapshot.hasError) { return Text("${snapshot.error}"); }// By default, show a loading spinner return CircularProgressIndicator(); }, );

      5.將獲取調用移出“build()”方法

      盡管很方便,但是不建議在build()方法中調用API。

      每當Flutter想要更改視圖中的任何內容時,它都會調用build()方法,而這種情況經常出人意料地發生。如果在`build()'方法中留下fetch調用,則API中將充斥著不必要的調用,并減慢應用程序的速度。

      以下是一些更好的選擇,因此它只會在頁面最初加載時命中API。

      將其傳遞到StatelessWidget

      使用這個策略,父小部件負責調用fetch方法,存儲其結果,然后將其傳遞給小部件。

      class MyApp extends StatelessWidget { final Future<Post> post;MyApp({Key key, this.post}) : super(key: key);

      您可以在下面的完整示例中看到這個示例的工作示例。

      StatefulWidget狀態的生命周期中調用它

      如果您的小部件是有狀態的,您可以在initState'](https://docs.flutter.io/flutter/widgets/State/initState.html)或[didChangeDependencies'方法中調用獲取方法。

      initstate被調用一次,然后再也不會調用。如果您想選擇重新加載API以響應[inheritedWidget](https://docs.flutter.io/flutter/widgets/inheritedWidget class.html)更改,請將調用放入didchangeDependencies方法。更多詳情請參見[state](https://docs.flutter.io/flutter/widgets/state class.html)。

      class _MyAppState extends State<MyApp> { Future<Post> post;@override void initState() { super.initState(); post = fetchPost(); }

      測試

      有關如何測試此功能的信息,請參閱以下文章:

      • Introduction to unit testing
      • Mock dependencies using Mockito

      完整例子

      import 'dart:async'; import 'dart:convert';import 'package:flutter/material.dart'; import 'package:http/http.dart' as http;Future<Post> fetchPost() async { final response = await http.get('https://jsonplaceholder.typicode.com/posts/1');if (response.statusCode == 200) { // If the call to the server was successful, parse the JSON return Post.fromJson(json.decode(response.body)); } else { // If that call was not successful, throw an error. throw Exception('Failed to load post'); } }class Post { final int userId; final int id; final String title; final String body;Post({this.userId, this.id, this.title, this.body});factory Post.fromJson(Map<String, dynamic> json) { return Post( userId: json['userId'], id: json['id'], title: json['title'], body: json['body'], ); } }void main() => runApp(MyApp(post: fetchPost()));class MyApp extends StatelessWidget { final Future<Post> post;MyApp({Key key, this.post}) : super(key: key);@override Widget build(BuildContext context) { return MaterialApp( title: 'Fetch Data Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('Fetch Data Example'), ), body: Center( child: FutureBuilder<Post>( future: post, builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data.title); } else if (snapshot.hasError) { return Text("${snapshot.error}"); }// By default, show a loading spinner return CircularProgressIndicator(); }, ), ), ), ); } } 

      二、效果圖

      三、原文鏈接

      1.Flutter初步探索(四)網絡連接

      四、參考文檔

      1.Fetch data from the internet

      五、公眾號

      不器猿
      本頁內容由塔燈網絡科技有限公司通過網絡收集編輯所得,所有資料僅供用戶學習參考,本站不擁有所有權,如您認為本網頁中由涉嫌抄襲的內容,請及時與我們聯系,并提供相關證據,工作人員會在5工作日內聯系您,一經查實,本站立刻刪除侵權內容。本文鏈接:http://www.webpost.com.cn/18046.html
      相關APP開發
       八年  行業經驗

      多一份參考,總有益處

      聯系深圳網站公司塔燈網絡,免費獲得網站建設方案及報價

      咨詢相關問題或預約面談,可以通過以下方式與我們聯系

      業務熱線:余經理:13699882642

      Copyright ? 2013-2018 Tadeng NetWork Technology Co., LTD. All Rights Reserved.    

      国产成人精品综合在线观看