Step By Step Implementation
Step 1: Add the Dio package in pubspec.yaml file and import it
dio: ^5.4.0
Step 2: Make a GET request using the Dio package
For this, we have created a function called getData()
Calling the function in the initState()
`var jsonList;
@override
void initState() {
getData();
}
void getData() async {
try {
var response = await Dio()
.get('https://protocoderspoint.com/jsondata/superheros.json');
if (response.statusCode == 200) {
setState(() {
jsonList = response.data['superheros'] as List;
});
} else {
print(response.statusCode);
}
} catch (e) {
print(e);
}
} `
Step 3: To show data on the screen that is coming from an API
body: ListView.builder(
itemCount: jsonList == null ? 0 : jsonList.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: ListTile(
leading: ClipRRect(
borderRadius: BorderRadius.circular(80),
child: Image.network(
jsonList[index]['url'],
fit: BoxFit.fill,
width: 50,
height: 50,
),
),
title: Text(jsonList[index]['name']),
subtitle: Text(jsonList[index]['power']),
));
}),
Complate code
`import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var jsonList;
@override
void initState() {
getData();
}
void getData() async {
try {
var response = await Dio()
.get('https://protocoderspoint.com/jsondata/superheros.json');
if (response.statusCode == 200) {
setState(() {
jsonList = response.data['superheros'] as List;
});
} else {
print(response.statusCode);
}
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'GeeksForGeeks',
style: TextStyle(color: Colors.white),
),
centerTitle: true,
),
body: ListView.builder(
itemCount: jsonList == null ? 0 : jsonList.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: ListTile(
leading: ClipRRect(
borderRadius: BorderRadius.circular(80),
child: Image.network(
jsonList[index]['url'],
fit: BoxFit.fill,
width: 50,
height: 50,
),
),
title: Text(jsonList[index]['name']),
subtitle: Text(jsonList[index]['power']),
));
}),
);
}
}
`