import "dart:convert";
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: "Sixth API Calling with HTTP",
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.grey,
centerTitle: true,
),
),
home: const SixthApi(),
);
}
}
class SixthApi extends StatefulWidget {
const SixthApi({super.key});
@override
State<SixthApi> createState() => _SixthApiState();
}
class _SixthApiState extends State<SixthApi> {
@override
void initState() {
super.initState();
fetchSixthModel();
}
Future<List<SixthModel>> fetchSixthModel() async {
final response = await http.get(
Uri.parse("https://jsonplaceholder.typicode.com/albums"),
);
if (response.statusCode == 200) {
Iterable jsonResponse = jsonDecode(response.body);
List<SixthModel> dataInputs = jsonResponse.map(
(model) {
return SixthModel.fromJson(model);
},
).toList();
return dataInputs;
} else {
throw Exception("Failed to load SixthModel");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Sixth API Calling with HTTP",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
body: Center(
child: FutureBuilder<List<SixthModel>>(
future: fetchSixthModel(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List<SixthModel>? data = snapshot.data;
return ListView.builder(
itemCount: data!.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(
data[index].id.toString(),
style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0),
),
subtitle: Text(
data[index].title,
style: const TextStyle(fontWeight: FontWeight.bold),
),
trailing: Text(
data[index].userId.toString(),
style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0),
),
),
);
},
);
} else if (snapshot.hasError) {
return Text("Error : ${snapshot.error}");
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
),
);
}
}
/// Model Class
class SixthModel {
final int userId;
final int id;
final String title;
SixthModel({required this.userId, required this.id, required this.title});
factory SixthModel.fromJson(Map<String, dynamic> json) {
return SixthModel(
userId: json["userId"],
id: json["id"],
title: json["title"],
);
}
}


Comments
Post a Comment