Flutter / Examples / Api Integration
API integration
-
Steps
STEP 1: Add http dependencies
Open pubspec.yaml file and add the below lines of code
dependencies: http: ^0.12.0+4 //add this line STEP 2: install http dependencies
'Get dependencies' is shown in the Adroid studio window. Click on it to install new dependencies
STEP 3: import http in the dart file
import 'package:http/http.dart' as http; STEP 4: create StatefulWidget
class PeoplePage extends StatefulWidget { @override createState() => _ApiDataState(); } STEP 5: define State()
class _ApiDataState extends State { } STEP 6:Define the state variables
String data=''; var superheros_length; STEP 7:initialize the state
@override void initState() { // TODO: implement initState getData(); } STEP 8:Set state()
setState(() { superheros_length = jsonDecode( data)['superheros']; //get all the data from json string superheros print(superheros_length.length); // just printed length of data }); STEP 9: call the variable in UI
Complete code is giventitle: Text(jsonDecode(data)['superheros'][index]['name']), subtitle: Text(jsonDecode(data)['superheros'][index]['power']), import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; class PeoplePage extends StatefulWidget { @override createState() => _ApiDataState(); } class _ApiDataState extends State { String data=''; var superheros_length; @override void initState() { // TODO: implement initState getData(); } void getData() async { http.Response response = await http.get(Uri.parse("https://protocoderspoint.com/jsondata/superheros.json")); if (response.statusCode == 200) { data = response.body; setState(() { superheros_length = jsonDecode( data)['superheros']; //get all the data from json string superheros print(superheros_length.length); // just printed length of data }); var venam = jsonDecode(data)['superheros'][4]['url']; print(venam); } else { print(response.statusCode); } } @override Widget build(BuildContext context) => Scaffold( //drawer: NavigationDrawerWidget(), appBar: AppBar( title: Text('People'), centerTitle: true, backgroundColor: Colors.green, ), body: ListView.builder( itemCount: superheros_length == null ? 0 : superheros_length.length, itemBuilder: (BuildContext context, int index) { return Card( child: ListTile( leading: Image.network( jsonDecode(data)['superheros'][index]['url'], fit: BoxFit.fill, width: 100, height: 500, alignment: Alignment.center, ), title: Text(jsonDecode(data)['superheros'][index]['name']), subtitle: Text(jsonDecode(data)['superheros'][index]['power']), ), ); }, ), ); }