API Calling with HTTP Library (Second API)
import "dart:convert";
import "package:api_integration_http/First_Api_Integration/First_Model_Class.dart";
import "package:flutter/material.dart";
import "package:http/http.dart" as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "First Api practice",
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.grey,
centerTitle: true,
),
),
home: const FirstApiPractice(),
);
}
}
class FirstApiPractice extends StatefulWidget {
const FirstApiPractice({super.key});
@override
State<FirstApiPractice> createState() {
return FirstApiPracticeState();
}
}
class FirstApiPracticeState extends State<FirstApiPractice> {
List<FirstModel> futureFirstModel = [];
Future<List<FirstModel>> fetchFirstModel() async {
var response = await http.get(
Uri.parse("https://jsonplaceholder.typicode.com/posts"),
);
var data = jsonDecode(response.body.toString());
if (response.statusCode == 200) {
for (Map<String, dynamic> index in data) {
futureFirstModel.add(
FirstModel.fromJson(index),
);
}
return futureFirstModel;
} else {
return futureFirstModel;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"First Api Practice",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
body: Center(
child: FutureBuilder(
future: fetchFirstModel(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
final product = snapshot.data![index];
return Card(
child: ListTile(
title: Text(
product.title,
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(product.body),
trailing: Text(
"\$${product.id.toString()}",
style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0),
),
),
);
},
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return const Center(
child: CircularProgressIndicator(),
);
},
),
),
);
}
}
class FirstModel {
final int userId;
final int id;
final String title;
final String body;
FirstModel({
required this.userId,
required this.id,
required this.title,
required this.body,
});
factory FirstModel.fromJson(Map<String, dynamic> json) {
if (json.containsKey("userId") &&
json.containsKey("id") &&
json.containsKey("title") &&
json.containsKey("body")) {
return FirstModel(
userId: json["userId"],
id: json["id"],
title: json["title"],
body: json["body"],
);
}
else
{
throw const FormatException("Failed to load FirstModel");
}
}
}


Comments
Post a Comment