Now a days every mobile application communicate with remote server on Networking
Flutter provides a sky_enginedevelopment kit in the Flutter engine , which contains a _http library that contains various operation classes related to encapsulated http requests. In this article, we will introduce _http the use of related operation classes and the use _httpof three-party dio network libraries based on encapsulation
The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers. HTTP works as a request-response protocol between a
client and server. A protocol describes how machines communicate with each other using messages. A protocol defines the format of these messages
http support is located dart:io, so to create an HTTP client, we need to add an import
import 'dart:io'; var httpClient = new HttpClient(); |
HTTP API uses Dart Futures in the return value . We recommend using the async/ await syntax to call the AP
Involve below steps to handle the HttpClient
Create client
Construct Uri
Make a request, wait for a request, and you can also configure request headers and body
Close the request and wait for a response
Decode the content of the response
get() async { var httpClient = new HttpClient(); var uri = new Uri.http( 'domain', 'path to api', params in map object); var request = await httpClient.getUrl(uri); var response = await request.close(); var responseBody = await response.transform(UTF8.decoder).join(); } |
The dart:convertlibrary makes it easy to decode and encode JSON.
Decode a simple JSON string and parse the response into a Map
Map data = JSON.decode(responseBody);
String name=mapNews[0]['name']
Check Example
class NetwotkHTTP extends StatefulWidget { NetwotkHTTP({Key key}) : super(key: key); @override _NetwotkHTTPState createState() => new _NetwotkHTTPState(); } class _NetwotkHTTPState extends State<NetwotkHTTP> { Map<int,dynamic>mapNews=Map(); @override void initState() { // TODO: implement initState super.initState(); _getNewsData(); } _getNewsData() async { var url='https://newsapi.org/v2/sources?apiKey=API_KEY&page=1'; //var url = 'https://httpbin.org/ip'; var httpClient = new HttpClient(); var listNewsdata=""; try { var request = await httpClient.getUrl(Uri.parse(url)); var response = await request.close(); if (response.statusCode == HttpStatus.OK) { var json = await response.transform(utf8.decoder).join(); var data = jsonDecode(json); List<dynamic>hm=data['sources'] as List; setState(() { mapNews=hm.asMap(); print("errorr SetState"+mapNews.toString()); }); } else { print("errorr "); listNewsdata = 'Error Resposne :\nHttp status ${response.statusCode}'; } } catch (exception) { print("errorr $exception"); listNewsdata = 'Failed getting News Data $exception'; } // If the widget was removed from the tree while the message was in flight, // we want to discard the reply rather than calling setState to update our // non-existent appearance. if (!mounted) return; } @override Widget build(BuildContext context) { var spacer = new SizedBox(height: 32.0); return new Scaffold( appBar: AppBar(title: Text("News API WITH HTTP CLIENT"),backgroundColor: Colors.pink,), body: SingleChildScrollView( child: new Center( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ (mapNews.length==0)?CircularProgressIndicator():Text(""), ListView.builder( shrinkWrap: true, primary: false, itemCount: mapNews.length, itemBuilder: (ctx,pos){ return Card( elevation: 5, child: Container( margin: EdgeInsets.all(5), padding: EdgeInsets.all(5), child: InkWell( onTap: (){}, child: Row( children: <Widget>[ Container( height: 50, width: 50, decoration: ShapeDecoration(shape: CircleBorder(),color: Colors.pink), child: Center(child: Text(mapNews[pos]['name'].substring(0,1).toUpperCase(),style: TextStyle(fontSize: 30,color: Colors.white),)), ), SizedBox(width:15,), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text(mapNews[pos]['name'],style: TextStyle(fontSize: 18,color: Colors.black),), SizedBox(height:5,), Text(mapNews[pos]['description'],style: TextStyle(fontSize: 12,color: Colors.grey[800]),maxLines: 3,), ], ), ) ], ), ), ) ); }) ], ), ), ), ); } } |
http Library http.dartfile package HttpClientclass is our common network requests the operation class, which is an abstract class, the specific operation by the http_impl.dart document _HttpClient class that implements the class encapsulates http request various methods, including get, post, put, delete, patchAnd head wait for the request
Let's look at the usage method through the following example
In this example using the NewsAPI to fetch the news headlines. News API is a simple HTTP REST API for searching and retrieving live articles from all over the web
To call api in Flutter we need to add http: ^0.12.0+2 dependencies in the pubspec.yaml file
The above same example with http library
static Future callNewsCAtegory() async{ var url="API_KEY"; return get('https://newsapi.org/v2/sources?apiKey=$url&page=1'); } |
The above method will return the response data, that we are handle in below code
fetchNews(){ var callNews = NewsCategoryModel.callNewsCAtegory(); callNews.then((data){ var response=json.decode(data.body ); print(response); var listNewsdata=response['sources']as List; setState(() { listNews=listNewsdata.map<NewsCategoryModel>((model)=>NewsCategoryModel.fromJson(model)).toList(); listNewsAll.clear(); listNewsAll.addAll(listNews); }); },onError: (error){ print("Result Error $error"); } ); } |
POST Method
Map<String, String> queryParameters = {'key': 'value', 'key': 'value'}; Map<String, String> header = {'key': 'value'}; post("API_URL",body: queryParameters,headers: header); |
JSON Parsing
After getting the response from the API we need to parse the data, for this we are using the import 'dart:convert' library
var callNews = NewsCategoryModel.callNewsCAtegory(); callNews.then((data){ var response=json.decode(data.body ); print(response); var listNewsdata=response['sources']as List Var listNews=listNewsdata.map<NewsCategoryModel>((model)=>NewsCategoryModel.fromJson(model)).toList(); |
The NewsCategoryModel class like below
class NewsCategoryModel { String id; String name; String description; String url; String category; String language; String country; NewsCategoryModel(this.id,this.name,this.description,this.url,this.category,this.language,this.country); NewsCategoryModel.fromJson(Map<String,dynamic>parseModel) { id=parseModel['id']; name=parseModel['name']; description=parseModel['description']; url=parseModel['url']; category=parseModel['category']; language=parseModel['language']; country=parseModel['country']; } static Future callNewsCAtegory() async{ var url="API_KEY"; return get('https://newsapi.org/v2/sources?apiKey=$url&page=1'); } } |
Flutter - ListVew - Search Filter - NewsApplication