API Calling with Dio Library (Fifth API)
import "package:flutter/material.dart";
import "package:dio/dio.dart";
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Fifth API Calling with Dio",
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.grey,
centerTitle: true,
),
),
home: FifthDio(),
);
}
}
class FifthDio extends StatefulWidget {
const FifthDio({super.key});
@override
State<FifthDio> createState() {
return FifthDioState();
}
}
class FifthDioState extends State<FifthDio> {
var jsonlist = [];
@override
void initState() {
super.initState();
getData();
}
void getData() async {
try {
var response =
await Dio().get("https://jsonplaceholder.typicode.com/comments");
print(response);
if (response.statusCode == 200) {
setState(
() {
jsonlist = response.data as List;
},
);
} else {
print(response.statusCode);
}
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Fifth API Calling with Dio",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
body: ListView.builder(
itemCount: jsonlist == null ? 0 : jsonlist.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(
jsonlist[index]["id"].toString(),
style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Name : ${jsonlist[index]["name"]}",
style: const TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 10.0),
Text(
"Email : ${jsonlist[index]["email"]}",
style: const TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 10.0),
Text("Body: ${jsonlist[index]["body"]}"),
],
),
trailing: Text(
jsonlist[index]["postId"].toString(),
style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0),
),
),
);
},
),
);
}
}
Comments
Post a Comment