API Calling with HTTP Library (Ninth API)
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: "Eighth API Calling with HTTP",
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.grey,
centerTitle: true,
),
),
home: const EighthApi(),
);
}
}
class EighthApi extends StatefulWidget {
const EighthApi({super.key});
@override
State<EighthApi> createState() {
return EighthApiState();
}
}
class EighthApiState extends State<EighthApi> {
@override
void initState() {
super.initState();
fetchEighthModel();
}
Future<List<EighthModel>> fetchEighthModel() async {
final response = await http.get(
Uri.parse("https://jsonplaceholder.typicode.com/todos"),
);
if (response.statusCode == 200) {
Iterable jsonResponse = jsonDecode(response.body);
List<EighthModel> dataInputs = jsonResponse.map(
(model) {
return EighthModel.fromJson(model);
},
).toList();
return dataInputs;
} else {
throw Exception("Failed to load EighthModel");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Eighth API with HTTP",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
body: Center(
child: FutureBuilder<List<EighthModel>>(
future: fetchEighthModel(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List<EighthModel>? 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: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Title : ${data[index].title}",
style: const TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 10.0),
Text("completed : ${data[index].completed}"),
],
),
trailing: Text(
data[index].userId.toString(),
style: const TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
),
);
},
);
} else if (snapshot.hasError) {
return Text("Error : ${snapshot.error}");
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
),
);
}
}
/// Model Class
class EighthModel {
final int userId;
final int id;
final String title;
final bool completed;
EighthModel({
required this.userId,
required this.id,
required this.title,
required this.completed,
});
factory EighthModel.fromJson(Map<String, dynamic> json) {
return EighthModel(
userId: json["userId"],
id: json["id"],
title: json["title"],
completed: json["completed"],
);
}
}


Comments
Post a Comment