亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

flutter中的網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)獲取詳解

 更新時(shí)間:2023年01月11日 10:11:02   作者:前端那些年  
這篇文章主要為大家介紹了flutter中的網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)獲取示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

跨平臺(tái)的http請(qǐng)求

http包提供了最簡(jiǎn)單的發(fā)起請(qǐng)求的方式,并且這個(gè)包在WEB,ANDROID,IOS上都得到了很好的支持。

需要注意的是,在某些特定的平臺(tái)上需要設(shè)置一些額外的內(nèi)容,比如:

ANDROID上必須在manifest(AndroidManifest.xml)文件中進(jìn)行聲明。

<manifest xmlns:android...>
 ...
 <uses-permission android:name="android.permission.INTERNET" />
 <application ...
</manifest>

macOS上必須在.entitlements進(jìn)行配置。

<key>com.apple.security.network.client</key>
<true/>

請(qǐng)求數(shù)據(jù)

從網(wǎng)絡(luò)上請(qǐng)求數(shù)據(jù)大致分為四步:

  • 添加http
  • 通過(guò)http包發(fā)起請(qǐng)求
  • 將收到的響應(yīng)數(shù)據(jù)轉(zhuǎn)為客戶端可用的數(shù)據(jù)
  • 展示用戶界面

添加http包

我們只需要在pub.dev文件中添加配置即可:

dependencies:
  http: <latest_version>

然后在代碼中導(dǎo)入http包:

import 'package:http/http.dart' as http;

另外,在安卓中我們需要添加網(wǎng)絡(luò)權(quán)限:

<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />

發(fā)起請(qǐng)求

發(fā)起請(qǐng)求很簡(jiǎn)單:

Future<http.Response> fetchAlbum() {
  return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}

http.get()方法返回一個(gè)Future類的數(shù)據(jù),這個(gè)數(shù)據(jù)包含了收到的響應(yīng)數(shù)據(jù)。 Future是用于處理異步操作的核心Dart類。Future對(duì)象表示將來(lái)某個(gè)時(shí)間可能出現(xiàn)的值或錯(cuò)誤。 http.Response類包含從成功的http調(diào)用接收的數(shù)據(jù)。

將響應(yīng)轉(zhuǎn)為常用對(duì)象

雖然發(fā)出網(wǎng)絡(luò)請(qǐng)求很容易,但使用原始的Future<http.Response>并不是很方便。為了讓我們的開發(fā)更簡(jiǎn)單,我們可以將http.Response轉(zhuǎn)換為Dart對(duì)象。

首先,創(chuàng)建一個(gè)包含網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)的Album類。它包括一個(gè)工廠構(gòu)造函數(shù),用于從JSON創(chuàng)建Album。

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

然后,我們使用以下步驟更新fetchAlbum()函數(shù)以返回Future<Album>

  • 使用dart:Convert包將響應(yīng)體轉(zhuǎn)換為JSON映射。
  • 如果服務(wù)器確實(shí)返回了狀態(tài)代碼為200的OK響應(yīng),則使用fromJson()工廠方法將JSON映射轉(zhuǎn)換為Album
  • 如果服務(wù)器沒(méi)有返回狀態(tài)代碼為200的OK響應(yīng),則拋出異常。(即使在“404 Not Found”服務(wù)器響應(yīng)的情況下,也會(huì)拋出異常。不要返回null。這在檢查快照中的數(shù)據(jù)時(shí)很重要,如下所示。)
Future<Album> fetchAlbum() async {
  final response = await http
      .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

獲取數(shù)據(jù)

我們可以在initState()didChangeDependencies()方法中調(diào)用fetchAlbum()方法。

initState()方法只調(diào)用一次,然后再也不會(huì)調(diào)用。如果我們想選擇重新加載API以響應(yīng)InheritedWidget的更改,我們可以將調(diào)用放入didChangeDependencies()方法中。

class _MyAppState extends State<MyApp> {
  late Future<Album> futureAlbum;
  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }
  // ···
}

展示數(shù)據(jù)

要在屏幕上顯示數(shù)據(jù),我們可以使用FutureBuilder組件。FutureBuilder組件隨Flutter一起提供,可以輕松處理異步數(shù)據(jù)源。

我們需要提供兩個(gè)參數(shù):

  • 具體的Future
  • builder方法,用來(lái)告訴系統(tǒng)渲染什么內(nèi)容,根據(jù)狀態(tài)可以選擇加載中等等。
FutureBuilder<Album>(
  future: futureAlbum,
  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 const CircularProgressIndicator();
  },
)

為什么要在initstate中獲取數(shù)據(jù)?

雖然在build()中調(diào)用很方便,但不建議將API調(diào)用放在build()方法中。

Flutter每次需要更改視圖中的任何內(nèi)容時(shí)都會(huì)調(diào)用build()方法,這種情況經(jīng)常發(fā)生。如果將fetchAlbum()方法放置在build()中,則會(huì)在每次重建時(shí)重復(fù)調(diào)用,導(dǎo)致應(yīng)用程序速度減慢。

以上就是flutter中的網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)獲取詳解的詳細(xì)內(nèi)容,更多關(guān)于flutter網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)獲取的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論