API Calling with HTTP Library (Third 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: 'First API',
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.grey,
centerTitle: true,
),
),
home: const FirstApi(),
);
}
}

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

@override
State<FirstApi> createState() => _FirstApiState();
}

class _FirstApiState extends State<FirstApi> {
late Future<List<FirstModel>> futureFirstModels;

@override
void initState() {
super.initState();
futureFirstModels = fetchFirstModels();
}

Future<List<FirstModel>> fetchFirstModels() async {
final response = await http.get(
Uri.parse("https://fakestoreapi.com/products"),
);

if (response.statusCode == 200) {
final List<dynamic> data = jsonDecode(response.body);
final List<FirstModel> products = data
.map((json) => FirstModel.fromJson(json))
.toList(); // Convert JSON data to list of FirstModel
return products;
} else {
throw Exception("Failed to load FirstModels");
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"First Api Calling",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
body: Center(
child: FutureBuilder<List<FirstModel>>(
future: futureFirstModels,
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.description),
trailing: Text(
product.price.toString(),
style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 15.0),
),
),
);
},
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
);
}
}

class FirstModel {
final int id;
final String title;
final num price;
final String description;
final String category;
final Map<String, dynamic> rating;

FirstModel({
required this.id,
required this.title,
required this.price,
required this.description,
required this.category,
required this.rating,
});

factory FirstModel.fromJson(Map<String, dynamic> json) {
return FirstModel(
id: json['id'] as int,
title: json['title'] as String,
price: json["price"],
description: json['description'] as String,
category: json['category'] as String,
rating: json['rating'] as Map<String, dynamic>,
);
}
}



Comments

Popular posts from this blog

Second GET API Calling with Bloc simple Example in Flutter

Stack Container Scrollable Card widget UI with Custom Widget

Pagination with Bloc Pattern in Flutter