flutter调用api_如何在Flutter(REST API)中进行API调用
flutter調(diào)用api
在本文中,我們將看一下如何快速進(jìn)行API調(diào)用并使用簡單的REST API。
在這里查看我在Flutter上的其他一些帖子:
- Flutter vs React Native
- 了解Flutter中的BLoC架構(gòu) (強烈建議)
- 在Flutter中構(gòu)建ListView(RecyclerView) (推薦)
我們將創(chuàng)建一個簡單的應(yīng)用程序,在其中我將對以下網(wǎng)址進(jìn)行API調(diào)用: https : //jsonplaceholder.typicode.com/posts并在列表中打印出標(biāo)題。
這將演示如何在flutter中進(jìn)行API調(diào)用以及如何使用convert包解碼json 。 所以,讓我們開始吧。
首先,在Android Studio中創(chuàng)建一個新的flutter項目,并根據(jù)需要命名。
我將其命名為: flutter_api_calls 。
接下來,清除您獲得的所有樣板代碼。 我們將從頭開始編寫所有內(nèi)容。
接下來,我將設(shè)置項目的框架。 這意味著添加一個AppBar,一個腳手架并編寫主要功能。
看起來像這樣
import 'package:flutter/material.dart' ; void main() => runApp(MyApp()); MyApp class extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo' , theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Api Call' ), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this .title}) : super (key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { ??@override Widget build(BuildContext context) { return null ; } ?? }首先,我們需要在pubspec.yaml文件中包含http包。 在依賴項下添加此行,該行將顯示fld sdk。 這是您的pubspec.yaml的樣子:
name: flutter_api_calls description: Flutter application to demonstrate api calls. # The following defines the version and build number for your application. # A version number is three numbers separated by dots, like 1.2 . 43 # followed by an optional build number separated by a +. # Both the version and the builder number may be overridden in flutter # build by specifying --build-name and --build-number, respectively. # In Android, build-name is used as versionName while build-number used as versionCode. # Read more about Android versioning at https: //developer.android.com/studio/publish/versioning # In iOS, build-name is used as CFBundleShortVersionString build-number used as CFBundleVersion. # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # Read more about iOS versioning at # https: //developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html version: 1.0 . 0 + 1 environment: sdk: ">=2.1.0 <3.0.0" dependencies: flutter: sdk: flutter http: ^ 0.12 . 0 # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^ 0.1 . 2 dev_dependencies: flutter_test: sdk: flutter現(xiàn)在,將http包導(dǎo)入到您的main.dart文件中:
import 'package:http/http.dart' as http;讓我們創(chuàng)建一個函數(shù)getData(),該函數(shù)將從API中獲取數(shù)據(jù)。
Future<String> getData() { }我們將進(jìn)行API調(diào)用,這可能需要一些時間才能返回響應(yīng)。 這種情況需要異步編程。
基本上,我們需要等到api調(diào)用完成并返回結(jié)果。 一旦完成,我們將顯示列表。
所以,這就是我們要做的。 我們將使用http對象進(jìn)行api調(diào)用,并等待其完成。
Future<String> getData() async { var response = await http.get( Uri.encodeFull( " https://jsonplaceholder.typicode.com/posts " ), headers: { "Accept" : "application/json" }); setState(() { data = json.decode(response.body); }); return "Success" ; }要在函數(shù)中使用await關(guān)鍵字,我們需要將函數(shù)標(biāo)記為異步。 并且任何異步函數(shù)都具有Future <T>的返回類型,其中T可以為void,int,string等。
為了解碼數(shù)據(jù),我們使用:
import 'dart:convert' ;它為我們提供了json.decode()方法,該方法可用于反序列化JSON 。 解碼數(shù)據(jù)后,我們將通知視圖層次結(jié)構(gòu)該數(shù)據(jù)可用,并且可以將其填充到listview中。
這是代碼的真正內(nèi)容。 現(xiàn)在,我們需要向flutter應(yīng)用程序添加一個列表視圖 。
接下來,我們將在flutter應(yīng)用程序中添加一個listview。 如果您不知道如何在flutter中創(chuàng)建列表視圖,請快速閱讀我的另一篇文章:
- 閱讀: 在Flutter中構(gòu)建ListView(RecyclerView)
讓我們創(chuàng)建一個函數(shù)getList(), 如果獲取數(shù)據(jù) ,它將返回List; 如果響應(yīng)尚未到達(dá), 則返回“ please wait”消息。
Widget getList() { if (data == null || data.length < 1 ) { return Container( child: Center( child: Text( "Please wait..." ), ), ); } return ListView.separated( itemCount: data?.length, itemBuilder: (BuildContext context, int index) { return getListItem(index); }, separatorBuilder: (context, index) { return Divider(); }, ); }請注意,我們使用的是ListView.separated而不是普通的ListView.builder 。 原因是此列表視圖已內(nèi)置對分隔項的支持。 我們不需要顯式檢查索引。
為此構(gòu)建列表項非常簡單。 只需創(chuàng)建一個文本小部件并為其添加一些樣式即可。
Widget getListItem( int i) { if (data == null || data.length < 1 ) return null ; if (i == 0 ) { return Container( margin: EdgeInsets.all( 4 ), child: Center( child: Text( "Titles" , style: TextStyle( fontSize: 22 , fontWeight: FontWeight.bold, ), ), ), ); } return Container( child: Container( margin: EdgeInsets.all( 4.0 ), child: Padding( padding: EdgeInsets.all( 4 ), child: Text( data[i][ 'title' ].toString(), style: TextStyle(fontSize: 18 ), ), ), ), ); }您可以在github上找到完整的代碼:https://github.com/Ayusch/flutter-api-calls
這是一個非常簡單快捷的示例,說明如何開始在flutter中進(jìn)行API調(diào)用。 盡管我建議為您的應(yīng)用程序遵循適當(dāng)?shù)捏w系結(jié)構(gòu),但不要將所有代碼都寫在一個地方。
BLoC抖動架構(gòu)非常強大。 在此處查看: Flutter中的BLoC體系結(jié)構(gòu) 。 這將使您深入了解如何為Flutter應(yīng)用程序編寫健壯的BLoC架構(gòu) 。
*重要* :加入面向移動開發(fā)人員的AndroidVille SLACK工作區(qū),人們可以在這里分享對最新技術(shù)的了解,尤其是在Android開發(fā),RxJava,Kotlin,Flutter和一般的移動開發(fā)方面 。
翻譯自: https://www.javacodegeeks.com/2019/09/how-to-make-an-api-call-in-flutter-rest-api.html
flutter調(diào)用api
總結(jié)
以上是生活随笔為你收集整理的flutter调用api_如何在Flutter(REST API)中进行API调用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: posman mocks_使用Mocks
- 下一篇: 乐视视频电脑版6.8官方(乐视视频官方免