You are on page 1of 3

MAD D22CE161

Using the given API link create an fake shop api


Fake Store API (button for add to cart, and buy now option)
https://fakestoreapi.com/

Code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fake Store',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: FakeStoreHomePage(),
);
}
}

class FakeStoreHomePage extends StatefulWidget {


@override
_FakeStoreHomePageState createState() => _FakeStoreHomePageState();
}

class _FakeStoreHomePageState extends State<FakeStoreHomePage> {

List products = [];

@override
void initState() {
super.initState();
fetchProducts();
}

fetchProducts() async {
var url = Uri.https('fakestoreapi.com', '/products');
var response = await http.get(url);
setState(() {
products = jsonDecode(response.body);
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Fake Store'),
),
body: ListView.builder(
itemCount: products.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
MAD D22CE161

padding: const EdgeInsets.all(8.0),


child: Container(
height: 100,
child: Row(
children: [
Image.network(products[index]['image']),
SizedBox(width: 10,),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
products[index]['title'],
style: TextStyle(fontWeight: FontWeight.bold),
),
SizedBox(height: 5,),
Text('\$${products[index]['price']}'),
],
),
),
ElevatedButton(
child: Text('Add to Cart'),
onPressed: () {
// Add to cart action
},
),
SizedBox(width: 10,),
ElevatedButton(
child: Text('Buy Now'),
onPressed: () {
// Buy now action
},
)
],
),
),
);
},
),
);
}
}
MAD D22CE161

OUTPUT:

You might also like