Skip to content

Common Error: SetState Called During Build- Error fixed,Error handling added in api call, code reformat #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,7 @@ Demp APK [Visit](https://github.com/om-chauhan/Super-Store-Ecommerce-App-using-R
## 👤 Authors

- [@om-chauhan](https://github.com/om-chauhan)

## 👤 Contributor

- [@jaygoswami](https://github.goswamijay)
3 changes: 2 additions & 1 deletion lib/const/raw_string.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ class RawString {
RawString._();
static String appName = 'Super Store';
static String appDescription = 'Flutter E-commerce App using REST API.';
static String gitHubRepo = 'https://github.com/om-chauhan/Super-Store-Ecommerce-App-using-REST-Api-in-Flutter';
static String gitHubRepo =
'https://github.com/om-chauhan/Super-Store-Ecommerce-App-using-REST-Api-in-Flutter';
static String emailId = '[email protected]';
static String dummyEmail = '[email protected]';
static String appLogoURL = 'https://ui-avatars.com/api/?name=Super+Store';
Expand Down
2 changes: 1 addition & 1 deletion lib/controller/cart_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class CartProvider with ChangeNotifier {
for (int i = 0; i < _items.length; i++) {
totalPrice += _items[i].totalPrice!;
}
notifyListeners();
// notifyListeners();
if (kDebugMode) {
print('Total Price: $totalPrice');
}
Expand Down
4 changes: 3 additions & 1 deletion lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<CartProvider>(create: (context) => CartProvider()),
ChangeNotifierProvider<CartProvider>(
create: (context) => CartProvider(),
),
],
child: MaterialApp(
title: RawString.appName,
Expand Down
6 changes: 4 additions & 2 deletions lib/model/product_model.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import 'dart:convert';

List<ProductModel> productModelFromJson(String str) => List<ProductModel>.from(json.decode(str).map((x) => ProductModel.fromJson(x)));
List<ProductModel> productModelFromJson(String str) => List<ProductModel>.from(
json.decode(str).map((x) => ProductModel.fromJson(x)));

String productModelToJson(List<ProductModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
String productModelToJson(List<ProductModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class ProductModel {
int? id;
Expand Down
3 changes: 2 additions & 1 deletion lib/utils/url_launch.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ class UrlLaunch {
await launchUrl(launchUri);
}

static Future makeEmail({String? email, String? subject, String? body}) async {
static Future makeEmail(
{String? email, String? subject, String? body}) async {
final Uri params = Uri(
scheme: 'mailto',
path: email,
Expand Down
20 changes: 15 additions & 5 deletions lib/view/cart/cart.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ class _CartState extends State<Cart> {
height: 25,
width: 25,
alignment: Alignment.center,
decoration: const BoxDecoration(shape: BoxShape.circle, color: Colors.black),
decoration: const BoxDecoration(
shape: BoxShape.circle, color: Colors.black),
child: TextBuilder(
text: cart.itemCount.toString(),
color: Colors.white,
Expand Down Expand Up @@ -56,22 +57,31 @@ class _CartState extends State<Cart> {
height: 60,
color: Colors.black,
minWidth: size.width,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
onPressed: () {
final ScaffoldMessengerState buyNow = ScaffoldMessenger.of(context);
buyNow.showSnackBar(
SnackBar(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
backgroundColor: Colors.black,
behavior: SnackBarBehavior.floating,
content: const TextBuilder(text: 'Thank you for shopping with us'),
content:
const TextBuilder(text: 'Thank you for shopping with us'),
),
);
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextBuilder(text: '₹ ${cart.totalPrice()}', color: Colors.white, fontWeight: FontWeight.w600, fontSize: 20),
Consumer<CartProvider>(builder: (_, cart, child) {
return TextBuilder(
text: '₹ ${cart.totalPrice()}',
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 20);
}),
const SizedBox(width: 10.0),
const TextBuilder(
text: 'Pay Now',
Expand Down
63 changes: 50 additions & 13 deletions lib/view/drawer/drawer_menu.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class _DrawerMenuState extends State<DrawerMenu> {
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircleAvatar(
radius: 35,
radius: 30,
backgroundColor: Colors.white,
backgroundImage: NetworkImage(RawString.appLogoURL),
),
Expand All @@ -33,8 +33,14 @@ class _DrawerMenuState extends State<DrawerMenu> {
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextBuilder(text: RawString.appName, fontSize: 30.0, fontWeight: FontWeight.bold),
TextBuilder(text: RawString.dummyEmail, fontSize: 15.0, fontWeight: FontWeight.normal),
TextBuilder(
text: RawString.appName,
fontSize: 20.0,
fontWeight: FontWeight.bold),
TextBuilder(
text: RawString.dummyEmail,
fontSize: 15.0,
fontWeight: FontWeight.normal),
],
),
],
Expand All @@ -46,43 +52,70 @@ class _DrawerMenuState extends State<DrawerMenu> {
children: [
ListTile(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (_) => const Home()));
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const Home()));
},
leading: const Icon(
Icons.home,
color: Colors.black,
size: 20,
),
title: const TextBuilder(text: "Home", fontSize: 20.0, fontWeight: FontWeight.w600, color: Colors.black),
title: const TextBuilder(
text: "Home",
fontSize: 20.0,
fontWeight: FontWeight.w600,
color: Colors.black),
),
ListTile(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (_) => const Cart()));
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const Cart()));
},
leading: const Icon(
Icons.shopping_bag,
color: Colors.black,
size: 20,
),
title: const TextBuilder(text: "Cart", fontSize: 20.0, fontWeight: FontWeight.w600, color: Colors.black),
title: const TextBuilder(
text: "Cart",
fontSize: 20.0,
fontWeight: FontWeight.w600,
color: Colors.black),
),
ListTile(
onTap: () {
UrlLaunch.launchInBrowser(urlString: RawString.gitHubRepo);
UrlLaunch.launchInBrowser(
urlString: RawString.gitHubRepo);
},
leading: const Icon(Icons.source, color: Colors.black, size: 20),
title: const TextBuilder(text: "Source code", fontSize: 20.0, fontWeight: FontWeight.w600, color: Colors.black),
leading: const Icon(Icons.source,
color: Colors.black, size: 20),
title: const TextBuilder(
text: "Source code",
fontSize: 20.0,
fontWeight: FontWeight.w600,
color: Colors.black),
),
ListTile(
onTap: () {
UrlLaunch.makeEmail(email: RawString.gitHubRepo, body: 'Hello,', subject: 'Can we Talk?');
UrlLaunch.makeEmail(
email: RawString.gitHubRepo,
body: 'Hello,',
subject: 'Can we Talk?');
},
leading: const Icon(
Icons.email,
color: Colors.black,
size: 20,
),
title: const TextBuilder(text: "Contact", fontSize: 20.0, fontWeight: FontWeight.w600, color: Colors.black),
title: const TextBuilder(
text: "Contact",
fontSize: 20.0,
fontWeight: FontWeight.w600,
color: Colors.black),
),
InkWell(
onTap: () {
Expand All @@ -99,7 +132,11 @@ class _DrawerMenuState extends State<DrawerMenu> {
color: Colors.black,
size: 20,
),
title: TextBuilder(text: "About App", fontSize: 20.0, fontWeight: FontWeight.w600, color: Colors.black),
title: TextBuilder(
text: "About App",
fontSize: 20.0,
fontWeight: FontWeight.w600,
color: Colors.black),
),
),
],
Expand Down
55 changes: 34 additions & 21 deletions lib/view/home/home.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,36 @@ class _HomeState extends State<Home> {
Future<List<ProductModel>>? futureProduct;
Future<List<ProductModel>> fetchProducts() async {
List<ProductModel> products = [];
const baseUrl = 'https://fakestoreapi.com/products';
var request = http.Request('GET', Uri.parse(baseUrl));
try{
const baseUrl = 'https://fakestoreapi.com/products';
var request = http.Request('GET', Uri.parse(baseUrl));

http.StreamedResponse response = await request.send();
var responseBody = await response.stream.bytesToString(); // Store the response body
http.StreamedResponse response = await request.send();
var responseBody =
await response.stream.bytesToString(); // Store the response body

if (response.statusCode == 200) {
if (kDebugMode) {
print(responseBody);
}
final jsonData = jsonDecode(responseBody);
products = jsonData.map<ProductModel>((e) => ProductModel.fromJson(e)).toList();
setState(() {}); // Assuming this is within a Stateful widget
if (response.statusCode == 200) {
if (kDebugMode) {
print(responseBody);
}
final jsonData = jsonDecode(responseBody);
products =
jsonData.map<ProductModel>((e) => ProductModel.fromJson(e)).toList();
setState(() {}); // Assuming this is within a Stateful widget

return products;
} else {
if (kDebugMode) {
print(response.reasonPhrase);
}
return [];
}
return products;
} else {
if (kDebugMode) {
print(response.reasonPhrase);
}
return [];
}
}catch(e){
if (kDebugMode) {
print("something went wrong!");
}
return [];
}
}

@override
Expand All @@ -55,12 +64,15 @@ class _HomeState extends State<Home> {
actions: [
IconButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (_) => const Cart()));
Navigator.push(
context, MaterialPageRoute(builder: (_) => const Cart()));
},
icon: Stack(
children: [
Padding(
padding: EdgeInsets.only(top: cart.itemCount != 0 ? 8 : 0, right: cart.itemCount != 0 ? 8 : 0),
padding: EdgeInsets.only(
top: cart.itemCount != 0 ? 8 : 0,
right: cart.itemCount != 0 ? 8 : 0),
child: const Icon(
Icons.shopping_cart,
color: Colors.black,
Expand All @@ -75,7 +87,8 @@ class _HomeState extends State<Home> {
height: 20,
width: 20,
alignment: Alignment.center,
decoration: const BoxDecoration(shape: BoxShape.circle, color: Colors.black),
decoration: const BoxDecoration(
shape: BoxShape.circle, color: Colors.black),
child: TextBuilder(
text: cart.itemCount.toString(),
color: Colors.white,
Expand Down
26 changes: 16 additions & 10 deletions lib/view/init_screen/login.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,6 @@ class _LoginState extends State<Login> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();

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

@override
Widget build(BuildContext context) {
// total height and width of screen
Expand All @@ -31,9 +26,15 @@ class _LoginState extends State<Login> {
children: [
const AppNameWidget(),
const SizedBox(height: 100),
const CustomTextField(labelText: 'Email', hintText: '[email protected]', prefixIcon: Icons.email),
const CustomTextField(
labelText: 'Email',
hintText: '[email protected]',
prefixIcon: Icons.email),
const SizedBox(height: 20.0),
const CustomTextField(labelText: 'Password', hintText: 'Password', prefixIcon: Icons.lock),
const CustomTextField(
labelText: 'Password',
hintText: 'Password',
prefixIcon: Icons.lock),
Align(
alignment: Alignment.centerRight,
child: InkWell(
Expand All @@ -51,9 +52,13 @@ class _LoginState extends State<Login> {
height: 60,
color: Colors.black,
minWidth: size.width * 0.8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
onPressed: () {
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (_) => const Home()), (route) => false);
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (_) => const Home()),
(route) => false);
},
child: const TextBuilder(
text: 'Login',
Expand All @@ -73,7 +78,8 @@ class _LoginState extends State<Login> {
),
InkWell(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (_) => const Register()));
Navigator.push(context,
MaterialPageRoute(builder: (_) => const Register()));
},
child: const TextBuilder(
text: 'Sign Up',
Expand Down
Loading