API Calling with HTTP Library (Fourth API)

 import "dart:convert";

import "package:api_integration_http/Second_Api_Integration/Second_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: "Second Api Calling",
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.grey,
centerTitle: true,
),
),
home: const SecondApi(),
);
}
}

class SecondApi extends StatefulWidget {
const SecondApi({super.key});

@override
State<SecondApi> createState() {
return SecondApiState();
}
}

class SecondApiState extends State<SecondApi> {
late Future<List<SecondModel>> futureSecondModel;

Future<List<SecondModel>> fetchSecondModel() async {
final response = await http.get(
Uri.parse("https://jsonplaceholder.typicode.com/posts"),
);

if (response.statusCode == 200) {
Iterable jsonResponse = json.decode(response.body);

List<SecondModel> dataInputs = jsonResponse.map(
(model) {
return SecondModel.fromJson(model);
},
).toList();
return dataInputs;
} else {
throw Exception("Failed to load data!");
}
}

@override
void initState() {
super.initState();
futureSecondModel = fetchSecondModel();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Second Api Calling",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
body: Center(
child: FutureBuilder<List<SecondModel>>(
future: futureSecondModel,
builder: (context, snapshot) {
if (snapshot.hasData) {
List<SecondModel>? data = snapshot.data;
return ListView.builder(
itemCount: data!.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(
data[index].title,
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(data[index].body),
trailing: Text(
data[index].id.toString(),
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
),
),
);
},
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return const CircularProgressIndicator();
},
),
),
);
}
}
class SecondModel {
final int userId;
final int id;
final String title;
final String body;

SecondModel(
{required this.userId,
required this.id,
required this.title,
required this.body});

factory SecondModel.fromJson(Map<String, dynamic> json) {
return switch (json) {
{
"userId": int userId,
"id": int id,
"title": String title,
"body": String body,
} =>
SecondModel(
userId: userId,
id: id,
title: title,
body: body,
),
_ => throw const FormatException("Failed to load SecondModel"),
};
}
}



Comments

Popular posts from this blog

Pagination with Bloc Pattern in Flutter

Pagination First Practical in Flutter

ExpansionPanel with ExpansionPanelList with Complete Collapse Operation in Flutter