国产精品主播叶子闺蜜_三级高清精品国产_99久久精品国产麻豆_国产精品无码免费专区午夜

歡迎您光臨深圳塔燈網(wǎng)絡(luò)科技有限公司!
電話圖標(biāo) 余先生:13699882642

網(wǎng)站百科

為您解碼網(wǎng)站建設(shè)的點點滴滴

Flutter初步探索(四)網(wǎng)絡(luò)連接

發(fā)表日期:2018-12 文章編輯:小燈 瀏覽次數(shù):3895

Dart和Flutter提供了工具來完成訪問網(wǎng)絡(luò)連接的工作。

一、指引

  1. 添加http
  2. 使用http包來生成網(wǎng)絡(luò)請求
  3. 轉(zhuǎn)換response到一個Dart對象
  4. 使用Flutter展示數(shù)據(jù)

1. 添加http

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

dependencies: http: <latest_version>

2. 使用http包來生成網(wǎng)絡(luò)請求

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

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

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

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

  • http.Response 類包含從成功的http調(diào)用接收的數(shù)據(jù)。

3. 轉(zhuǎn)換response到一個Dart對象

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

創(chuàng)建一個Post

首先,我們需要創(chuàng)建一個包含來自網(wǎng)絡(luò)請求的數(shù)據(jù)的Post類。它還將包括一個工廠構(gòu)造器,允許我們從json創(chuàng)建Post

手動轉(zhuǎn)換JSON只是其中一個選擇。有關(guān)更多信息,請參閱關(guān)于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轉(zhuǎn)換為Post

現(xiàn)在,我們將更新fetchPost函數(shù)以返回<Post>。為此,我們需要:

1.將響應(yīng)主體轉(zhuǎn)換為帶有dart包的jsonMap
2.如果服務(wù)器返回狀態(tài)碼為200的"OK"響應(yīng),則使用fromJson工廠將jsonMap轉(zhuǎn)換為Post
3.如果服務(wù)器返回意外響應(yīng),則拋出錯誤

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'); } }

萬歲!現(xiàn)在我們有了一個函數(shù),我們可以調(diào)用它來從互聯(lián)網(wǎng)上獲取一篇文章!

4. 使用Flutter展示數(shù)據(jù)

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

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

  1. 一個builder函數(shù),告訴Flutter要呈現(xiàn)什么,這取決于Future的狀態(tài):加載、成功或錯誤。
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.將獲取調(diào)用移出“build()”方法

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

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

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

將其傳遞到StatelessWidget

使用這個策略,父小部件負(fù)責(zé)調(diào)用fetch方法,存儲其結(jié)果,然后將其傳遞給小部件。

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

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

StatefulWidget狀態(tài)的生命周期中調(diào)用它

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

initstate被調(diào)用一次,然后再也不會調(diào)用。如果您想選擇重新加載API以響應(yīng)[inheritedWidget](https://docs.flutter.io/flutter/widgets/inheritedWidget class.html)更改,請將調(diào)用放入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(); }

測試

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

  • 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初步探索(四)網(wǎng)絡(luò)連接

四、參考文檔

1.Fetch data from the internet

五、公眾號

不器猿
本頁內(nèi)容由塔燈網(wǎng)絡(luò)科技有限公司通過網(wǎng)絡(luò)收集編輯所得,所有資料僅供用戶學(xué)習(xí)參考,本站不擁有所有權(quán),如您認(rèn)為本網(wǎng)頁中由涉嫌抄襲的內(nèi)容,請及時與我們聯(lián)系,并提供相關(guān)證據(jù),工作人員會在5工作日內(nèi)聯(lián)系您,一經(jīng)查實,本站立刻刪除侵權(quán)內(nèi)容。本文鏈接:http://www.juherenli.com/18046.html
相關(guān)APP開發(fā)