repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/models/order_status.dart | class OrderStatus {
String id;
String status;
OrderStatus();
OrderStatus.fromJSON(Map<String, dynamic> jsonMap) {
try {
id = jsonMap['id'].toString();
status = jsonMap['status'] != null ? jsonMap['status'] : '';
} catch (e) {
id = '';
status = '';
print(e);
}
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/models/field.dart | import '../models/media.dart';
class Field {
String id;
String name;
String description;
Media image;
bool selected;
Field();
Field.fromJSON(Map<String, dynamic> jsonMap) {
try {
id = jsonMap['id'].toString();
name = jsonMap['name'];
description = jsonMap['description'];
image = jsonMap['media'] != null && (jsonMap['media'] as List).length > 0 ? Media.fromJSON(jsonMap['media'][0]) : new Media();
selected = jsonMap['selected'] ?? false;
} catch (e) {
id = '';
name = '';
description = '';
image = new Media();
selected = false;
print(e);
}
}
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
map['id'] = id;
return map;
}
@override
bool operator ==(dynamic other) {
return other.id == this.id;
}
@override
int get hashCode => super.hashCode;
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/models/product.dart | import '../models/category.dart';
import '../models/market.dart';
import '../models/media.dart';
import '../models/option.dart';
import '../models/option_group.dart';
import '../models/review.dart';
class Product {
String id;
String name;
double price;
double discountPrice;
Media image;
String description;
String ingredients;
String capacity;
String unit;
String packageItemsCount;
bool featured;
bool deliverable;
Market market;
Category category;
List<Option> options;
List<OptionGroup> optionGroups;
List<Review> productReviews;
Product();
Product.fromJSON(Map<String, dynamic> jsonMap) {
try {
id = jsonMap['id'].toString();
name = jsonMap['name'];
price = jsonMap['price'] != null ? jsonMap['price'].toDouble() : 0.0;
discountPrice = jsonMap['discount_price'] != null ? jsonMap['discount_price'].toDouble() : 0.0;
price = discountPrice != 0 ? discountPrice : price;
discountPrice = discountPrice == 0 ? discountPrice : jsonMap['price'] != null ? jsonMap['price'].toDouble() : 0.0;
description = jsonMap['description'];
capacity = jsonMap['capacity'].toString();
unit = jsonMap['unit'].toString();
packageItemsCount = jsonMap['package_items_count'].toString();
featured = jsonMap['featured'] ?? false;
deliverable = jsonMap['deliverable'] ?? false;
market = jsonMap['market'] != null ? Market.fromJSON(jsonMap['market']) : new Market();
category = jsonMap['category'] != null ? Category.fromJSON(jsonMap['category']) : new Category();
image = jsonMap['media'] != null && (jsonMap['media'] as List).length > 0 ? Media.fromJSON(jsonMap['media'][0]) : new Media();
options = jsonMap['options'] != null && (jsonMap['options'] as List).length > 0
? List.from(jsonMap['options']).map((element) => Option.fromJSON(element)).toList()
: [];
optionGroups = jsonMap['option_groups'] != null && (jsonMap['option_groups'] as List).length > 0
? List.from(jsonMap['option_groups']).map((element) => OptionGroup.fromJSON(element)).toList()
: [];
productReviews = jsonMap['product_reviews'] != null && (jsonMap['product_reviews'] as List).length > 0
? List.from(jsonMap['product_reviews']).map((element) => Review.fromJSON(element)).toList()
: [];
} catch (e) {
id = '';
name = '';
price = 0.0;
discountPrice = 0.0;
description = '';
capacity = '';
unit = '';
packageItemsCount = '';
featured = false;
deliverable = false;
market = new Market();
category = new Category();
image = new Media();
options = [];
optionGroups = [];
productReviews = [];
print(jsonMap);
}
}
Map toMap() {
var map = new Map<String, dynamic>();
map["id"] = id;
map["name"] = name;
map["price"] = price;
map["discountPrice"] = discountPrice;
map["description"] = description;
map["capacity"] = capacity;
map["package_items_count"] = packageItemsCount;
return map;
}
@override
bool operator ==(dynamic other) {
return other.id == this.id;
}
@override
int get hashCode => super.hashCode;
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/models/setting.dart | import 'package:flutter/cupertino.dart';
class Setting {
String appName = '';
double defaultTax;
String defaultCurrency;
String distanceUnit;
bool currencyRight = false;
bool payPalEnabled = true;
bool stripeEnabled = true;
String mainColor;
String mainDarkColor;
String secondColor;
String secondDarkColor;
String accentColor;
String accentDarkColor;
String scaffoldDarkColor;
String scaffoldColor;
String googleMapsKey;
ValueNotifier<Locale> mobileLanguage = new ValueNotifier(Locale('en', ''));
String appVersion;
bool enableVersion = true;
ValueNotifier<Brightness> brightness = new ValueNotifier(Brightness.light);
Setting();
Setting.fromJSON(Map<String, dynamic> jsonMap) {
try {
appName = jsonMap['app_name'] ?? null;
mainColor = jsonMap['main_color'] ?? null;
mainDarkColor = jsonMap['main_dark_color'] ?? '';
secondColor = jsonMap['second_color'] ?? '';
secondDarkColor = jsonMap['second_dark_color'] ?? '';
accentColor = jsonMap['accent_color'] ?? '';
accentDarkColor = jsonMap['accent_dark_color'] ?? '';
scaffoldDarkColor = jsonMap['scaffold_dark_color'] ?? '';
scaffoldColor = jsonMap['scaffold_color'] ?? '';
googleMapsKey = jsonMap['google_maps_key'] ?? null;
mobileLanguage.value = Locale(jsonMap['mobile_language'] ?? "en", '');
appVersion = jsonMap['app_version'] ?? '';
distanceUnit = jsonMap['distance_unit'] ?? 'km';
enableVersion = jsonMap['enable_version'] == null || jsonMap['enable_version'] == '0' ? false : true;
defaultTax = double.tryParse(jsonMap['default_tax']) ?? 0.0; //double.parse(jsonMap['default_tax'].toString());
defaultCurrency = jsonMap['default_currency'] ?? '';
currencyRight = jsonMap['currency_right'] == null || jsonMap['currency_right'] == '0' ? false : true;
payPalEnabled = jsonMap['enable_paypal'] == null || jsonMap['enable_paypal'] == '0' ? false : true;
stripeEnabled = jsonMap['enable_stripe'] == null || jsonMap['enable_stripe'] == '0' ? false : true;
} catch (e) {
print(e);
}
}
// ValueNotifier<Locale> initMobileLanguage(String defaultLanguage) {
// SharedPreferences.getInstance().then((prefs) {
// return new ValueNotifier(Locale(prefs.get('language') ?? defaultLanguage, ''));
// });
// return new ValueNotifier(Locale(defaultLanguage ?? "en", ''));
// }
Map toMap() {
var map = new Map<String, dynamic>();
map["app_name"] = appName;
map["default_tax"] = defaultTax;
map["default_currency"] = defaultCurrency;
map["currency_right"] = currencyRight;
map["enable_paypal"] = payPalEnabled;
map["enable_stripe"] = stripeEnabled;
map["mobile_language"] = mobileLanguage.value.languageCode;
return map;
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/models/user.dart | import '../models/media.dart';
class User {
String id;
String name;
String email;
String password;
String apiToken;
String deviceToken;
String phone;
String address;
String bio;
Media image;
// used for indicate if client logged in or not
bool auth;
// String role;
User();
User.fromJSON(Map<String, dynamic> jsonMap) {
try {
id = jsonMap['id'].toString();
name = jsonMap['name'] != null ? jsonMap['name'] : '';
email = jsonMap['email'] != null ? jsonMap['email'] : '';
apiToken = jsonMap['api_token'];
deviceToken = jsonMap['device_token'];
try {
phone = jsonMap['custom_fields']['phone']['view'];
} catch (e) {
phone = "";
}
try {
address = jsonMap['custom_fields']['address']['view'];
} catch (e) {
address = "";
}
try {
bio = jsonMap['custom_fields']['bio']['view'];
} catch (e) {
bio = "";
}
image = jsonMap['media'] != null && (jsonMap['media'] as List).length > 0 ? Media.fromJSON(jsonMap['media'][0]) : new Media();
} catch (e) {
print(e);
}
}
Map toMap() {
var map = new Map<String, dynamic>();
map["id"] = id;
map["email"] = email;
map["name"] = name;
map["password"] = password;
map["api_token"] = apiToken;
if (deviceToken != null) {
map["device_token"] = deviceToken;
}
map["phone"] = phone;
map["address"] = address;
map["bio"] = bio;
map["media"] = image?.toMap();
return map;
}
@override
String toString() {
var map = this.toMap();
map["auth"] = this.auth;
return map.toString();
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/models/option_group.dart | class OptionGroup {
String id;
String name;
OptionGroup();
OptionGroup.fromJSON(Map<String, dynamic> jsonMap) {
try {
id = jsonMap['id'].toString();
name = jsonMap['name'];
} catch (e) {
id = '';
name = '';
print(e);
}
}
Map toMap() {
var map = new Map<String, dynamic>();
map["id"] = id;
map["name"] = name;
return map;
}
@override
String toString() {
return this.toMap().toString();
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/NotificationItemWidget.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart' show DateFormat;
import '../helpers/helper.dart';
import '../helpers/swipe_widget.dart';
import '../models/notification.dart' as model;
class NotificationItemWidget extends StatelessWidget {
model.Notification notification;
VoidCallback onMarkAsRead;
VoidCallback onMarkAsUnRead;
VoidCallback onRemoved;
NotificationItemWidget({Key key, this.notification, this.onMarkAsRead, this.onMarkAsUnRead, this.onRemoved}) : super(key: key);
@override
Widget build(BuildContext context) {
return OnSlide(
backgroundColor: notification.read ? Theme.of(context).scaffoldBackgroundColor : Theme.of(context).primaryColor,
items: <ActionItems>[
ActionItems(
icon: notification.read
? new Icon(
Icons.panorama_fish_eye,
color: Theme.of(context).accentColor,
)
: new Icon(
Icons.brightness_1,
color: Theme.of(context).accentColor,
),
onPress: () {
if (notification.read) {
onMarkAsUnRead();
} else {
onMarkAsRead();
}
},
backgroudColor: Theme.of(context).scaffoldBackgroundColor),
new ActionItems(
icon: Padding(
padding: const EdgeInsets.only(right: 10),
child: new Icon(Icons.delete, color: Theme.of(context).accentColor),
),
onPress: () {
onRemoved();
},
backgroudColor: Theme.of(context).scaffoldBackgroundColor),
],
child: Container(
margin: EdgeInsets.symmetric(vertical: 10),
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Stack(
children: <Widget>[
Container(
width: 75,
height: 75,
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(begin: Alignment.bottomLeft, end: Alignment.topRight, colors: [
Theme.of(context).focusColor.withOpacity(0.7),
Theme.of(context).focusColor.withOpacity(0.05),
])),
child: Icon(
Icons.notifications,
color: Theme.of(context).scaffoldBackgroundColor,
size: 40,
),
),
Positioned(
right: -30,
bottom: -50,
child: Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: Theme.of(context).scaffoldBackgroundColor.withOpacity(0.15),
borderRadius: BorderRadius.circular(150),
),
),
),
Positioned(
left: -20,
top: -50,
child: Container(
width: 120,
height: 120,
decoration: BoxDecoration(
color: Theme.of(context).scaffoldBackgroundColor.withOpacity(0.15),
borderRadius: BorderRadius.circular(150),
),
),
)
],
),
SizedBox(width: 15),
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Text(
Helper.trans(notification.type),
overflow: TextOverflow.ellipsis,
maxLines: 2,
textAlign: TextAlign.justify,
style: Theme.of(context).textTheme.body2.merge(TextStyle(fontWeight: notification.read ? FontWeight.w300 : FontWeight.w600)),
),
Text(
DateFormat('yyyy-MM-dd | HH:mm').format(notification.createdAt),
style: Theme.of(context).textTheme.caption,
)
],
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/EmptyOrdersWidget.dart | import 'dart:async';
import 'package:flutter/material.dart';
import '../../generated/i18n.dart';
import '../helpers/app_config.dart' as config;
class EmptyOrdersWidget extends StatefulWidget {
EmptyOrdersWidget({
Key key,
}) : super(key: key);
@override
_EmptyOrdersWidgetState createState() => _EmptyOrdersWidgetState();
}
class _EmptyOrdersWidgetState extends State<EmptyOrdersWidget> {
bool loading = true;
@override
void initState() {
Timer(Duration(seconds: 5), () {
if (mounted) {
setState(() {
loading = false;
});
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
loading
? SizedBox(
height: 3,
child: LinearProgressIndicator(
backgroundColor: Theme.of(context).accentColor.withOpacity(0.2),
),
)
: SizedBox(),
Container(
alignment: AlignmentDirectional.center,
padding: EdgeInsets.symmetric(horizontal: 30),
height: config.App(context).appHeight(70),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Stack(
children: <Widget>[
Container(
width: 150,
height: 150,
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(begin: Alignment.bottomLeft, end: Alignment.topRight, colors: [
Theme.of(context).focusColor.withOpacity(0.7),
Theme.of(context).focusColor.withOpacity(0.05),
])),
child: Icon(
Icons.shopping_basket,
color: Theme.of(context).scaffoldBackgroundColor,
size: 70,
),
),
Positioned(
right: -30,
bottom: -50,
child: Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: Theme.of(context).scaffoldBackgroundColor.withOpacity(0.15),
borderRadius: BorderRadius.circular(150),
),
),
),
Positioned(
left: -20,
top: -50,
child: Container(
width: 120,
height: 120,
decoration: BoxDecoration(
color: Theme.of(context).scaffoldBackgroundColor.withOpacity(0.15),
borderRadius: BorderRadius.circular(150),
),
),
)
],
),
SizedBox(height: 15),
Opacity(
opacity: 0.4,
child: Text(
S.of(context).you_dont_have_any_order_assigned_to_you,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.display2.merge(TextStyle(fontWeight: FontWeight.w300)),
),
),
SizedBox(height: 50),
],
),
),
],
);
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/FaqItemWidget.dart | import 'package:flutter/material.dart';
import '../helpers/helper.dart';
import '../models/faq.dart';
class FaqItemWidget extends StatelessWidget {
Faq faq;
FaqItemWidget({Key key, this.faq}) : super(key: key);
@override
Widget build(BuildContext context) {
return DecoratedBox(
decoration: BoxDecoration(boxShadow: [
BoxShadow(
color: Theme.of(context).focusColor.withOpacity(0.15),
offset: Offset(0, 5),
blurRadius: 15,
)
]),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: double.infinity,
padding: EdgeInsets.all(10),
decoration:
BoxDecoration(color: Theme.of(context).focusColor, borderRadius: BorderRadius.only(topLeft: Radius.circular(5), topRight: Radius.circular(5))),
child: Text(
Helper.skipHtml(this.faq.question),
style: Theme.of(context).textTheme.body2.merge(TextStyle(color: Theme.of(context).primaryColor)),
),
),
Container(
width: double.infinity,
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Theme.of(context).primaryColor, borderRadius: BorderRadius.only(bottomRight: Radius.circular(5), bottomLeft: Radius.circular(5))),
child: Text(
Helper.skipHtml(this.faq.answer),
style: Theme.of(context).textTheme.body1,
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/BlockButtonWidget.dart | import 'package:flutter/material.dart';
class BlockButtonWidget extends StatelessWidget {
const BlockButtonWidget({Key key, @required this.color, @required this.text, @required this.onPressed}) : super(key: key);
final Color color;
final Text text;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(color: this.color.withOpacity(0.4), blurRadius: 40, offset: Offset(0, 15)),
BoxShadow(color: this.color.withOpacity(0.4), blurRadius: 13, offset: Offset(0, 3))
],
borderRadius: BorderRadius.all(Radius.circular(100)),
),
child: FlatButton(
onPressed: this.onPressed,
padding: EdgeInsets.symmetric(horizontal: 66, vertical: 14),
color: this.color,
shape: StadiumBorder(),
child: this.text,
),
);
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/ShoppingCartButtonWidget.dart | import 'package:flutter/material.dart';
import 'package:mvc_pattern/mvc_pattern.dart';
import '../controllers/notification_controller.dart';
class ShoppingCartButtonWidget extends StatefulWidget {
const ShoppingCartButtonWidget({
this.iconColor,
this.labelColor,
Key key,
}) : super(key: key);
final Color iconColor;
final Color labelColor;
@override
_ShoppingCartButtonWidgetState createState() => _ShoppingCartButtonWidgetState();
}
class _ShoppingCartButtonWidgetState extends StateMVC<ShoppingCartButtonWidget> {
NotificationController _con;
_ShoppingCartButtonWidgetState() : super(NotificationController()) {
_con = controller;
}
@override
void initState() {
//_con.listenForCartsCount();
super.initState();
}
@override
Widget build(BuildContext context) {
return FlatButton(
onPressed: () {
Navigator.of(context).pushNamed('/Notifications');
},
child: Stack(
alignment: AlignmentDirectional.bottomEnd,
children: <Widget>[
Icon(
Icons.notifications_none,
color: this.widget.iconColor,
size: 28,
),
Container(
child: Text(
_con.unReadNotificationsCount.toString(),
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.caption.merge(
TextStyle(color: Theme.of(context).primaryColor, fontSize: 8),
),
),
padding: EdgeInsets.all(0),
decoration: BoxDecoration(color: this.widget.labelColor, borderRadius: BorderRadius.all(Radius.circular(10))),
constraints: BoxConstraints(minWidth: 13, maxWidth: 13, minHeight: 13, maxHeight: 13),
),
],
),
color: Colors.transparent,
);
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/CircularLoadingWidget.dart | import 'dart:async';
import 'package:flutter/material.dart';
class CircularLoadingWidget extends StatefulWidget {
double height;
CircularLoadingWidget({Key key, this.height}) : super(key: key);
@override
_CircularLoadingWidgetState createState() => _CircularLoadingWidgetState();
}
class _CircularLoadingWidgetState extends State<CircularLoadingWidget> with SingleTickerProviderStateMixin {
Animation<double> animation;
AnimationController animationController;
void initState() {
super.initState();
animationController = AnimationController(duration: Duration(milliseconds: 300), vsync: this);
CurvedAnimation curve = CurvedAnimation(parent: animationController, curve: Curves.easeOut);
animation = Tween<double>(begin: widget.height, end: 0).animate(curve)
..addListener(() {
if (mounted) {
setState(() {});
}
});
Timer(Duration(seconds: 10), () {
if (mounted) {
animationController.forward();
}
});
}
@override
void dispose() {
// Timer(Duration(seconds: 30), () {
// //if (mounted) {
// //}
// });
animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Opacity(
opacity: animation.value / 100 > 1.0 ? 1.0 : animation.value / 100,
child: SizedBox(
height: animation.value,
child: new Center(
child: new CircularProgressIndicator(),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/ProfileSettingsDialog.dart | import 'package:flutter/material.dart';
import '../../generated/i18n.dart';
import '../models/user.dart';
class ProfileSettingsDialog extends StatefulWidget {
User user;
VoidCallback onChanged;
ProfileSettingsDialog({Key key, this.user, this.onChanged}) : super(key: key);
@override
_ProfileSettingsDialogState createState() => _ProfileSettingsDialogState();
}
class _ProfileSettingsDialogState extends State<ProfileSettingsDialog> {
GlobalKey<FormState> _profileSettingsFormKey = new GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return FlatButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return SimpleDialog(
contentPadding: EdgeInsets.symmetric(horizontal: 20),
titlePadding: EdgeInsets.symmetric(horizontal: 15, vertical: 20),
title: Row(
children: <Widget>[
Icon(Icons.person),
SizedBox(width: 10),
Text(
S.of(context).profile_settings,
style: Theme.of(context).textTheme.body2,
)
],
),
children: <Widget>[
Form(
key: _profileSettingsFormKey,
child: Column(
children: <Widget>[
new TextFormField(
style: TextStyle(color: Theme.of(context).hintColor),
keyboardType: TextInputType.text,
decoration: getInputDecoration(hintText: S.of(context).john_doe, labelText: S.of(context).full_name),
initialValue: widget.user.name,
validator: (input) => input.trim().length < 3 ? S.of(context).not_a_valid_full_name : null,
onSaved: (input) => widget.user.name = input,
),
new TextFormField(
style: TextStyle(color: Theme.of(context).hintColor),
keyboardType: TextInputType.emailAddress,
decoration: getInputDecoration(hintText: '[email protected]', labelText: S.of(context).email_address),
initialValue: widget.user.email,
validator: (input) => !input.contains('@') ? S.of(context).not_a_valid_email : null,
onSaved: (input) => widget.user.email = input,
),
new TextFormField(
style: TextStyle(color: Theme.of(context).hintColor),
keyboardType: TextInputType.text,
decoration: getInputDecoration(hintText: '+136 269 9765', labelText: S.of(context).phone),
initialValue: widget.user.phone,
validator: (input) => input.trim().length < 3 ? S.of(context).not_a_valid_phone : null,
onSaved: (input) => widget.user.phone = input,
),
new TextFormField(
style: TextStyle(color: Theme.of(context).hintColor),
keyboardType: TextInputType.text,
decoration: getInputDecoration(hintText: S.of(context).your_address, labelText: S.of(context).address),
initialValue: widget.user.address,
validator: (input) => input.trim().length < 3 ? S.of(context).not_a_valid_address : null,
onSaved: (input) => widget.user.address = input,
),
new TextFormField(
style: TextStyle(color: Theme.of(context).hintColor),
keyboardType: TextInputType.text,
decoration: getInputDecoration(hintText: S.of(context).your_biography, labelText: S.of(context).about),
initialValue: widget.user.bio,
validator: (input) => input.trim().length < 3 ? S.of(context).not_a_valid_biography : null,
onSaved: (input) => widget.user.bio = input,
),
],
),
),
SizedBox(height: 20),
Row(
children: <Widget>[
MaterialButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(S.of(context).cancel),
),
MaterialButton(
onPressed: _submit,
child: Text(
S.of(context).save,
style: TextStyle(color: Theme.of(context).accentColor),
),
),
],
mainAxisAlignment: MainAxisAlignment.end,
),
SizedBox(height: 10),
],
);
});
},
child: Text(
S.of(context).edit,
style: Theme.of(context).textTheme.body1,
),
);
}
InputDecoration getInputDecoration({String hintText, String labelText}) {
return new InputDecoration(
hintText: hintText,
labelText: labelText,
hintStyle: Theme.of(context).textTheme.body1.merge(
TextStyle(color: Theme.of(context).focusColor),
),
enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Theme.of(context).hintColor.withOpacity(0.2))),
focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: Theme.of(context).hintColor)),
hasFloatingPlaceholder: true,
labelStyle: Theme.of(context).textTheme.body1.merge(
TextStyle(color: Theme.of(context).hintColor),
),
);
}
void _submit() {
if (_profileSettingsFormKey.currentState.validate()) {
_profileSettingsFormKey.currentState.save();
widget.onChanged();
Navigator.pop(context);
}
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/ShoppingCartFloatButtonWidget.dart | import 'package:flutter/material.dart';
import 'package:mvc_pattern/mvc_pattern.dart';
import '../controllers/cart_controller.dart';
import '../models/product.dart';
import '../models/route_argument.dart';
class ShoppingCartFloatButtonWidget extends StatefulWidget {
const ShoppingCartFloatButtonWidget({
this.iconColor,
this.labelColor,
this.product,
Key key,
}) : super(key: key);
final Color iconColor;
final Color labelColor;
final Product product;
@override
_ShoppingCartFloatButtonWidgetState createState() => _ShoppingCartFloatButtonWidgetState();
}
class _ShoppingCartFloatButtonWidgetState extends StateMVC<ShoppingCartFloatButtonWidget> {
CartController _con;
_ShoppingCartFloatButtonWidgetState() : super(CartController()) {
_con = controller;
}
@override
void initState() {
_con.listenForCartsCount();
super.initState();
}
@override
Widget build(BuildContext context) {
return SizedBox(
width: 60,
height: 60,
child: RaisedButton(
padding: EdgeInsets.all(0),
color: Theme.of(context).accentColor,
shape: StadiumBorder(),
onPressed: () {
Navigator.of(context).pushReplacementNamed('/Cart', arguments: RouteArgument(param: '/Product', id: widget.product.id));
},
child: Stack(
alignment: AlignmentDirectional.bottomEnd,
children: <Widget>[
Icon(
Icons.shopping_cart,
color: this.widget.iconColor,
size: 28,
),
Container(
child: Text(
_con.cartCount.toString(),
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.caption.merge(
TextStyle(color: Theme.of(context).primaryColor, fontSize: 9),
),
),
padding: EdgeInsets.all(0),
decoration: BoxDecoration(color: this.widget.labelColor, borderRadius: BorderRadius.all(Radius.circular(10))),
constraints: BoxConstraints(minWidth: 15, maxWidth: 15, minHeight: 15, maxHeight: 15),
),
],
),
),
);
// return FlatButton(
// onPressed: () {
// print('to shopping cart');
// },
// child:
// color: Colors.transparent,
// );
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/ProfileAvatarWidget.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import '../models/user.dart';
class ProfileAvatarWidget extends StatelessWidget {
final User user;
ProfileAvatarWidget({
Key key,
this.user,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(vertical: 30),
decoration: BoxDecoration(
color: Theme.of(context).accentColor,
borderRadius: BorderRadius.only(bottomLeft: Radius.circular(30), bottomRight: Radius.circular(30)),
),
child: Column(
children: <Widget>[
Container(
height: 160,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
// SizedBox(
// width: 50,
// height: 50,
// child: FlatButton(
// padding: EdgeInsets.all(0),
// onPressed: () {},
// child: Icon(Icons.add, color: Theme.of(context).primaryColor),
// color: Theme.of(context).accentColor,
// shape: StadiumBorder(),
// ),
// ),
ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(300)),
child: CachedNetworkImage(
height: 135,
width: 135,
fit: BoxFit.cover,
imageUrl: user.image.url,
placeholder: (context, url) => Image.asset(
'assets/img/loading.gif',
fit: BoxFit.cover,
height: 135,
width: 135,
),
errorWidget: (context, url, error) => Icon(Icons.error),
),
),
// SizedBox(
// width: 50,
// height: 50,
// child: FlatButton(
// padding: EdgeInsets.all(0),
// onPressed: () {},
// child: Icon(Icons.chat, color: Theme.of(context).primaryColor),
// color: Theme.of(context).accentColor,
// shape: StadiumBorder(),
// ),
// ),
],
),
),
Text(
user.name,
style: Theme.of(context).textTheme.headline.merge(TextStyle(color: Theme.of(context).primaryColor)),
),
Text(
user.address,
style: Theme.of(context).textTheme.caption.merge(TextStyle(color: Theme.of(context).primaryColor)),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/OrderItemWidget.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart' show DateFormat;
import '../helpers/helper.dart';
import '../models/order.dart';
import '../models/product_order.dart';
import '../models/route_argument.dart';
class OrderItemWidget extends StatelessWidget {
final String heroTag;
final ProductOrder productOrder;
final Order order;
const OrderItemWidget({Key key, this.productOrder, this.order, this.heroTag}) : super(key: key);
@override
Widget build(BuildContext context) {
return InkWell(
splashColor: Theme.of(context).accentColor,
focusColor: Theme.of(context).accentColor,
highlightColor: Theme.of(context).primaryColor,
onTap: () {
Navigator.of(context).pushNamed('/OrderDetails', arguments: RouteArgument(id: order.id));
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 8),
decoration: BoxDecoration(
color: Theme.of(context).primaryColor.withOpacity(0.9),
boxShadow: [
BoxShadow(color: Theme.of(context).focusColor.withOpacity(0.1), blurRadius: 5, offset: Offset(0, 2)),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Hero(
tag: heroTag + productOrder?.id,
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(5)),
child: CachedNetworkImage(
height: 60,
width: 60,
fit: BoxFit.cover,
imageUrl: productOrder.product.image.thumb,
placeholder: (context, url) => Image.asset(
'assets/img/loading.gif',
fit: BoxFit.cover,
height: 60,
width: 60,
),
errorWidget: (context, url, error) => Icon(Icons.error),
),
),
),
SizedBox(width: 15),
Flexible(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
productOrder.product.name,
overflow: TextOverflow.ellipsis,
maxLines: 2,
style: Theme.of(context).textTheme.subhead,
),
Text(
productOrder.product.market.name,
overflow: TextOverflow.ellipsis,
maxLines: 2,
style: Theme.of(context).textTheme.caption,
),
Text(
'Quantity: ${productOrder.quantity}',
overflow: TextOverflow.ellipsis,
maxLines: 2,
style: Theme.of(context).textTheme.caption,
),
],
),
),
SizedBox(width: 8),
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Helper.getPrice(Helper.getTotalOrderPrice(productOrder, order.tax, order.deliveryFee), context,
style: Theme.of(context).textTheme.display1),
Text(
DateFormat('yyyy-MM-dd').format(productOrder.dateTime),
style: Theme.of(context).textTheme.caption,
),
Text(
DateFormat('HH:mm').format(productOrder.dateTime),
style: Theme.of(context).textTheme.caption,
),
],
),
],
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/EmptyNotificationsWidget.dart | import 'dart:async';
import 'package:flutter/material.dart';
import '../../generated/i18n.dart';
import '../helpers/app_config.dart' as config;
class EmptyNotificationsWidget extends StatefulWidget {
EmptyNotificationsWidget({
Key key,
}) : super(key: key);
@override
_EmptyNotificationsWidgetState createState() => _EmptyNotificationsWidgetState();
}
class _EmptyNotificationsWidgetState extends State<EmptyNotificationsWidget> {
bool loading = true;
@override
void initState() {
Timer(Duration(seconds: 5), () {
if (mounted) {
setState(() {
loading = false;
});
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
loading
? SizedBox(
height: 3,
child: LinearProgressIndicator(
backgroundColor: Theme.of(context).accentColor.withOpacity(0.2),
),
)
: SizedBox(),
Container(
alignment: AlignmentDirectional.center,
padding: EdgeInsets.symmetric(horizontal: 30),
height: config.App(context).appHeight(70),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Stack(
children: <Widget>[
Container(
width: 150,
height: 150,
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(begin: Alignment.bottomLeft, end: Alignment.topRight, colors: [
Theme.of(context).focusColor.withOpacity(0.7),
Theme.of(context).focusColor.withOpacity(0.05),
])),
child: Icon(
Icons.notifications,
color: Theme.of(context).scaffoldBackgroundColor,
size: 70,
),
),
Positioned(
right: -30,
bottom: -50,
child: Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: Theme.of(context).scaffoldBackgroundColor.withOpacity(0.15),
borderRadius: BorderRadius.circular(150),
),
),
),
Positioned(
left: -20,
top: -50,
child: Container(
width: 120,
height: 120,
decoration: BoxDecoration(
color: Theme.of(context).scaffoldBackgroundColor.withOpacity(0.15),
borderRadius: BorderRadius.circular(150),
),
),
)
],
),
SizedBox(height: 15),
Opacity(
opacity: 0.4,
child: Text(
S.of(context).dont_have_any_item_in_the_notification_list,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.display2.merge(TextStyle(fontWeight: FontWeight.w300)),
),
),
SizedBox(height: 50),
!loading
? FlatButton(
onPressed: () {
Navigator.of(context).pushNamed('/Pages', arguments: 1);
},
padding: EdgeInsets.symmetric(vertical: 12, horizontal: 30),
color: Theme.of(context).accentColor.withOpacity(1),
shape: StadiumBorder(),
child: Text(
'Go To Home',
style: Theme.of(context).textTheme.title.merge(TextStyle(color: Theme.of(context).scaffoldBackgroundColor)),
),
)
: SizedBox(),
],
),
),
],
);
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/LanguageItemWidget.dart | import 'package:flutter/material.dart';
import '../models/language.dart';
import '../repository/settings_repository.dart' as settingRepo;
class LanguageItemWidget extends StatefulWidget {
final Language language;
final ValueChanged onTap;
const LanguageItemWidget({
Key key,
this.language,
this.onTap,
}) : super(key: key);
@override
_LanguageItemWidgetState createState() => _LanguageItemWidgetState();
}
class _LanguageItemWidgetState extends State<LanguageItemWidget> with SingleTickerProviderStateMixin {
Animation animation;
AnimationController animationController;
Animation<double> sizeCheckAnimation;
Animation<double> rotateCheckAnimation;
Animation<double> opacityAnimation;
Animation opacityCheckAnimation;
bool checked = false;
@override
void initState() {
super.initState();
animationController = AnimationController(duration: Duration(milliseconds: 350), vsync: this);
CurvedAnimation curve = CurvedAnimation(parent: animationController, curve: Curves.easeOut);
animation = Tween(begin: 0.0, end: 40.0).animate(curve)
..addListener(() {
setState(() {});
});
opacityAnimation = Tween(begin: 0.0, end: 0.85).animate(curve)
..addListener(() {
setState(() {});
});
opacityCheckAnimation = Tween(begin: 0.0, end: 1.0).animate(curve)
..addListener(() {
setState(() {});
});
rotateCheckAnimation = Tween(begin: 2.0, end: 0.0).animate(curve)
..addListener(() {
setState(() {});
});
sizeCheckAnimation = Tween<double>(begin: 0, end: 24).animate(curve)
..addListener(() {
setState(() {});
});
}
@override
void dispose() {
super.dispose();
animationController.dispose();
}
@override
Widget build(BuildContext context) {
if (widget.language.selected) {
animationController.forward();
}
return InkWell(
onTap: () async {
widget.onTap(widget.language);
if (widget.language.selected) {
animationController.reverse();
} else {
animationController.forward();
}
settingRepo.setting.value.mobileLanguage.value = new Locale(widget.language.code, '');
settingRepo.setting.notifyListeners();
//settingRepo.locale.notifyListeners();
//widget.language.selected = !widget.language.selected;
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 8),
decoration: BoxDecoration(
color: Theme.of(context).primaryColor.withOpacity(0.9),
boxShadow: [
BoxShadow(color: Theme.of(context).focusColor.withOpacity(0.1), blurRadius: 5, offset: Offset(0, 2)),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Stack(
alignment: AlignmentDirectional.center,
children: <Widget>[
Container(
height: 40,
width: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(40)),
image: DecorationImage(image: AssetImage(widget.language.flag), fit: BoxFit.cover),
),
),
Container(
height: animation.value,
width: animation.value,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(40)),
color: Theme.of(context).accentColor.withOpacity(opacityAnimation.value),
),
child: Transform.rotate(
angle: rotateCheckAnimation.value,
child: Icon(
Icons.check,
size: sizeCheckAnimation.value,
color: Theme.of(context).primaryColor.withOpacity(opacityCheckAnimation.value),
),
),
),
],
),
SizedBox(width: 15),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
widget.language.englishName,
overflow: TextOverflow.ellipsis,
maxLines: 2,
style: Theme.of(context).textTheme.subhead,
),
Text(
widget.language.localName,
overflow: TextOverflow.ellipsis,
maxLines: 2,
style: Theme.of(context).textTheme.caption,
),
],
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/DrawerWidget.dart | import 'package:flutter/material.dart';
import 'package:mvc_pattern/mvc_pattern.dart';
import '../../generated/i18n.dart';
import '../controllers/profile_controller.dart';
import '../elements/CircularLoadingWidget.dart';
import '../repository/settings_repository.dart';
import '../repository/user_repository.dart';
class DrawerWidget extends StatefulWidget {
@override
_DrawerWidgetState createState() => _DrawerWidgetState();
}
class _DrawerWidgetState extends StateMVC<DrawerWidget> {
//ProfileController _con;
_DrawerWidgetState() : super(ProfileController()) {
//_con = controller;
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return Drawer(
child: currentUser.value.apiToken == null
? CircularLoadingWidget(height: 500)
: ListView(
children: <Widget>[
GestureDetector(
onTap: () {
Navigator.of(context).pushNamed('/Pages', arguments: 0);
},
child: UserAccountsDrawerHeader(
decoration: BoxDecoration(
color: Theme.of(context).hintColor.withOpacity(0.1),
// borderRadius: BorderRadius.only(bottomLeft: Radius.circular(35)),
),
accountName: Text(
currentUser.value.name,
style: Theme.of(context).textTheme.title,
),
accountEmail: Text(
currentUser.value.email,
style: Theme.of(context).textTheme.caption,
),
currentAccountPicture: CircleAvatar(
backgroundColor: Theme.of(context).accentColor,
backgroundImage: NetworkImage(currentUser.value.image.thumb),
),
),
),
ListTile(
onTap: () {
Navigator.of(context).pushNamed('/Pages', arguments: 1);
},
leading: Icon(
Icons.shopping_basket,
color: Theme.of(context).focusColor.withOpacity(1),
),
title: Text(
S.of(context).orders,
style: Theme.of(context).textTheme.subhead,
),
),
ListTile(
onTap: () {
Navigator.of(context).pushNamed('/Notifications');
},
leading: Icon(
Icons.notifications,
color: Theme.of(context).focusColor.withOpacity(1),
),
title: Text(
S.of(context).notifications,
style: Theme.of(context).textTheme.subhead,
),
),
ListTile(
onTap: () {
Navigator.of(context).pushNamed('/Pages', arguments: 2);
},
leading: Icon(
Icons.history,
color: Theme.of(context).focusColor.withOpacity(1),
),
title: Text(
S.of(context).history,
style: Theme.of(context).textTheme.subhead,
),
),
ListTile(
dense: true,
title: Text(
S.of(context).application_preferences,
style: Theme.of(context).textTheme.body1,
),
trailing: Icon(
Icons.remove,
color: Theme.of(context).focusColor.withOpacity(0.3),
),
),
ListTile(
onTap: () {
Navigator.of(context).pushNamed('/Help');
},
leading: Icon(
Icons.help,
color: Theme.of(context).focusColor.withOpacity(1),
),
title: Text(
S.of(context).help__support,
style: Theme.of(context).textTheme.subhead,
),
),
ListTile(
onTap: () {
Navigator.of(context).pushNamed('/Settings');
},
leading: Icon(
Icons.settings,
color: Theme.of(context).focusColor.withOpacity(1),
),
title: Text(
S.of(context).settings,
style: Theme.of(context).textTheme.subhead,
),
),
ListTile(
onTap: () {
Navigator.of(context).pushNamed('/Languages');
},
leading: Icon(
Icons.translate,
color: Theme.of(context).focusColor.withOpacity(1),
),
title: Text(
S.of(context).languages,
style: Theme.of(context).textTheme.subhead,
),
),
ListTile(
onTap: () {
if (Theme.of(context).brightness == Brightness.dark) {
setBrightness(Brightness.light);
setting.value.brightness.value = Brightness.light;
} else {
setting.value.brightness.value = Brightness.dark;
setBrightness(Brightness.dark);
}
setting.notifyListeners();
},
leading: Icon(
Icons.brightness_6,
color: Theme.of(context).focusColor.withOpacity(1),
),
title: Text(
Theme.of(context).brightness == Brightness.dark ? S.of(context).light_mode : S.of(context).dark_mode,
style: Theme.of(context).textTheme.subhead,
),
),
ListTile(
onTap: () {
logout().then((value) {
Navigator.of(context).pushNamedAndRemoveUntil('/Login', (Route<dynamic> route) => false);
});
},
leading: Icon(
Icons.exit_to_app,
color: Theme.of(context).focusColor.withOpacity(1),
),
title: Text(
S.of(context).log_out,
style: Theme.of(context).textTheme.subhead,
),
),
setting.value.enableVersion
? ListTile(
dense: true,
title: Text(
S.of(context).version + " " + setting.value.appVersion,
style: Theme.of(context).textTheme.body1,
),
trailing: Icon(
Icons.remove,
color: Theme.of(context).focusColor.withOpacity(0.3),
),
)
: SizedBox(),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/elements/HeadingIconButtonWidget.dart | import 'package:flutter/material.dart';
class HeadingIconButtonWidget extends StatelessWidget {
const HeadingIconButtonWidget({Key key, @required this.text, @required this.icon, this.showActions = false}) : super(key: key);
final Text text;
final Icon icon;
final bool showActions;
@override
Widget build(BuildContext context) {
return Container(
// margin: EdgeInsets.only(top: 10),
child: Row(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
this.icon,
SizedBox(width: 10),
this.text,
],
),
),
IconButton(
color: Theme.of(context).hintColor,
onPressed: () {},
icon: Icon(Icons.more_horiz),
iconSize: 28,
)
],
),
);
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/helpers/custom_trace.dart | class CustomTrace {
final StackTrace _trace;
String fileName;
String functionName;
String callerFunctionName;
String message;
int lineNumber;
int columnNumber;
CustomTrace(this._trace, {this.message}) {
_parseTrace();
}
String _getFunctionNameFromFrame(String frame) {
/* Just giving another nickname to the frame */
var currentTrace = frame;
/* To get rid off the #number thing, get the index of the first whitespace */
var indexOfWhiteSpace = currentTrace.indexOf(' ');
/* Create a substring from the first whitespace index till the end of the string */
var subStr = currentTrace.substring(indexOfWhiteSpace);
/* Grab the function name using reg expr */
var indexOfFunction = subStr.indexOf(RegExp(r'[A-Za-z0-9]'));
/* Create a new substring from the function name index till the end of string */
subStr = subStr.substring(indexOfFunction);
//indexOfWhiteSpace = subStr.indexOf(' ');
/* Create a new substring from start to the first index of a whitespace. This substring gives us the function name */
//subStr = subStr.substring(0, indexOfWhiteSpace);
return subStr;
}
void _parseTrace() {
/* The trace comes with multiple lines of strings, (each line is also known as a frame), so split the trace's string by lines to get all the frames */
var frames = this._trace.toString().split("\n");
/* The first frame is the current function */
this.functionName = _getFunctionNameFromFrame(frames[0]);
/* The second frame is the caller function */
this.callerFunctionName = _getFunctionNameFromFrame(frames[1]);
/* The first frame has all the information we need */
var traceString = frames[0];
/* Search through the string and find the index of the file name by looking for the '.dart' regex */
var indexOfFileName = traceString.indexOf(RegExp(r'[A-Za-z]+.dart'));
var fileInfo = traceString.substring(indexOfFileName);
var listOfInfos = fileInfo.split(":");
/* Splitting fileInfo by the character ":" separates the file name, the line number and the column counter nicely.
Example: main.dart:5:12
To get the file name, we split with ":" and get the first index
To get the line number, we would have to get the second index
To get the column number, we would have to get the third index
*/
this.fileName = listOfInfos[0];
this.lineNumber = int.parse(listOfInfos[1]);
var columnStr = listOfInfos[2];
columnStr = columnStr.replaceFirst(")", "");
this.columnNumber = int.parse(columnStr);
}
@override
String toString() {
return "Error in ($functionName) | [$message] ";
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/helpers/checkbox_form_field.dart | import 'package:flutter/material.dart';
class CheckboxFormField extends FormField<bool> {
CheckboxFormField(
{Widget title,
@required BuildContext context,
FormFieldSetter<bool> onSaved,
FormFieldValidator<bool> validator,
bool initialValue = false,
bool autovalidate = false})
: super(
onSaved: onSaved,
validator: validator,
initialValue: initialValue,
autovalidate: autovalidate,
builder: (FormFieldState<bool> state) {
return CheckboxListTile(
dense: state.hasError,
title: title,
value: state.value,
onChanged: state.didChange,
subtitle: state.hasError
? Text(
state.errorText,
style: TextStyle(color: Theme.of(context).errorColor),
)
: null,
controlAffinity: ListTileControlAffinity.leading,
);
});
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/helpers/app_config.dart | import 'package:flutter/material.dart';
import '../repository/settings_repository.dart' as settingRepo;
class App {
BuildContext _context;
double _height;
double _width;
double _heightPadding;
double _widthPadding;
App(_context) {
this._context = _context;
MediaQueryData _queryData = MediaQuery.of(this._context);
_height = _queryData.size.height / 100.0;
_width = _queryData.size.width / 100.0;
_heightPadding = _height - ((_queryData.padding.top + _queryData.padding.bottom) / 100.0);
_widthPadding = _width - (_queryData.padding.left + _queryData.padding.right) / 100.0;
}
double appHeight(double v) {
return _height * v;
}
double appWidth(double v) {
return _width * v;
}
double appVerticalPadding(double v) {
return _heightPadding * v;
}
double appHorizontalPadding(double v) {
// int.parse(settingRepo.setting.mainColor.replaceAll("#", "0xFF"));
return _widthPadding * v;
}
}
class Colors {
Color mainColor(double opacity) {
try {
return Color(int.parse(settingRepo.setting.value.mainColor.replaceAll("#", "0xFF"))).withOpacity(opacity);
} catch (e) {
return Color(0xFFCCCCCC).withOpacity(opacity);
}
}
Color secondColor(double opacity) {
try {
return Color(int.parse(settingRepo.setting.value.secondColor.replaceAll("#", "0xFF"))).withOpacity(opacity);
} catch (e) {
return Color(0xFFCCCCCC).withOpacity(opacity);
}
}
Color accentColor(double opacity) {
try {
return Color(int.parse(settingRepo.setting.value.accentColor.replaceAll("#", "0xFF"))).withOpacity(opacity);
} catch (e) {
return Color(0xFFCCCCCC).withOpacity(opacity);
}
}
Color mainDarkColor(double opacity) {
try {
return Color(int.parse(settingRepo.setting.value.mainDarkColor.replaceAll("#", "0xFF"))).withOpacity(opacity);
} catch (e) {
return Color(0xFFCCCCCC).withOpacity(opacity);
}
}
Color secondDarkColor(double opacity) {
try {
return Color(int.parse(settingRepo.setting.value.secondDarkColor.replaceAll("#", "0xFF"))).withOpacity(opacity);
} catch (e) {
return Color(0xFFCCCCCC).withOpacity(opacity);
}
}
Color accentDarkColor(double opacity) {
try {
return Color(int.parse(settingRepo.setting.value.accentDarkColor.replaceAll("#", "0xFF"))).withOpacity(opacity);
} catch (e) {
return Color(0xFFCCCCCC).withOpacity(opacity);
}
}
Color scaffoldColor(double opacity) {
// TODO test if brightness is dark or not
try {
return Color(int.parse(settingRepo.setting.value.scaffoldColor.replaceAll("#", "0xFF"))).withOpacity(opacity);
} catch (e) {
return Color(0xFFCCCCCC).withOpacity(opacity);
}
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/helpers/size_change_notifier.dart | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
typedef void SizeChangedCallBack(Size newSize);
class LayoutSizeChangeNotification extends LayoutChangedNotification {
LayoutSizeChangeNotification(this.newSize) : super();
Size newSize;
}
/// A widget that automatically dispatches a [SizeChangedLayoutNotification]
/// when the layout dimensions of its child change.
///
/// The notification is not sent for the initial layout (since the size doesn't
/// change in that case, it's just established).
///
/// To listen for the notification dispatched by this widget, use a
/// [NotificationListener<SizeChangedLayoutNotification>].
///
/// The [Material] class listens for [LayoutChangedNotification]s, including
/// [SizeChangedLayoutNotification]s, to repaint [InkResponse] and [InkWell] ink
/// effects. When a widget is likely to change size, wrapping it in a
/// [SizeChangedLayoutNotifier] will cause the ink effects to correctly repaint
/// when the child changes size.
///
/// See also:
///
/// * [Notification], the base class for notifications that bubble through the
/// widget tree.
class LayoutSizeChangeNotifier extends SingleChildRenderObjectWidget {
/// Creates a [SizeChangedLayoutNotifier] that dispatches layout changed
/// notifications when [child] changes layout size.
const LayoutSizeChangeNotifier({Key key, Widget child}) : super(key: key, child: child);
@override
_SizeChangeRenderWithCallback createRenderObject(BuildContext context) {
return new _SizeChangeRenderWithCallback(onLayoutChangedCallback: (size) {
new LayoutSizeChangeNotification(size).dispatch(context);
});
}
}
class _SizeChangeRenderWithCallback extends RenderProxyBox {
_SizeChangeRenderWithCallback({RenderBox child, @required this.onLayoutChangedCallback})
: assert(onLayoutChangedCallback != null),
super(child);
// There's a 1:1 relationship between the _RenderSizeChangedWithCallback and
// the `context` that is captured by the closure created by createRenderObject
// above to assign to onLayoutChangedCallback, and thus we know that the
// onLayoutChangedCallback will never change nor need to change.
final SizeChangedCallBack onLayoutChangedCallback;
Size _oldSize;
@override
void performLayout() {
super.performLayout();
// Don't send the initial notification, or this will be SizeObserver all
// over again!
if (size != _oldSize) onLayoutChangedCallback(size);
_oldSize = size;
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/helpers/swipe_widget.dart | import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'size_change_notifier.dart';
class ActionItems extends Object {
ActionItems({@required this.icon, @required this.onPress, this.backgroudColor: Colors.grey}) {
assert(icon != null);
assert(onPress != null);
}
final Widget icon;
final VoidCallback onPress;
final Color backgroudColor;
}
class OnSlide extends StatefulWidget {
OnSlide({Key key, @required this.items, @required this.child, this.backgroundColor: Colors.white}) : super(key: key) {
assert(items.length <= 6);
}
final List<ActionItems> items;
final Widget child;
final Color backgroundColor;
@override
State<StatefulWidget> createState() {
return new _OnSlideState();
}
}
class _OnSlideState extends State<OnSlide> {
ScrollController controller = new ScrollController();
bool isOpen = false;
Size childSize;
@override
void initState() {
super.initState();
}
bool _handleScrollNotification(dynamic notification) {
if (notification is ScrollEndNotification) {
if (notification.metrics.pixels >= (widget.items.length * 70.0) / 2 && notification.metrics.pixels < widget.items.length * 70.0) {
scheduleMicrotask(() {
controller.animateTo(widget.items.length * 60.0, duration: new Duration(milliseconds: 600), curve: Curves.decelerate);
});
} else if (notification.metrics.pixels > 0.0 && notification.metrics.pixels < (widget.items.length * 70.0) / 2) {
scheduleMicrotask(() {
controller.animateTo(0.0, duration: new Duration(milliseconds: 600), curve: Curves.decelerate);
});
}
}
return true;
}
@override
Widget build(BuildContext context) {
if (childSize == null) {
return new NotificationListener(
child: new LayoutSizeChangeNotifier(
child: widget.child,
),
onNotification: (LayoutSizeChangeNotification notification) {
childSize = notification.newSize;
print(notification.newSize);
scheduleMicrotask(() {
setState(() {});
});
},
);
}
List<Widget> above = <Widget>[
new Container(
width: childSize.width,
height: childSize.height,
color: widget.backgroundColor,
child: widget.child,
),
];
List<Widget> under = <Widget>[];
for (ActionItems item in widget.items) {
under.add(new Container(
alignment: Alignment.center,
color: item.backgroudColor,
width: 60.0,
height: childSize.height,
child: item.icon,
));
above.add(new InkWell(
child: new Container(
alignment: Alignment.center,
width: 60.0,
height: childSize.height,
),
onTap: () {
controller.jumpTo(2.0);
item.onPress();
}));
}
Widget items = new Container(
width: childSize.width,
height: childSize.height,
color: widget.backgroundColor,
child: new Row(
mainAxisAlignment: MainAxisAlignment.end,
children: under,
),
);
Widget scrollview = new NotificationListener(
child: new ListView(
controller: controller,
scrollDirection: Axis.horizontal,
children: above,
),
onNotification: _handleScrollNotification,
);
return new Stack(
children: <Widget>[
items,
new Positioned(
child: scrollview,
left: 0.0,
bottom: 0.0,
right: 0.0,
top: 0.0,
)
],
);
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/helpers/maps_util.dart | import 'dart:async';
import 'dart:convert';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;
import '../models/Step.dart';
class MapsUtil {
static const BASE_URL = "https://maps.googleapis.com/maps/api/directions/json?";
static MapsUtil _instance = new MapsUtil.internal();
MapsUtil.internal();
factory MapsUtil() => _instance;
final JsonDecoder _decoder = new JsonDecoder();
Future<dynamic> get(String url) {
return http.get(BASE_URL + url).then((http.Response response) {
String res = response.body;
int statusCode = response.statusCode;
// print("API Response: " + res);
if (statusCode < 200 || statusCode > 400 || json == null) {
res = "{\"status\":" + statusCode.toString() + ",\"message\":\"error\",\"response\":" + res + "}";
throw new Exception(res);
}
List<LatLng> steps;
try {
steps = parseSteps(_decoder.convert(res)["routes"][0]["legs"][0]["steps"]);
} catch (e) {
// throw new Exception(e);
}
return steps;
});
}
List<LatLng> parseSteps(final responseBody) {
List<Step> _steps = responseBody.map<Step>((json) {
return new Step.fromJson(json);
}).toList();
List<LatLng> _latLang = _steps.map((Step step) => step.startLatLng).toList();
return _latLang;
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src | mirrored_repositories/flutter_proyects_in_2020/flutter_application/lib/src/helpers/helper.dart | import 'dart:async';
import 'dart:math';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:global_configuration/global_configuration.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:html/dom.dart' as dom;
import 'package:html/parser.dart';
import '../../generated/i18n.dart';
import '../elements/CircularLoadingWidget.dart';
import '../models/product_order.dart';
import '../repository/settings_repository.dart';
class Helper {
// for mapping data retrieved form json array
static getData(Map<String, dynamic> data) {
return data['data'] ?? [];
}
static int getIntData(Map<String, dynamic> data) {
return (data['data'] as int) ?? 0;
}
static bool getBoolData(Map<String, dynamic> data) {
return (data['data'] as bool) ?? false;
}
static getObjectData(Map<String, dynamic> data) {
return data['data'] ?? new Map<String, dynamic>();
}
static Future<Uint8List> getBytesFromAsset(String path, int width) async {
ByteData data = await rootBundle.load(path);
ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(), targetWidth: width);
ui.FrameInfo fi = await codec.getNextFrame();
return (await fi.image.toByteData(format: ui.ImageByteFormat.png)).buffer.asUint8List();
}
static Future<Marker> getMarker(Map<String, dynamic> res) async {
final Uint8List markerIcon = await getBytesFromAsset('assets/img/marker.png', 120);
final Marker marker = Marker(
markerId: MarkerId(res['id']),
icon: BitmapDescriptor.fromBytes(markerIcon),
// onTap: () {
// //print(res.name);
// },
anchor: Offset(0.5, 0.5),
infoWindow: InfoWindow(
title: res['name'],
snippet: res['distance'].toStringAsFixed(2) + ' mi',
onTap: () {
print('infowi tap');
}),
position: LatLng(double.parse(res['latitude']), double.parse(res['longitude'])));
return marker;
}
static Future<Marker> getOrderMarker(Map<String, dynamic> res) async {
final Uint8List markerIcon = await getBytesFromAsset('assets/img/marker.png', 120);
final Marker marker = Marker(
markerId: MarkerId(res['id']),
icon: BitmapDescriptor.fromBytes(markerIcon),
// onTap: () {
// //print(res.name);
// },
anchor: Offset(0.5, 0.5),
infoWindow: InfoWindow(
title: res['address'],
snippet: '',
onTap: () {
print('infowi tap');
}),
position: LatLng(res['latitude'], res['longitude']));
return marker;
}
static Future<Marker> getMyPositionMarker(double latitude, double longitude) async {
final Uint8List markerIcon = await getBytesFromAsset('assets/img/my_marker.png', 120);
final Marker marker = Marker(
markerId: MarkerId(Random().nextInt(100).toString()),
icon: BitmapDescriptor.fromBytes(markerIcon),
anchor: Offset(0.5, 0.5),
position: LatLng(latitude, longitude));
return marker;
}
static List<Icon> getStarsList(double rate, {double size = 18}) {
var list = <Icon>[];
list = List.generate(rate.floor(), (index) {
return Icon(Icons.star, size: size, color: Color(0xFFFFB24D));
});
if (rate - rate.floor() > 0) {
list.add(Icon(Icons.star_half, size: size, color: Color(0xFFFFB24D)));
}
list.addAll(List.generate(5 - rate.floor() - (rate - rate.floor()).ceil(), (index) {
return Icon(Icons.star_border, size: size, color: Color(0xFFFFB24D));
}));
return list;
}
// static Future<List> getPriceWithCurrency(double myPrice) async {
// final Setting _settings = await getCurrentSettings();
// List result = [];
// if (myPrice != null) {
// result.add('${myPrice.toStringAsFixed(2)}');
// if (_settings.currencyRight) {
// return '${myPrice.toStringAsFixed(2)} ' + _settings.defaultCurrency;
// } else {
// return _settings.defaultCurrency + ' ${myPrice.toStringAsFixed(2)}';
// }
// }
// if (_settings.currencyRight) {
// return '0.00 ' + _settings.defaultCurrency;
// } else {
// return _settings.defaultCurrency + ' 0.00';
// }
// }
static Widget getPrice(double myPrice, BuildContext context, {TextStyle style}) {
if (style != null) {
style = style.merge(TextStyle(fontSize: style.fontSize + 2));
}
try {
return RichText(
softWrap: false,
overflow: TextOverflow.fade,
maxLines: 1,
text: setting.value?.currencyRight != null && setting.value?.currencyRight == false
? TextSpan(
text: setting.value?.defaultCurrency,
style: style ?? Theme.of(context).textTheme.subhead,
children: <TextSpan>[
TextSpan(text: myPrice.toStringAsFixed(2) ?? '', style: style ?? Theme.of(context).textTheme.subhead),
],
)
: TextSpan(
text: myPrice.toStringAsFixed(2) ?? '',
style: style ?? Theme.of(context).textTheme.subhead,
children: <TextSpan>[
TextSpan(
text: setting.value?.defaultCurrency,
style: TextStyle(
fontWeight: FontWeight.w400, fontSize: style != null ? style.fontSize - 4 : Theme.of(context).textTheme.subhead.fontSize - 4)),
],
),
);
} catch (e) {
return Text('');
}
}
static double getTotalOrderPrice(ProductOrder productOrder, double tax, double deliveryFee) {
double total = productOrder.price * productOrder.quantity;
productOrder.options.forEach((option) {
total += option.price != null ? option.price : 0;
});
total += deliveryFee;
total += tax * total / 100;
return total;
}
static String getDistance(double distance) {
String unit = setting.value.distanceUnit;
if (unit == 'km') {
distance *= 1.60934;
}
return distance != null ? distance.toStringAsFixed(2) + " " + trans(unit) : "";
}
static String skipHtml(String htmlString) {
try {
var document = parse(htmlString);
String parsedString = parse(document.body.text).documentElement.text;
return parsedString;
} catch (e) {
return '';
}
}
static Html applyHtml(context, String html, {TextStyle style}) {
return Html(
blockSpacing: 0,
data: html,
defaultTextStyle: style ?? Theme.of(context).textTheme.body2.merge(TextStyle(fontSize: 14)),
useRichText: false,
customRender: (node, children) {
if (node is dom.Element) {
switch (node.localName) {
case "br":
return SizedBox(
height: 0,
);
case "p":
return Padding(
padding: EdgeInsets.only(top: 0, bottom: 0),
child: Container(
width: double.infinity,
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
alignment: WrapAlignment.start,
children: children,
),
),
);
}
}
return null;
},
);
}
static OverlayEntry overlayLoader(context) {
OverlayEntry loader = OverlayEntry(builder: (context) {
final size = MediaQuery.of(context).size;
return Positioned(
height: size.height,
width: size.width,
top: 0,
left: 0,
child: Material(
color: Theme.of(context).primaryColor.withOpacity(0.85),
child: CircularLoadingWidget(height: 200),
),
);
});
return loader;
}
static hideLoader(OverlayEntry loader) {
Timer(Duration(milliseconds: 500), () {
loader?.remove();
});
}
static String limitString(String text, {int limit = 24, String hiddenText = "..."}) {
return text.substring(0, min<int>(limit, text.length)) + (text.length > limit ? hiddenText : '');
}
static String getCreditCardNumber(String number) {
String result = '';
if (number != null && number.isNotEmpty && number.length == 16) {
result = number.substring(0, 4);
result += ' ' + number.substring(4, 8);
result += ' ' + number.substring(8, 12);
result += ' ' + number.substring(12, 16);
}
return result;
}
static Uri getUri(String path) {
String _path = Uri.parse(GlobalConfiguration().getString('base_url')).path;
if (!_path.endsWith('/')) {
_path += '/';
}
Uri uri = Uri(
scheme: Uri.parse(GlobalConfiguration().getString('base_url')).scheme,
host: Uri.parse(GlobalConfiguration().getString('base_url')).host,
port: Uri.parse(GlobalConfiguration().getString('base_url')).port,
path: _path + path);
return uri;
}
static String trans(String text) {
switch (text) {
case "App\\Notifications\\StatusChangedOrder":
return S.current.order_satatus_changed;
case "App\\Notifications\\NewOrder":
return S.current.new_order_from_costumer;
case "App\\Notifications\\AssignedOrder":
return S.current.your_have_an_order_assigned_to_you;
default:
return "";
}
}
}
| 0 |
mirrored_repositories/flutter_proyects_in_2020/flutter_application | mirrored_repositories/flutter_proyects_in_2020/flutter_application/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../lib/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/online_shop | mirrored_repositories/online_shop/lib/description.dart | import 'package:flutter/material.dart';
import 'package:online_shop/gen/assets.gen.dart';
import 'package:online_shop/main.dart';
import 'package:online_shop/signup_signin.dart';
import 'package:shared_preferences/shared_preferences.dart';
class DescriptionScreean extends StatefulWidget {
final SharedPreferences pref;
const DescriptionScreean({super.key, required this.pref});
@override
State<DescriptionScreean> createState() => _DescriptionScreeanState();
}
class _DescriptionScreeanState extends State<DescriptionScreean> {
int index = 0;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final des = descriptionList[index];
return Scaffold(
body: SingleChildScrollView(
child: Column(children: [
Padding(
padding: const EdgeInsets.fromLTRB(45, 60, 45, 16),
child: Image.asset(
des.image_path,
width: 250,
height: 250,
)),
Text(des.title, style: theme.textTheme.titleMedium),
const SizedBox(
height: 10,
),
Padding(
padding: const EdgeInsets.only(left: 32, right: 32),
child: Text(
des.body,
style: theme.textTheme.bodyMedium,
textAlign: TextAlign.center,
)),
const SizedBox(
height: 123,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
index > 0
? Stack(
alignment: Alignment.center,
children: [
Positioned(
bottom: 0,
child: Container(
width: 50,
height: 10,
decoration: const BoxDecoration(boxShadow: [
BoxShadow(
color: Colors.black54, blurRadius: 15),
]),
)),
InkWell(
onTap: () {
setState(() {
index--;
});
},
child: ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20),
bottomLeft: Radius.circular(20)),
child: Assets.img.icon.back.image(),
),
),
const SizedBox(
height: 10,
)
],
)
: const SizedBox(
width: 50,
height: 50,
),
const SizedBox(
width: 6,
),
Stack(
alignment: Alignment.center,
children: [
Positioned(
bottom: 0,
child: Container(
width: 50,
height: 10,
decoration: const BoxDecoration(boxShadow: [
BoxShadow(color: Colors.black54, blurRadius: 15),
]),
)),
InkWell(
onTap: () {
setState(() {
index < 2
? index++
: {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) =>
SigninScreen(key: GlobalKey<NavigatorState>(),preferences: prefs!,)))
,widget.pref.setBool('first_time', false)
};
});
},
child: ClipRRect(
borderRadius: const BorderRadius.only(
topRight: Radius.circular(20),
bottomRight: Radius.circular(20)),
child: Assets.img.icon.next.image(),
),
),
const SizedBox(
height: 10,
)
],
)
],
),
const SizedBox(
height: 73,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for (int i = 0; i < 3; i++)
Container(
width: 50,
height: 7,
color: theme.colorScheme.onPrimary
.withOpacity(i == index ? 1 : 0.5),
)
],
),
const SizedBox(
height: 89,
)
]),
),
);
}
}
List<_Description> descriptionList = [
_Description(
image_path: Assets.img.background.des1.path,
title: "Search Your Products",
body:
"Lorem ipsum dolor sit amet. Et asperiores neque rem quisquam voluptatum eos quia omnis ex reiciendis voluptates"),
_Description(
image_path: Assets.img.background.des2.path,
title: "Order Your Products",
body:
"Lorem ipsum dolor sit amet. Et asperiores neque rem quisquam voluptatum eos quia omnis ex reiciendis voluptates"),
_Description(
image_path: Assets.img.background.des3.path,
title: "Get Delivered",
body:
"Lorem ipsum dolor sit amet. Et asperiores neque rem quisquam voluptatum eos quia omnis ex reiciendis voluptates")
];
class _Description {
final String image_path;
final String title;
final String body;
_Description(
{required this.image_path, required this.title, required this.body});
}
| 0 |
mirrored_repositories/online_shop | mirrored_repositories/online_shop/lib/api.dart | import 'dart:convert';
import 'package:http/http.dart' as http;
import 'model.dart';
class UserApi{
// bool is access to site. when internet connection fail , return false
static Future<(bool,User?)> signUp(String name,String email,String pass) async{
try{
final response = await http.post(Uri.parse('https://www.starcoder.ir/add_user.php'),body: {
'name':name,
'email':email,
'pass':pass
});
Map<String,dynamic> json = jsonDecode(response.body) as Map<String,dynamic>;
if(json['status']=='ok')return (true,User.fromJson(json));
return (true,null);
} on Exception catch(ex){
return (false,null);
}
}
// String is status.
static Future<(String,User?)> signIn(String email,String pass) async{
try{
final response = await http.post(Uri.parse('https://www.starcoder.ir/loggin.php'),body: {
'email':email,
'pass':pass
});
Map<String,dynamic> json = jsonDecode(response.body) as Map<String,dynamic>;
if(json['status']=='ok')return ('ok',User.fromJson(json));
return (json['status'] as String,null);
} on Exception catch(ex){
return ('',null);
}
}
} | 0 |
mirrored_repositories/online_shop | mirrored_repositories/online_shop/lib/signup_signin.dart | import 'package:flutter/material.dart';
import 'package:online_shop/api.dart';
import 'package:online_shop/gen/assets.gen.dart';
import 'package:online_shop/splash.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:crypto/crypto.dart';
class SigninScreen extends StatelessWidget {
final SharedPreferences preferences;
const SigninScreen({super.key, required this.preferences});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final emailController = TextEditingController();
final passController = TextEditingController();
return Scaffold(
body: SingleChildScrollView(
child: Column(children: [
const SizedBox(
height: 114,
),
Text("Hello Again!", style: theme.textTheme.titleLarge),
Text(
"Welcome Back You’ve Been Missed",
style: theme.textTheme.bodyMedium,
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 29, 20, 30),
child: TextField(
controller: emailController,
cursorColor: theme.colorScheme.onPrimary,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide:
BorderSide(color: theme.colorScheme.onPrimary),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5)),
prefixIcon: const Icon(Icons.email),
label: const Text("Enter email Id"),
))),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 11),
child: TextField(
controller: passController,
cursorColor: theme.colorScheme.onPrimary,
obscureText: true,
enableSuggestions: false,
autocorrect: false,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide:
BorderSide(color: theme.colorScheme.onPrimary),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5)),
prefixIcon: const Icon(Icons.lock),
label: const Text("Enter password"),
))),
Container(
alignment: Alignment.topRight,
margin: const EdgeInsets.only(right: 9, bottom: 37),
child: TextButton(
onPressed: () {},
child: Text(
"forgot password ?",
style: theme.textTheme.bodySmall!
.copyWith(fontSize: 10, color: Colors.black),
)),
),
SizedBox(
width: 350,
height: 40,
child: ElevatedButton(
onPressed: () async {
final (status, user) = await UserApi.signIn(
emailController.text,
encryptPassword(passController.text));
if (!context.mounted) return;
if (status == '') {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Fail in access to server'),
duration: Duration(seconds: 1),
));
} else if (user == null) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(status),
duration: const Duration(seconds: 1),
));
} else {
preferences.setString('name', user.name);
preferences.setString('email', user.email);
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Signed in successfully'),
duration: Duration(seconds: 1),
));
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => const SplashScreen()));
}
},
child: const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Sign in",
),
SizedBox(
width: 12,
),
Icon(
Icons.arrow_forward,
)
]))),
const SizedBox(
height: 21,
),
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
const SizedBox(
width: 10,
),
Container(
height: 2,
width: 103,
color: Colors.black.withOpacity(0.5),
),
Text(
'Continue with',
style: theme.textTheme.titleSmall!.copyWith(fontSize: 10),
),
Container(
height: 2,
width: 103,
color: Colors.black.withOpacity(0.5),
),
const SizedBox(
width: 10,
)
]),
const SizedBox(
height: 39,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const SizedBox(),
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.25),
borderRadius: BorderRadius.circular(5)),
child: Assets.img.icon.google.image(width: 20, height: 20),
),
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.25),
borderRadius: BorderRadius.circular(5)),
child: Assets.img.icon.apple.image(width: 20, height: 20),
),
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.25),
borderRadius: BorderRadius.circular(5)),
child: Assets.img.icon.facebook.image(width: 20, height: 20),
),
const SizedBox()
],
),
const SizedBox(height: 19),
TextButton(
onPressed: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => SignupScreen(
preferences: preferences,
)));
},
child: Text('Create an Account',
style: theme.textTheme.titleSmall!.copyWith(
fontSize: 10,
color: theme.colorScheme.onPrimary,
decoration: TextDecoration.underline)),
)
]),
),
);
}
}
class SignupScreen extends StatelessWidget {
final SharedPreferences preferences;
const SignupScreen({super.key, required this.preferences});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
TextEditingController nameController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController passController = TextEditingController();
return Scaffold(
body: SingleChildScrollView(
child: Column(children: [
const SizedBox(
height: 114,
),
Text("Register", style: theme.textTheme.titleLarge),
Text(
"Sign up to get started!",
style: theme.textTheme.bodyMedium,
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 29, 20, 0),
child: TextField(
controller: nameController,
cursorColor: theme.colorScheme.onPrimary,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide:
BorderSide(color: theme.colorScheme.onPrimary),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5)),
prefixIcon: const Icon(Icons.person),
label: const Text("Enter Name"),
))),
Padding(
padding: const EdgeInsets.fromLTRB(20, 29, 20, 30),
child: TextField(
controller: emailController,
cursorColor: theme.colorScheme.onPrimary,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide:
BorderSide(color: theme.colorScheme.onPrimary),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5)),
prefixIcon: const Icon(Icons.email),
label: const Text("Enter email Id"),
))),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 11),
child: TextField(
controller: passController,
cursorColor: theme.colorScheme.onPrimary,
obscureText: true,
enableSuggestions: false,
autocorrect: false,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide:
BorderSide(color: theme.colorScheme.onPrimary),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5)),
prefixIcon: const Icon(Icons.lock),
label: const Text("Enter password"),
))),
Container(
alignment: Alignment.topRight,
margin: const EdgeInsets.only(right: 9, bottom: 37),
child: TextButton(
onPressed: () {},
child: Text(
"forgot password ?",
style: theme.textTheme.bodySmall!
.copyWith(fontSize: 10, color: Colors.black),
)),
),
SizedBox(
width: 350,
height: 40,
child: ElevatedButton(
onPressed: () async {
final (conn, user) = await UserApi.signUp(
nameController.text,
emailController.text,
encryptPassword(passController.text));
if (!context.mounted) return;
if (!conn) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Fail in access to server'),
duration: Duration(seconds: 1),
));
} else if (user == null) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Email address exists'),
duration: Duration(seconds: 1),
));
} else {
preferences.setString('name', user.name);
preferences.setString('email', user.email);
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Signed up successfully'),
duration: Duration(seconds: 1),
));
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => const SplashScreen()));
}
},
child: const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Sign up",
),
SizedBox(
width: 12,
),
Icon(
Icons.arrow_forward,
)
]))),
const SizedBox(
height: 21,
),
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
const SizedBox(
width: 10,
),
Container(
height: 2,
width: 103,
color: Colors.black.withOpacity(0.5),
),
Text(
'Continiue with',
style: theme.textTheme.titleSmall!.copyWith(fontSize: 10),
),
Container(
height: 2,
width: 103,
color: Colors.black.withOpacity(0.5),
),
const SizedBox(
width: 10,
)
]),
const SizedBox(
height: 39,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const SizedBox(),
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.25),
borderRadius: BorderRadius.circular(5)),
child: Assets.img.icon.google.image(width: 20, height: 20),
),
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.25),
borderRadius: BorderRadius.circular(5)),
child: Assets.img.icon.apple.image(width: 20, height: 20),
),
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.25),
borderRadius: BorderRadius.circular(5)),
child: Assets.img.icon.facebook.image(width: 20, height: 20),
),
const SizedBox()
],
),
const SizedBox(height: 19),
TextButton(
onPressed: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (builder) => SigninScreen(
preferences: preferences,
)));
},
child: Text('I have an Account',
style: theme.textTheme.titleSmall!.copyWith(
fontSize: 10,
color: theme.colorScheme.onPrimary,
decoration: TextDecoration.underline)),
)
]),
),
);
}
}
String encryptPassword(String pass) {
final bytes = utf8.encode(pass);
final hash = sha256.convert(bytes);
return hash.toString();
}
| 0 |
mirrored_repositories/online_shop | mirrored_repositories/online_shop/lib/splash.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:online_shop/gen/assets.gen.dart';
import 'package:online_shop/signup_signin.dart';
class SplashScreen extends StatelessWidget {
const SplashScreen({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
ValueNotifier<int> counter = ValueNotifier(0);
Timer.periodic(const Duration(milliseconds: 200),
(timer) => counter.value = (counter.value + 1) % 4);
return Scaffold(
body: Center(
child: Column(
children: [
const SizedBox(
height: 266,
),
Text(
'Hey Steve',
style: theme.textTheme.titleLarge,
),
const SizedBox(
height: 16,
),
Text(
'Wait for loading products',
style: theme.textTheme.bodyLarge,
),
const SizedBox(
height: 35,
),
ValueListenableBuilder<int>(
valueListenable: counter,
builder: (context, value, child) {
switch (value) {
case 0:
return Assets.img.icon.progress1
.image(width: 100, height: 100);
case 1:
return Assets.img.icon.progress2
.image(width: 100, height: 100);
case 2:
return Assets.img.icon.progress3
.image(width: 100, height: 100);
default:
return Assets.img.icon.progress4
.image(width: 100, height: 100);
}
})
],
),
));
}
}
| 0 |
mirrored_repositories/online_shop | mirrored_repositories/online_shop/lib/model.dart | class User{
String name = "";
String email = "";
User.fromJson(Map<String,dynamic> json):name=json['name'],email=json['email'];
} | 0 |
mirrored_repositories/online_shop | mirrored_repositories/online_shop/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:online_shop/description.dart';
import 'package:online_shop/gen/fonts.gen.dart';
import 'package:online_shop/signup_signin.dart';
import 'package:online_shop/splash.dart';
import 'package:shared_preferences/shared_preferences.dart';
SharedPreferences? prefs;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
prefs = await SharedPreferences.getInstance();
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
statusBarColor: Colors.white,
statusBarIconBrightness: Brightness.dark,
systemNavigationBarColor: Colors.white,
systemNavigationBarIconBrightness: Brightness.dark));
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({
super.key,
});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
const Color onPrimary = Color(0xff4B61DC);
const Color primary = Color(0xffF5F5F5);
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
onPrimary: onPrimary,
primary: primary),
useMaterial3: true,
scaffoldBackgroundColor: primary,
elevatedButtonTheme: ElevatedButtonThemeData(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(const Color(0xff217085)),
shape: MaterialStateProperty.all(RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5))))),
textTheme: TextTheme(
titleMedium: const TextStyle(
color: onPrimary,
fontFamily: FontFamily.poppins,
fontSize: 20,
fontWeight: FontWeight.w500,
),
titleLarge: const TextStyle(
color: onPrimary,
fontFamily: FontFamily.poppins,
fontSize: 32,
fontWeight: FontWeight.w500,
),
bodySmall: TextStyle(
fontFamily: FontFamily.poppins,
fontSize: 8,
fontWeight: FontWeight.w200,
color: Colors.black.withOpacity(.5),
),
bodyMedium: TextStyle(
fontFamily: FontFamily.poppins,
fontSize: 12,
fontWeight: FontWeight.w200,
color: Colors.black.withOpacity(.5),
),
bodyLarge: const TextStyle(
fontFamily: FontFamily.poppins,
fontSize: 15,
fontWeight: FontWeight.w200,
color: Colors.black,
),
)),
home: MainScreen(
preferences: prefs!,
),
);
}
}
class MainScreen extends StatelessWidget {
final SharedPreferences preferences;
MainScreen({super.key, required this.preferences});
final GlobalKey<NavigatorState> _screenKey = GlobalKey();
bool snackbarIsActive = false;
Future<bool> Function() _onWillPop(BuildContext context) {
return () async {
NavigatorState navigatorState = _screenKey.currentState!;
if (!navigatorState.canPop()) {
if(snackbarIsActive) {
return true;
}
snackbarIsActive = true;
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(duration: Duration(seconds: 1),
content: Text('press back key again to exit')
)).closed.then((value) => snackbarIsActive = false);
return false;
}
return true;
};
}
@override
Widget build(BuildContext context) {
Widget screen = DescriptionScreean(pref: preferences);
if(preferences.getBool('first_time')!=null){
if(preferences.getString('name')!=null){
screen = const SplashScreen();
}else{
screen = SigninScreen(preferences:preferences);
}
}
return WillPopScope(
onWillPop: _onWillPop(context),
child: Navigator(
key: _screenKey,
onGenerateRoute: (settings) =>
MaterialPageRoute(builder: (context) => screen),
));
}
}
| 0 |
mirrored_repositories/online_shop/lib | mirrored_repositories/online_shop/lib/gen/assets.gen.dart | /// GENERATED CODE - DO NOT MODIFY BY HAND
/// *****************************************************
/// FlutterGen
/// *****************************************************
// coverage:ignore-file
// ignore_for_file: type=lint
// ignore_for_file: directives_ordering,unnecessary_import,implicit_dynamic_list_literal,deprecated_member_use
import 'package:flutter/widgets.dart';
class $AssetsImgGen {
const $AssetsImgGen();
$AssetsImgBackgroundGen get background => const $AssetsImgBackgroundGen();
$AssetsImgIconGen get icon => const $AssetsImgIconGen();
}
class $AssetsImgBackgroundGen {
const $AssetsImgBackgroundGen();
/// File path: assets/img/background/background.png
AssetGenImage get background =>
const AssetGenImage('assets/img/background/background.png');
/// File path: assets/img/background/des1.png
AssetGenImage get des1 =>
const AssetGenImage('assets/img/background/des1.png');
/// File path: assets/img/background/des2.png
AssetGenImage get des2 =>
const AssetGenImage('assets/img/background/des2.png');
/// File path: assets/img/background/des3.png
AssetGenImage get des3 =>
const AssetGenImage('assets/img/background/des3.png');
/// List of all assets
List<AssetGenImage> get values => [background, des1, des2, des3];
}
class $AssetsImgIconGen {
const $AssetsImgIconGen();
/// File path: assets/img/icon/apple.png
AssetGenImage get apple => const AssetGenImage('assets/img/icon/apple.png');
/// File path: assets/img/icon/back.png
AssetGenImage get back => const AssetGenImage('assets/img/icon/back.png');
/// File path: assets/img/icon/facebook.png
AssetGenImage get facebook =>
const AssetGenImage('assets/img/icon/facebook.png');
/// File path: assets/img/icon/google.png
AssetGenImage get google => const AssetGenImage('assets/img/icon/google.png');
/// File path: assets/img/icon/next.png
AssetGenImage get next => const AssetGenImage('assets/img/icon/next.png');
/// File path: assets/img/icon/progress1.png
AssetGenImage get progress1 =>
const AssetGenImage('assets/img/icon/progress1.png');
/// File path: assets/img/icon/progress2.png
AssetGenImage get progress2 =>
const AssetGenImage('assets/img/icon/progress2.png');
/// File path: assets/img/icon/progress3.png
AssetGenImage get progress3 =>
const AssetGenImage('assets/img/icon/progress3.png');
/// File path: assets/img/icon/progress4.png
AssetGenImage get progress4 =>
const AssetGenImage('assets/img/icon/progress4.png');
/// List of all assets
List<AssetGenImage> get values => [
apple,
back,
facebook,
google,
next,
progress1,
progress2,
progress3,
progress4
];
}
class Assets {
Assets._();
static const $AssetsImgGen img = $AssetsImgGen();
}
class AssetGenImage {
const AssetGenImage(this._assetName);
final String _assetName;
Image image({
Key? key,
AssetBundle? bundle,
ImageFrameBuilder? frameBuilder,
ImageErrorWidgetBuilder? errorBuilder,
String? semanticLabel,
bool excludeFromSemantics = false,
double? scale,
double? width,
double? height,
Color? color,
Animation<double>? opacity,
BlendMode? colorBlendMode,
BoxFit? fit,
AlignmentGeometry alignment = Alignment.center,
ImageRepeat repeat = ImageRepeat.noRepeat,
Rect? centerSlice,
bool matchTextDirection = false,
bool gaplessPlayback = false,
bool isAntiAlias = false,
String? package,
FilterQuality filterQuality = FilterQuality.low,
int? cacheWidth,
int? cacheHeight,
}) {
return Image.asset(
_assetName,
key: key,
bundle: bundle,
frameBuilder: frameBuilder,
errorBuilder: errorBuilder,
semanticLabel: semanticLabel,
excludeFromSemantics: excludeFromSemantics,
scale: scale,
width: width,
height: height,
color: color,
opacity: opacity,
colorBlendMode: colorBlendMode,
fit: fit,
alignment: alignment,
repeat: repeat,
centerSlice: centerSlice,
matchTextDirection: matchTextDirection,
gaplessPlayback: gaplessPlayback,
isAntiAlias: isAntiAlias,
package: package,
filterQuality: filterQuality,
cacheWidth: cacheWidth,
cacheHeight: cacheHeight,
);
}
ImageProvider provider({
AssetBundle? bundle,
String? package,
}) {
return AssetImage(
_assetName,
bundle: bundle,
package: package,
);
}
String get path => _assetName;
String get keyName => _assetName;
}
| 0 |
mirrored_repositories/online_shop/lib | mirrored_repositories/online_shop/lib/gen/fonts.gen.dart | /// GENERATED CODE - DO NOT MODIFY BY HAND
/// *****************************************************
/// FlutterGen
/// *****************************************************
// coverage:ignore-file
// ignore_for_file: type=lint
// ignore_for_file: directives_ordering,unnecessary_import,implicit_dynamic_list_literal,deprecated_member_use
class FontFamily {
FontFamily._();
/// Font family: Poppins
static const String poppins = 'Poppins';
}
| 0 |
mirrored_repositories/online_shop | mirrored_repositories/online_shop/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:online_shop/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/github-user-info-app | mirrored_repositories/github-user-info-app/lib/responsive.dart | import 'package:flutter/material.dart';
class Responsive extends StatelessWidget {
const Responsive({super.key, required this.desktop, required this.largeMobile,required this.mobile,required this.tablet, this.extraLargeScreen});
final Widget desktop;
final Widget? largeMobile;
final Widget mobile;
final Widget? tablet;
final Widget? extraLargeScreen;
static bool isMobile(BuildContext context){
return MediaQuery.sizeOf(context).width <= 500;
}
static bool isLargeMobile(BuildContext context){
return MediaQuery.sizeOf(context).width <=700;
}
static bool isTablet(BuildContext context){
return MediaQuery.sizeOf(context).width < 1080;
}
static bool isDesktop(BuildContext context){
return MediaQuery.sizeOf(context).width > 1024;
}
static bool isExtraLargeScreen(BuildContext context){
return MediaQuery.sizeOf(context).width > 1400;
}
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
if (size.width > 1400 && extraLargeScreen!=null) {
return extraLargeScreen!;
}
else if (size.width >= 1080) {
return desktop;
} else if (size.width >= 700 && tablet != null) {
return tablet!;
} else if (size.width >= 500 && largeMobile != null) {
return largeMobile!;
} else {
return mobile;
}
}
}
| 0 |
mirrored_repositories/github-user-info-app | mirrored_repositories/github-user-info-app/lib/constants.dart | import 'package:flutter/material.dart';
const primaryColor = Colors.white;
const secondaryColor = Color(0xFF242430);
const darkColor = Color(0xFF191923);
const bodyTextColor = Color(0xFF8B8B8D);
const bgColor = Color(0xFF000515);
const defaultPadding = 20.0;
| 0 |
mirrored_repositories/github-user-info-app | mirrored_repositories/github-user-info-app/lib/main.dart | import 'package:flutter/material.dart';
import 'package:github_user_info_app/components/list_providers.dart';
import 'package:github_user_info_app/pages/login_page.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => ListProvider()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
themeMode: ThemeMode.dark,
darkTheme: ThemeData(brightness: Brightness.dark),
theme: ThemeData(fontFamily: 'poppins'),
home: const LoginPage(),
),
);
}
}
| 0 |
mirrored_repositories/github-user-info-app/lib | mirrored_repositories/github-user-info-app/lib/pages/home_page.dart | import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../components/Homepage_components/glassCard1/glasscard_details.dart';
import '../components/app_bar.dart';
import '../components/Homepage_components/profile_details.dart';
import 'package:shared_preferences/shared_preferences.dart';
Map<dynamic, dynamic> mapResponse = {};
class HomePage extends StatefulWidget {
HomePage({
super.key,
});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String? nameValue;
// final baseUrl = "https://api.github.com/users/";
Future<void> userdetailscall(String? nameValue) async {
http.Response response;
final SharedPreferences prefs = await SharedPreferences.getInstance();
nameValue = prefs.getString('names');
print(nameValue);
response = await http.get(
Uri.parse("http://api.github.com/users/$nameValue"),
);
print(response.body);
if (response.statusCode == 200) {
setState(() {
mapResponse = json.decode(response.body);
});
}
}
@override
void initState() {
getNames();
super.initState();
userdetailscall(nameValue);
}
void getNames() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
nameValue = prefs.getString('names');
setState(() {});
}
@override
Widget build(BuildContext context) {
String imgUrl = "https://github.com/$nameValue.png";
return Scaffold(
body: Column(
children: [
MyAppBar(),
// nameValue == null ? const Text("No names saved") : Text(nameValue!),
profileDetails(imgUrl),
glassCard1(),
],
),
);
}
}
| 0 |
mirrored_repositories/github-user-info-app/lib | mirrored_repositories/github-user-info-app/lib/pages/fav_page.dart | import 'package:flutter/material.dart';
import 'package:github_user_info_app/components/app_bar.dart';
import 'package:github_user_info_app/components/glassmorphism.dart';
class FavRepoPage extends StatefulWidget {
const FavRepoPage({Key? key});
@override
_FavRepoPageState createState() => _FavRepoPageState();
}
class _FavRepoPageState extends State<FavRepoPage> {
List<Map<String, dynamic>> favRepoResponse = []; // Initialize an empty list
Future<void> fetchFavRepos() async {
// Simulate fetching favorited repositories from an API or any other data source
// Replace this with your actual logic to fetch the data
await Future.delayed(Duration(seconds: 2));
// Example data structure for starred repositories
final List<Map<String, dynamic>> dummyFavRepos = [
{'name': 'Starred Repo 1'},
{'name': 'Starred Repo 2'},
// Add more repositories as needed
];
setState(() {
favRepoResponse = dummyFavRepos;
});
}
@override
void initState() {
fetchFavRepos();
super.initState();
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: [
const MyAppBar(),
const Text(
"Starred Repositories",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w800,
),
),
Column(
children: favRepoResponse.map((repo) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 20,
),
child: Glassmorphism(
blur: 15,
opacity: 0.2,
radius: 20,
child: Container(
height: 60,
width: 750,
padding: const EdgeInsets.only(top: 4, left: 10),
child: ListTile(
title: Text(
repo['name'].toString(),
),
),
),
),
);
}).toList(),
),
],
),
);
}
}
| 0 |
mirrored_repositories/github-user-info-app/lib | mirrored_repositories/github-user-info-app/lib/pages/repos_page.dart | import 'package:flutter/material.dart';
import 'package:github_user_info_app/components/app_bar.dart';
import 'package:github_user_info_app/components/glassmorphism.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class RepoPage extends StatefulWidget {
RepoPage({Key? key});
@override
State<RepoPage> createState() => _RepoPageState();
}
class _RepoPageState extends State<RepoPage> {
List<Map<String, dynamic>> repoResponse = [];
Future<void> repocall() async {
http.Response response;
String url = "https://api.github.com/users/Naincy04/repos";
response = await http.get(
Uri.parse(url),
);
if (response.statusCode == 200) {
setState(() {
repoResponse =
List<Map<String, dynamic>>.from(json.decode(response.body));
print(repoResponse);
});
}
}
@override
void initState() {
repocall();
super.initState();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
const MyAppBar(),
const Text(
"Repositories",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w700,
),
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: repoResponse.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 20,
),
child: Glassmorphism(
blur: 15,
opacity: 0.2,
radius: 20,
child: Container(
height: MediaQuery.of(context).size.height * 0.2,
width: 750,
padding: const EdgeInsets.symmetric(
vertical: 4,
horizontal: 10,
),
child: ListTile(
title: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
repoResponse[index]['name'].toString(),
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
),
subtitle: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
repoResponse[index]['description'].toString(),
),
),
),
),
),
);
},
),
),
],
);
}
}
| 0 |
mirrored_repositories/github-user-info-app/lib | mirrored_repositories/github-user-info-app/lib/pages/accounts_page.dart | import 'package:flutter/material.dart';
import 'package:github_user_info_app/components/app_bar.dart';
import '../components/glassmorphism.dart';
class AccountPage extends StatelessWidget {
const AccountPage({super.key});
@override
Widget build(BuildContext context) {
String imgUrl = "https://github.com/Naincy04.png";
return Column(
children: [
const MyAppBar(),
const Text(
"About",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w800,
),
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 20,
),
child: Glassmorphism(
blur: 15,
opacity: 0.2,
radius: 20,
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.3,
width: 750,
child: const Column(
children: [
Padding(
padding:
EdgeInsets.symmetric(vertical: 16, horizontal: 1)),
Text(
"Dear Users \nThis is a simple app to get the details of a github user. \nYou can get the details of the user by entering the username in the search bar. \nYou can also get the details of the repositories and the starred repositories of the user. \nYou can also submit the feedback of the app. \nHope you like the app. \nThank You.",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
],
),
),
),
),
const SizedBox(
height: 5,
),
Glassmorphism(
blur: 15,
opacity: 0.2,
radius: 20,
child: Container(
padding: const EdgeInsets.all(20),
height: 60,
width: 350,
child: const Text(
"Submit Feedback",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
),
textAlign: TextAlign.center,
),
)),
],
);
}
}
| 0 |
mirrored_repositories/github-user-info-app/lib | mirrored_repositories/github-user-info-app/lib/pages/login_page.dart | import 'package:flutter/material.dart';
import 'package:github_user_info_app/components/nav_bar.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LoginPage extends StatefulWidget {
const LoginPage({super.key});
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
@override
void initState() {
super.initState();
}
final TextEditingController _name = TextEditingController();
@override
Widget build(BuildContext context) {
final formKey = GlobalKey<FormState>();
return Material(
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(right: 280.0, top: 50.0),
child: Image.asset("assets/images/Ellipse 1.png"),
),
Padding(
padding: const EdgeInsets.only(left: 285.0, top: 2.5),
child: Image.asset("assets/images/Ellipse 2.png"),
),
Image.asset(
"assets/images/github_icon.png",
width: 230,
height: 145,
),
const Text(
"Welcome",
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
const SizedBox(
height: 10.0,
),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 32.0, vertical: 16.0),
child: Form(
key: formKey,
child: Column(
children: [
TextFormField(
controller: _name,
decoration: const InputDecoration(
hintText: "Enter Username",
label: Text("Username"),
),
validator: (String? value) {
if (value != null && value.isEmpty) {
return "Username can't be empty";
}
return null;
}),
const SizedBox(
height: 25.0,
),
ElevatedButton(
onPressed: () async {
if (formKey.currentState!.validate()) {
{
String uname = _name.text.toString();
getValue(uname);
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => const NavBar()),
);
}
}
},
style: TextButton.styleFrom(
minimumSize: const Size(110, 40),
backgroundColor: const Color(0xFFFF7373),
),
child: const Text("Submit"),
),
const SizedBox(
height: 180.0,
),
],
),
),
),
],
),
);
}
Future<void> getValue(nameValue) async {
final SharedPreferences pref = await SharedPreferences.getInstance();
pref.setString('names', nameValue);
}
}
| 0 |
mirrored_repositories/github-user-info-app/lib | mirrored_repositories/github-user-info-app/lib/components/glass_cards.dart | import 'package:flutter/cupertino.dart';
import 'glassmorphism.dart';
class GlassCards extends StatelessWidget {
const GlassCards({
super.key,
});
@override
Widget build(BuildContext context) {
return Stack(
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20,
),
child: Glassmorphism(
blur: 15,
opacity: 0.2,
radius: 20,
child: Container(
height: 250,
padding: const EdgeInsets.all(20),
),
),
),
],
);
}
}
| 0 |
mirrored_repositories/github-user-info-app/lib | mirrored_repositories/github-user-info-app/lib/components/nav_bar.dart | import 'package:flutter/material.dart';
import 'package:github_user_info_app/pages/accounts_page.dart';
import 'package:github_user_info_app/pages/fav_page.dart';
import '../pages/home_page.dart';
import '../pages/repos_page.dart';
class NavBar extends StatefulWidget {
const NavBar({Key? key}) : super(key: key);
@override
State<NavBar> createState() => _NavBarState();
}
class _NavBarState extends State<NavBar> {
@override
void initState() {
pageController = PageController(initialPage: _selectedIndex);
super.initState();
}
int _selectedIndex = 0;
late PageController pageController;
final List<Widget> pages = [
HomePage(),
RepoPage(),
const FavRepoPage(),
const AccountPage(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
controller: pageController,
children: [pages[_selectedIndex]],
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
showSelectedLabels: false,
showUnselectedLabels: false,
backgroundColor: Color.fromARGB(255, 31, 30, 30),
elevation: 10.0,
items: [
_buildNavBarItem(Icons.home, 0, 'Home'),
_buildNavBarItem(Icons.folder_copy_sharp, 1, 'Repos'),
_buildNavBarItem(Icons.favorite, 2, 'Favorites'),
_buildNavBarItem(Icons.account_circle_sharp, 4, 'Account'),
],
currentIndex: _selectedIndex,
onTap: (index) {
setState(() {
_selectedIndex = index;
});
pageController.animateToPage(
_selectedIndex,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutQuad,
);
},
),
);
}
BottomNavigationBarItem _buildNavBarItem(
IconData icon, int index, String label) {
return BottomNavigationBarItem(
icon: Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Icon(
icon,
color: _selectedIndex == index ? Color(0xFFFF7373) : Colors.grey,
),
),
label: label,
);
}
}
| 0 |
mirrored_repositories/github-user-info-app/lib | mirrored_repositories/github-user-info-app/lib/components/list_providers.dart | import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class ListProvider extends ChangeNotifier {
String stringResponse = "";
Map<dynamic, dynamic> mapResponse = {};
Future userdetailscall() async {
http.Response response;
response = await http.get(
Uri.parse("https://api.github.com/users/Naincy04"),
);
if (response.statusCode == 200) {
// stringResponse = response.body;
mapResponse = json.decode(response.body);
}
}
}
| 0 |
mirrored_repositories/github-user-info-app/lib | mirrored_repositories/github-user-info-app/lib/components/glassmorphism.dart | import 'dart:ui';
import 'package:flutter/material.dart';
class Glassmorphism extends StatelessWidget {
final double blur;
final double opacity;
final double radius;
final Widget child;
const Glassmorphism({
Key? key,
required this.blur,
required this.opacity,
required this.radius,
required this.child,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(radius),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: blur, sigmaY: blur),
child: Container(
decoration: BoxDecoration(
color: Colors.white.withOpacity(opacity),
borderRadius: BorderRadius.all(Radius.circular(radius)),
border: Border.all(
width: 1.5,
color: Colors.white.withOpacity(0.2),
),
),
child: child,
),
),
);
}
}
| 0 |
mirrored_repositories/github-user-info-app/lib | mirrored_repositories/github-user-info-app/lib/components/app_bar.dart | import 'package:flutter/material.dart';
import 'package:github_user_info_app/pages/login_page.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MyAppBar extends StatefulWidget {
const MyAppBar({Key? key});
@override
State<MyAppBar> createState() => _MyAppBarState();
}
class _MyAppBarState extends State<MyAppBar> {
String? nameValue = "";
void getNames() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
nameValue = prefs.getString('names');
setState(() {});
}
@override
void initState() {
getNames();
super.initState();
}
// Logout function
void logout() async {
print("Exit clicked");
final SharedPreferences prefs = await SharedPreferences.getInstance();
// Clear user-related data or authentication token
prefs.clear();
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => const LoginPage()),
);
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.only(top: 19, bottom: 0.1),
child: Image.asset(
"assets/images/github_icon.png",
height: 75,
width: 85,
),
),
Container(
padding: const EdgeInsets.only(bottom: 0.1, top: 20),
child: Text(
nameValue!,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.w800,
),
),
)
],
),
Row(
children: [
Container(
padding: const EdgeInsets.only(right: 15, bottom: 0.1, top: 22),
child: const Icon(Icons.notifications_outlined),
),
const SizedBox(
width: 1,
),
Container(
padding: const EdgeInsets.only(right: 15, bottom: 0.1, top: 19),
width: 95,
child: ElevatedButton(
onPressed: logout,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFFFF7373),
),
child: const Text("Exit"),
),
)
],
),
],
);
}
}
| 0 |
mirrored_repositories/github-user-info-app/lib/components | mirrored_repositories/github-user-info-app/lib/components/Homepage_components/profile_details.dart | import 'package:flutter/material.dart';
import '../../pages/home_page.dart';
Row profileDetails(String imgUrl) {
return Row(
children: [
const Padding(
padding: EdgeInsets.only(left: 10.0, top: 0.25),
),
CircleAvatar(
radius: 70,
backgroundImage: NetworkImage(imgUrl),
),
const SizedBox(
width: 15,
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(mapResponse['name'].toString(),
style:
const TextStyle(fontWeight: FontWeight.w400, fontSize: 25)),
const SizedBox(
height: 10,
),
Row(
children: [
const Icon(
Icons.people,
size: 20,
),
const SizedBox(
width: 10,
),
Row(
children: [
Text(
mapResponse['followers'].toString(),
style: const TextStyle(
fontWeight: FontWeight.w400, fontSize: 14),
),
const SizedBox(
width: 5,
),
const Text("Followers"),
],
),
const SizedBox(
width: 10,
),
Row(
children: [
Text(
mapResponse['following'].toString(),
style: const TextStyle(
fontWeight: FontWeight.w400, fontSize: 14),
),
const SizedBox(
width: 5,
),
const Text("Following"),
],
),
const SizedBox(
width: 10,
),
],
),
],
),
],
);
}
| 0 |
mirrored_repositories/github-user-info-app/lib/components/Homepage_components | mirrored_repositories/github-user-info-app/lib/components/Homepage_components/glassCard1/card3.dart | import 'package:flutter/cupertino.dart';
import '../../../pages/home_page.dart';
Row card3() {
return Row(
children: [
const Padding(
padding: EdgeInsets.symmetric(
horizontal: 35.0,
vertical: 25.0,
),
child: Text(
"Total commits : ",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
),
Text(
mapResponse['reviews'].toString(),
style: const TextStyle(fontWeight: FontWeight.w400, fontSize: 14),
)
],
);
}
| 0 |
mirrored_repositories/github-user-info-app/lib/components/Homepage_components | mirrored_repositories/github-user-info-app/lib/components/Homepage_components/glassCard1/card1.dart | import 'package:flutter/cupertino.dart';
import '../../../pages/home_page.dart';
Row card1() {
return Row(
children: [
const Padding(
padding: EdgeInsets.symmetric(
horizontal: 35.0,
vertical: 25.0,
),
child: Text(
"Total repositories : ",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
),
Text(
mapResponse['public_repos'].toString(),
style: const TextStyle(fontWeight: FontWeight.w400, fontSize: 14),
)
],
);
}
| 0 |
mirrored_repositories/github-user-info-app/lib/components/Homepage_components | mirrored_repositories/github-user-info-app/lib/components/Homepage_components/glassCard1/card4.dart | import 'package:flutter/cupertino.dart';
import '../../../pages/home_page.dart';
Row card4() {
return Row(
children: [
const Padding(
padding: EdgeInsets.symmetric(
horizontal: 35.0,
vertical: 3.0,
),
child: Text(
"Total pull requests : ",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
),
Text(
mapResponse['public_repos'].toString(),
style: const TextStyle(fontWeight: FontWeight.w400, fontSize: 14),
)
],
);
}
| 0 |
mirrored_repositories/github-user-info-app/lib/components/Homepage_components | mirrored_repositories/github-user-info-app/lib/components/Homepage_components/glassCard1/card2.dart | import 'package:flutter/cupertino.dart';
import '../../../pages/home_page.dart';
Row card2() {
return Row(
children: [
const Padding(
padding: EdgeInsets.symmetric(
horizontal: 35.0,
vertical: 2.0,
),
child: Text(
"Total public gists : ",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
),
Text(
mapResponse['public_gists'].toString(),
style: const TextStyle(fontWeight: FontWeight.w400, fontSize: 14),
)
],
);
}
| 0 |
mirrored_repositories/github-user-info-app/lib/components/Homepage_components | mirrored_repositories/github-user-info-app/lib/components/Homepage_components/glassCard1/card5.dart | import 'package:flutter/cupertino.dart';
import '../../../pages/home_page.dart';
Row card5() {
return Row(
children: [
const Padding(
padding: EdgeInsets.symmetric(
horizontal: 35.0,
vertical: 25.0,
),
child: Text(
"Total Stars earned : ",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
),
Text(
mapResponse['public_repos'].toString(),
style: const TextStyle(fontWeight: FontWeight.w400, fontSize: 14),
)
],
);
}
| 0 |
mirrored_repositories/github-user-info-app/lib/components/Homepage_components | mirrored_repositories/github-user-info-app/lib/components/Homepage_components/glassCard1/glasscard_details.dart | import 'package:flutter/cupertino.dart';
import '../../../pages/home_page.dart';
import '../../glass_cards.dart';
import 'card1.dart';
import 'card2.dart';
import 'card3.dart';
import 'card4.dart';
import 'card5.dart';
Column glassCard1() {
return Column(
children: [
const Padding(
padding: EdgeInsets.only(top: 6.0),
),
const Text(
"Bio",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w800,
),
),
const SizedBox(
height: 5,
),
Text(
mapResponse['bio'].toString(),
style: const TextStyle(fontWeight: FontWeight.w400, fontSize: 14),
),
const SizedBox(
height: 25,
),
const Text(
"Github stats",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w800,
),
),
const SizedBox(
height: 10,
),
Stack(
children: [
const GlassCards(),
Column(
children: [
card1(),
card2(),
card3(),
card4(),
card5(),
],
),
],
),
],
);
}
| 0 |
mirrored_repositories/github-user-info-app/lib | mirrored_repositories/github-user-info-app/lib/config/responsive.dart | import 'package:flutter/material.dart';
class Responsive extends StatelessWidget {
final Widget mobile;
final Widget tablet;
final Widget desktop;
const Responsive({
required Key key,
required this.mobile,
required this.tablet,
required this.desktop,
}) : super(key: key);
// This isMobile, isTablet, isDesktop
static bool isMobile(BuildContext context) =>
MediaQuery.of(context).size.width < 400;
static bool isTablet(BuildContext context) =>
MediaQuery.of(context).size.width < 600 &&
MediaQuery.of(context).size.width >= 400;
static bool isDesktop(BuildContext context) =>
MediaQuery.of(context).size.width >= 600;
@override
Widget build(BuildContext context) {
final Size _size = MediaQuery.of(context).size;
// If our width is more than 1200 then we consider it a desktop
if (_size.width >= 600) {
return desktop;
}
// If width it less then 1200 and more then 768 we consider it as tablet
else if (_size.width >= 400) {
return tablet;
}
// Or less then that we called it mobile
else {
return mobile;
}
}
}
| 0 |
mirrored_repositories/github-user-info-app/lib | mirrored_repositories/github-user-info-app/lib/config/size_config.dart | import 'package:flutter/material.dart';
class SizeConfig {
static late MediaQueryData _mediaQueryData;
static late double screenWidth;
static late double screenHeight;
static late double blockSizeHorizontal;
static late double blockSizeVertical;
void init(BuildContext context) {
_mediaQueryData = MediaQuery.of(context);
screenWidth = _mediaQueryData.size.width;
screenHeight = _mediaQueryData.size.height;
blockSizeHorizontal = screenWidth / 100;
blockSizeVertical = screenHeight / 100;
}
}
| 0 |
mirrored_repositories/github-user-info-app | mirrored_repositories/github-user-info-app/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:github_user_info_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutterzon_provider | mirrored_repositories/flutterzon_provider/lib/router.dart | import 'package:amazon_clone_flutter/common/widgets/bottom_bar.dart';
import 'package:amazon_clone_flutter/features/account/screens/account_screen.dart';
import 'package:amazon_clone_flutter/features/account/screens/search_orders_screen.dart';
import 'package:amazon_clone_flutter/features/account/screens/wish_list_screen.dart';
import 'package:amazon_clone_flutter/features/account/screens/your_orders.dart';
import 'package:amazon_clone_flutter/features/address/screens/address_screen.dart';
import 'package:amazon_clone_flutter/features/address/screens/address_screen_buy_now.dart';
import 'package:amazon_clone_flutter/features/admin/screens/add_product_screen.dart';
import 'package:amazon_clone_flutter/features/admin/screens/bottom_bar.dart';
import 'package:amazon_clone_flutter/features/auth/screens/auth_screen.dart';
import 'package:amazon_clone_flutter/features/cart/screens/cart_screen.dart';
import 'package:amazon_clone_flutter/features/home/screens/category_deals_screen.dart';
import 'package:amazon_clone_flutter/features/home/screens/home_screen.dart';
import 'package:amazon_clone_flutter/features/menu/screens/menu_screen.dart';
import 'package:amazon_clone_flutter/features/order_details/screens/tracking_details_sceen.dart';
import 'package:amazon_clone_flutter/features/product_details/screens/product_details_screen.dart';
import 'package:amazon_clone_flutter/features/search/screens/search_screen.dart';
import 'package:amazon_clone_flutter/models/product.dart';
import 'package:flutter/material.dart';
import 'features/account/screens/browsing_history.dart';
import 'features/admin/screens/category_products_screen_admin.dart';
import 'features/order_details/screens/order_details.dart';
import 'models/order.dart';
Route<dynamic> generateRoute(RouteSettings routeSettings) {
switch (routeSettings.name) {
case AuthScreen.routeName:
return MaterialPageRoute(
builder: (_) => const AuthScreen(), settings: routeSettings);
case HomeScreen.routeName:
return MaterialPageRoute(
builder: (_) => const HomeScreen(), settings: routeSettings);
case BottomBar.routeName:
return MaterialPageRoute(
builder: (_) => const BottomBar(), settings: routeSettings);
case AddProductScreen.routeName:
return MaterialPageRoute(
builder: (_) => const AddProductScreen(), settings: routeSettings);
case AccountScreen.routeName:
return MaterialPageRoute(
builder: (_) => const AccountScreen(), settings: routeSettings);
case MenuScreen.routeName:
return MaterialPageRoute(
builder: (_) => const MenuScreen(), settings: routeSettings);
case YourOrders.routeName:
return MaterialPageRoute(
builder: (_) => const YourOrders(), settings: routeSettings);
case BrowsingHistory.routeName:
return MaterialPageRoute(
builder: (_) => const BrowsingHistory(), settings: routeSettings);
case AdminScreen.routeName:
return MaterialPageRoute(
builder: (_) => const AdminScreen(), settings: routeSettings);
case WishListScreen.routeName:
return MaterialPageRoute(
builder: (_) => const WishListScreen(), settings: routeSettings);
case CartScreen.routeName:
return MaterialPageRoute(
builder: (_) => const CartScreen(), settings: routeSettings);
case CategoryProductsScreenAdmin.routeName:
var category = routeSettings.arguments as String;
return MaterialPageRoute(
builder: (_) => CategoryProductsScreenAdmin(
category: category,
),
settings: routeSettings);
case AddressScreenBuyNow.routeName:
var product = routeSettings.arguments as Product;
return MaterialPageRoute(
builder: (_) => AddressScreenBuyNow(
product: product,
),
settings: routeSettings);
case TrackingDetailsScreen.routeName:
Order order = routeSettings.arguments as Order;
return MaterialPageRoute(
builder: (_) => TrackingDetailsScreen(order: order),
settings: routeSettings);
case AddressScreen.routeName:
var totalAmount = routeSettings.arguments as String;
return MaterialPageRoute(
builder: (_) => AddressScreen(totalAmount: totalAmount),
settings: routeSettings);
case SearchScreen.routeName:
var searchQuery = routeSettings.arguments as String;
return MaterialPageRoute(
builder: (_) => SearchScreen(
searchQuery: searchQuery,
),
settings: routeSettings);
case SearchOrderScreeen.routeName:
var orderQuery = routeSettings.arguments as String;
return MaterialPageRoute(
builder: (_) => SearchOrderScreeen(orderQuery: orderQuery),
settings: routeSettings);
case OrderDetailsScreen.routeName:
var order = routeSettings.arguments as Order;
return MaterialPageRoute(
builder: (_) => OrderDetailsScreen(
order: order,
),
settings: routeSettings);
case ProductDetailsScreen.routeName:
Map<String, dynamic> arguments =
routeSettings.arguments as Map<String, dynamic>;
Product product = arguments['product'];
String deliveryDate = arguments['deliveryDate'];
return MaterialPageRoute(
builder: (_) => ProductDetailsScreen(
arguments: {'product': product, 'deliveryDate': deliveryDate},
),
settings: routeSettings);
case CategoryDealsScreen.routeName:
var category = routeSettings.arguments as String;
return MaterialPageRoute(
builder: (_) => CategoryDealsScreen(
category: category,
),
settings: routeSettings);
default:
return MaterialPageRoute(
builder: (_) => const Scaffold(
body: Center(child: Text('Screen does not exist!')),
));
}
}
| 0 |
mirrored_repositories/flutterzon_provider | mirrored_repositories/flutterzon_provider/lib/main.dart | import 'package:amazon_clone_flutter/constants/app_theme.dart';
import 'package:amazon_clone_flutter/features/splash_screen/splash_screen.dart';
import 'package:amazon_clone_flutter/providers/cart_offers_provider.dart';
import 'package:amazon_clone_flutter/providers/screen_number_provider.dart';
import 'package:amazon_clone_flutter/providers/user_provider.dart';
import 'package:amazon_clone_flutter/router.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:provider/provider.dart';
import 'constants/utils.dart';
Future main() async {
await dotenv.load(fileName: "config.env");
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
runApp(MultiProvider(providers: [
ChangeNotifierProvider(create: (context) => UserProvider()),
ChangeNotifierProvider(create: (context) => ScreenNumberProvider()),
ChangeNotifierProvider(create: (context) => CartOfferProvider()),
], child: const MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
precacheAllImage(context);
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: AppTheme.light,
onGenerateRoute: (settings) => generateRoute(settings),
home: const SplashScreen());
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib | mirrored_repositories/flutterzon_provider/lib/constants/app_theme.dart | import 'package:amazon_clone_flutter/constants/global_variables.dart';
import 'package:flutter/material.dart';
class AppTheme {
static ThemeData get light {
return ThemeData(
fontFamily: 'AmazonEmber',
scaffoldBackgroundColor: GlobalVariables.backgroundColor,
bottomSheetTheme: const BottomSheetThemeData(
surfaceTintColor: Colors.white,
backgroundColor: Colors.white,
modalBackgroundColor: Colors.white),
colorScheme:
const ColorScheme.light(primary: GlobalVariables.secondaryColor),
appBarTheme: const AppBarTheme(
elevation: 0, iconTheme: IconThemeData(color: Colors.black)),
useMaterial3: true,
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib | mirrored_repositories/flutterzon_provider/lib/constants/global_variables.dart | import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
final secureUri = dotenv.env['URI'];
String uri = secureUri!;
class GlobalVariables {
// COLORS
static const appBarGradient = LinearGradient(
colors: [
Color(0xff84D8E3),
Color(0xffA6E6CE),
],
// stops: [0.5, 1.0],
);
static const addressBarGradient = LinearGradient(
colors: [
Color(0xffB6E8EF),
Color(0xffCBF1E2),
],
stops: [0.5, 1.0],
);
static const goldenGradient = LinearGradient(
colors: [Color(0xffFFEDBB), Color(0xffFEDC71)], stops: [0.25, 1]);
static const secondaryColor = Color.fromRGBO(255, 153, 0, 1);
static const yellowColor = Color(0xffFED813);
static const backgroundColor = Colors.white;
static const greenColor = Color(0xff057205);
static const redColor = Color(0xffB22603);
static const Color greyBackgroundColor = Color(0xffF6F6F6);
static var selectedNavBarColor = Colors.cyan[800]!;
static const unselectedNavBarColor = Colors.black87;
// category images
static const List<Map<String, String>> categoryImages = [
{'title': 'Mobiles', 'image': 'assets/images/category_images/mobiles.jpeg'},
{'title': 'Fashion', 'image': 'assets/images/category_images/fashion.jpeg'},
{
'title': 'Electronics',
'image': 'assets/images/category_images/electronics.jpeg'
},
{'title': 'Home', 'image': 'assets/images/category_images/home.jpeg'},
{'title': 'Beauty', 'image': 'assets/images/category_images/beauty.jpeg'},
{
'title': 'Appliances',
'image': 'assets/images/category_images/appliances.jpeg'
},
{'title': 'Grocery', 'image': 'assets/images/category_images/grocery.jpeg'},
{'title': 'Books', 'image': 'assets/images/category_images/books.jpeg'},
{
'title': 'Essentials',
'image': 'assets/images/category_images/essentials.jpeg'
},
];
// Carousel images
static const List<Map<String, String>> carouselImages = [
{
'category': 'Mobiles',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699265366/carousel_images/bg4c71tkghkwtnxkfx8r.jpg',
},
{
'category': 'Fashion',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699265359/carousel_images/lynhzhgccpfb8pbdknyh.jpg',
},
{
'category': 'Beauty',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699265354/carousel_images/ysdubrrkwbi5rqqcupg5.jpg',
},
{
'category': 'Appliances',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699265359/carousel_images/lh9urah5mtrd8uolos2m.jpg',
},
{
'category': 'Mobiles',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699265358/carousel_images/mvrwbxras7uig7woc5gj.jpg',
},
{
'category': 'Mobiles',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699265355/carousel_images/josedcgjkzst3iqnpqgf.jpg',
},
{
'category': 'Electronics',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699265357/carousel_images/nx2nmaq4pbqlebiexqup.jpg',
},
{
'category': 'Electronics',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699265358/carousel_images/gvgwvhmodau81bwddsrh.jpg',
},
{
'category': 'Mobiles',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699265354/carousel_images/tb0uzkote4twcczih8xj.jpg',
},
];
//Bottom offers amazon pay
static const List<Map<String, String>> bottomOffersAmazonPay = [
{
'title': 'Amazon Pay',
'image': 'assets/images/bottom_offers/amazon_pay.png'
},
{
'title': 'Recharge',
'image': 'assets/images/bottom_offers/amazon_recharge.png'
},
{
'title': 'Rewards',
'image': 'assets/images/bottom_offers/amazon_rewards.png'
},
{
'title': 'Pay Bills',
'image': 'assets/images/bottom_offers/amazon_bills.png'
},
];
//Bottom offer under price
static const List<Map<String, String>> bottomOffersUnderPrice = [
{
'title': 'Budget Buys',
'image': 'assets/images/bottom_offers/budgetBuys.png'
},
{'title': 'Best Buys', 'image': 'assets/images/bottom_offers/bestBuys.png'},
{
'title': 'Super Buys',
'image': 'assets/images/bottom_offers/superBuys.png'
},
{'title': 'Top Picks', 'image': 'assets/images/bottom_offers/topPicks.png'},
];
// Bottom offers images
static const List<Map<String, String>> bottomOfferImages = [
{
'category': 'AmazonPay',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699472117/bottom_offers/quvjt4q774dqkkqe0tb4.png',
},
{
'category': 'Mobiles',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699264799/bottom_offers/kxymbalj4pmgeor4u6ug.jpg',
},
{
'category': 'Mobiles',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699264799/bottom_offers/uthsphrtzpcfubvq9dwn.png',
},
{
'category': 'Beauty',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699264800/bottom_offers/v3nc5x9boosqlkbz2nrj.png',
},
{
'category': 'Mobiles',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699264798/bottom_offers/qctd1ju8kieb9oyuyfc2.jpg',
},
{
'category': 'Essentials',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699264798/bottom_offers/e4omcec49lsdjedjvzl9.jpg',
},
{
'category': 'Grocery',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699264799/bottom_offers/sjjbdzyowmgcznugrqsv.jpg',
},
{
'category': 'Essentials',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699264798/bottom_offers/xohbxfozk55euqsprjmp.jpg',
},
{
'category': 'Home',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699264798/bottom_offers/jerrpfgphdk76isd5c8s.jpg',
},
{
'category': 'Fashion',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699264798/bottom_offers/iu5u3qvtxrriyb13eh5g.jpg',
},
{
'category': 'Home',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699264799/bottom_offers/qlpctc3ljlkka4wqy6dr.jpg',
},
{
'category': 'Fashion',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699264799/bottom_offers/emqsyqzli078fguthilp.jpg',
},
];
// Multiimage offers
// mulit image offer 1
static const List<Map<String, String>> multiImageOffer1 = [
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616716/multi_image_offers/multi_image_offer1/ixunkzn9ihxmq7sz5kbu.jpg',
'offerTitle': 'Health & household'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616716/multi_image_offers/multi_image_offer1/qoluocxlfvfsm06aft7m.jpg',
'offerTitle': 'Grocery essentials'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616716/multi_image_offers/multi_image_offer1/opop30gr9ko1rh31elnp.jpg',
'offerTitle': 'Beauty products'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616716/multi_image_offers/multi_image_offer1/drlfqq5spc08gtpwoehi.jpg',
'offerTitle': 'Visit store'
},
];
// Multi image offers 2
static const List<Map<String, String>> multiImageOffer2 = [
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616730/multi_image_offers/multi_image_offer2/fy7cga8bnkhbwdczeojg.jpg',
'offerTitle': 'Under ₹299 | Kitchen accessories'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616730/multi_image_offers/multi_image_offer2/vpvy0tubzfu5xb7rdowo.jpg',
'offerTitle': 'Under ₹499 | Kitchen jars, containers & more'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616730/multi_image_offers/multi_image_offer2/ozc0y0aprcduz1k6mzbn.jpg',
'offerTitle': '₹499 - ₹999 | Cookware sets'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616730/multi_image_offers/multi_image_offer2/f9zsqeaq2shwflttwfcu.jpg',
'offerTitle': 'Min. 60% Off | Dinnerware'
},
];
// multi image offer 3
static const List<Map<String, String>> multiImageOffer3 = [
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616731/multi_image_offers/multi_image_offer3/cxywqfuwdqdlmxfwhznh.jpg',
'offerTitle': 'Redmi (32) 4K TV | Lowest ever prices'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616731/multi_image_offers/multi_image_offer3/jypnmwrxog1zhmgkn0mq.jpg',
'offerTitle': 'OnePlus (50) 4K TV | Flat 43% off'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616731/multi_image_offers/multi_image_offer3/by0atjdadl3vdxvkwcxe.jpg',
'offerTitle': 'Samsung (65) iSmart TV | Bestseller'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616732/multi_image_offers/multi_image_offer3/kdbran924rp1dcfxkc37.jpg',
'offerTitle': 'Sony (55) 4K TV | Get 3 years warranty'
},
];
//muli image offer 4
static const List<Map<String, String>> multiImageOffer4 = [
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616739/multi_image_offers/multi_image_offer4/sg6xeof7e8c6i8tdtn3a.png',
'offerTitle': 'Starting ₹79 | Cycles, helmets & more'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616735/multi_image_offers/multi_image_offer4/gwknudygu8xkgbqwjhyh.png',
'offerTitle': 'Starting ₹99 | Cricket'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616737/multi_image_offers/multi_image_offer4/ye374adnpqqw0g9rpdrh.png',
'offerTitle': 'Starting ₹99 | Badminton'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616735/multi_image_offers/multi_image_offer4/j6qu404fobsayouau9et.png',
'offerTitle': 'Starting ₹49 | Fitness accessories & more'
},
];
static const List<Map<String, String>> multiImageOffer5 = [
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616735/multi_image_offers/multi_image_offer5/jmowr6zekxwqa1eb9byb.png',
'offerTitle': 'Cooking ingredients'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616736/multi_image_offers/multi_image_offer5/jl5sruf184umnwrhic3s.png',
'offerTitle': 'Sweets'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616737/multi_image_offers/multi_image_offer5/jqdwbsu2f9zbribwyybs.png',
'offerTitle': 'Cleaning supplies'
},
{
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699616740/multi_image_offers/multi_image_offer5/frqjrpvryuwsmga2ohay.png',
'offerTitle': 'View all offers'
},
];
static const List<Map<String, String>> productQualityDetails = [
{
'iconName': 'replacement.png',
'title': '7 days Service Centre Replacement'
},
{'iconName': 'free_delivery.png', 'title': 'Free Delivery'},
{'iconName': 'warranty.png', 'title': '1 Year Warranty'},
{'iconName': 'pay_on_delivery.png', 'title': 'Pay on Delivery'},
{'iconName': 'top_brand.png', 'title': 'Top Brand'},
{'iconName': 'delivered.png', 'title': 'Amazon Delivered'},
];
static const List<Map<String, String>> menuScreenImages = [
{
'title': 'Mobiles, Smartphones',
'category': 'Mobiles',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699008683/menu_screen_images/hpaduzg6ws3gttr1fvqc.png',
},
{
'title': 'Fashion, Clothing',
'category': 'Fashion',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699008683/menu_screen_images/kf3f4gsxfrc05iewamt3.png'
},
{
'title': 'Electronics & Audio',
'category': 'Electronics',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699008678/menu_screen_images/kurapdxq9i2n2m6vvdyz.png'
},
{
'title': 'Home, Kitchen & Decor',
'category': 'Home',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699008675/menu_screen_images/jyp9jwyudc0jh6gao2uc.png'
},
{
'title': 'Beauty, Skincare',
'category': 'Beauty',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699008678/menu_screen_images/b5zl9qkm3cx20eklrfjm.png'
},
{
'title': 'Appliances',
'category': 'Appliances',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699008672/menu_screen_images/i8u2o2lknnqhjaybewbr.png'
},
{
'title': 'Grocery, Food & Beverages',
'category': 'Grocery',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699008681/menu_screen_images/wlad5ab74zzn49iqhkbk.png'
},
{
'title': 'Books, Novels',
'category': 'Books',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699008671/menu_screen_images/javbsvmojbp3725oysoo.jpg'
},
{
'title': 'Essentials, Kitchen',
'category': 'Essentials',
'image':
'https://res.cloudinary.com/dthljz11q/image/upload/v1699008683/menu_screen_images/u7lk7kkv4vlra4dhjdnj.png'
},
];
}
| 0 |
mirrored_repositories/flutterzon_provider/lib | mirrored_repositories/flutterzon_provider/lib/constants/utils.dart | import 'dart:io';
import 'dart:math';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../features/home/screens/category_deals_screen.dart';
import '../features/product_details/screens/product_details_screen.dart';
import '../features/product_details/services/product_details_services.dart';
import '../models/product.dart';
import 'global_variables.dart';
void showSnackBar(BuildContext context, String text) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(text)));
}
void precatchedImage(List<String> images, BuildContext context) {
for (String image in images) {
precacheImage(NetworkImage(image), context);
}
}
void precatchedImageMap(
List<Map<String, String>> images, BuildContext context) {
for (Map<String, String> image in images) {
precacheImage(NetworkImage(image['image']!), context);
}
}
void precacheAllImage(context) {
precatchedImageMap(GlobalVariables.carouselImages, context);
precatchedImageMap(GlobalVariables.bottomOfferImages, context);
precatchedImageMap(GlobalVariables.multiImageOffer1, context);
precatchedImageMap(GlobalVariables.multiImageOffer2, context);
precatchedImageMap(GlobalVariables.multiImageOffer3, context);
precatchedImageMap(GlobalVariables.multiImageOffer4, context);
precatchedImageMap(GlobalVariables.multiImageOffer5, context);
}
String formatFolderName(String productName) {
var formattedName = productName.replaceAll(' ', '-');
if (formattedName.length > 255) {
formattedName = formattedName.substring(0, 255);
}
formattedName = formattedName.replaceAll(RegExp(r'[^\w\-_]'), '');
return formattedName;
}
String capitalizeFirstLetter({required String string}) {
String firstLetter = string[0].toUpperCase();
String remainingString = string.substring(1, string.length);
return firstLetter + remainingString;
}
Future<List<File>> pickImages() async {
List<File> images = [];
try {
var files = await FilePicker.platform.pickFiles(
type: FileType.image,
allowMultiple: true,
);
if (files != null || files!.files.isNotEmpty) {
for (int i = 0; i < files.files.length; i++) {
images.add(File(files.files[i].path!));
}
}
} catch (e) {
debugPrint(e.toString());
}
return images;
}
String getDeliveryDate() {
final DateTime currentDate = DateTime.now();
final int randomDay = Random().nextInt(15) + 1;
final DateTime deliveryDate = currentDate.add(Duration(days: randomDay));
String formattedDeliveryDate =
DateFormat('EEEE, dd MMMM').format(deliveryDate);
return formattedDeliveryDate;
}
formatDate(int date) {
final DateFormat formatter = DateFormat('MMMM dd, yyyy');
final String formattedOrderDate =
formatter.format(DateTime.fromMillisecondsSinceEpoch(date));
return formattedOrderDate;
}
String formatPrice(num price) {
final NumberFormat numberFormatter = NumberFormat.decimalPattern('en_US');
numberFormatter.minimumFractionDigits = 0;
numberFormatter.maximumFractionDigits = 0;
final String formattedPrice = numberFormatter.format(price);
return formattedPrice;
}
String formatPriceWithDecimal(num price) {
final NumberFormat numberFormatter = NumberFormat.decimalPattern('en_US');
numberFormatter.minimumFractionDigits = 2;
numberFormatter.maximumFractionDigits = 2;
final String formattedPrice = numberFormatter.format(price);
return formattedPrice;
}
String formatLakhs(int lakhs) {
final formatter = NumberFormat.compact(locale: 'en_IN');
final String formattedAmount = formatter.format(lakhs);
return formattedAmount;
}
String getEmi(Product product) {
final double emi = (product.price) / 21;
final String formattedEmi = formatPrice(emi);
return formattedEmi;
}
String getStatus(int status) {
if (status == 0 || status == 1) {
return 'Received';
} else if (status == 2) {
return 'Dispatched';
} else if (status == 3) {
return 'In Transit';
} else if (status == 4) {
return 'Delivered';
}
return '';
}
String getSubStatus(int status) {
if (status == 0 || status == 1) {
return 'Your order has been received and is currently being processed by the seller.';
} else if (status == 2) {
return 'Your order has been shipped and dispatched.';
} else if (status == 3) {
return 'Your order is currently in transit.';
} else if (status == 4) {
return 'Your order has been delivered.';
}
return '';
}
void navigateToProductDetails(
{required BuildContext context,
required Product product,
required String deliveryDate}) {
Map<String, dynamic> arguments = {
'product': product,
'deliveryDate': deliveryDate,
};
Navigator.pushNamed(context, ProductDetailsScreen.routeName,
arguments: arguments);
}
final ProductDetailsServices productDetailsServices = ProductDetailsServices();
void addToCart(BuildContext context, Product product) {
productDetailsServices.addToCart(context: context, product: product);
showSnackBar(context, 'Added to cart!');
debugPrint('addToCart pressed!');
}
Random random = Random();
String getRandomFromMap(List<Map<String, String>> map) {
int randomIndex = random.nextInt(map.length);
Map<String, String> randomMap = map[randomIndex];
String randomTitle = randomMap['title']!;
return randomTitle;
}
int getUniqueRandomInt({required max}) {
Set<int> randomIntSet = <int>{};
int randomInt;
while (true) {
randomInt = random.nextInt(max);
if (!randomIntSet.contains(randomInt)) {
break;
}
}
return randomInt;
}
void navigateToCategoryPage(BuildContext context, String category) {
Navigator.pushNamed(context, CategoryDealsScreen.routeName,
arguments: category);
}
| 0 |
mirrored_repositories/flutterzon_provider/lib | mirrored_repositories/flutterzon_provider/lib/constants/error_handling.dart | import 'dart:convert';
import 'package:amazon_clone_flutter/constants/utils.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void httpErrorHandle({
required http.Response response,
required BuildContext context,
required VoidCallback onSuccess,
}) {
switch (response.statusCode) {
case 200:
onSuccess();
break;
case 400:
showSnackBar(context, jsonDecode(response.body)['msg']);
case 500:
showSnackBar(context, jsonDecode(response.body)['error']);
default:
showSnackBar(context, response.body);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/cart | mirrored_repositories/flutterzon_provider/lib/features/cart/widgets/cart_subtotal.dart | import 'package:amazon_clone_flutter/constants/utils.dart';
import 'package:amazon_clone_flutter/providers/user_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class CartSubtotal extends StatelessWidget {
const CartSubtotal({super.key});
@override
Widget build(BuildContext context) {
final userProvider = context.watch<UserProvider>().user;
int sum = 0;
userProvider.cart
.map((e) => sum += e['quantity'] * e['product']['price'] as int)
.toList();
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(
'SubTotal ',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.normal,
color: Colors.black87),
),
const Text(
'₹',
style: TextStyle(
fontSize: 18, color: Colors.black87, fontWeight: FontWeight.w400),
),
Text(
formatPriceWithDecimal(sum),
style: const TextStyle(
fontSize: 22, fontWeight: FontWeight.bold, color: Colors.black87),
),
],
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/cart | mirrored_repositories/flutterzon_provider/lib/features/cart/widgets/add_to_card_offer.dart | import 'package:amazon_clone_flutter/common/widgets/stars.dart';
import 'package:flutter/material.dart';
import '../../../constants/global_variables.dart';
import '../../../constants/utils.dart';
import '../../../models/product.dart';
class AddToCartOffer extends StatefulWidget {
const AddToCartOffer({
super.key,
required this.product,
});
final Product product;
@override
State<AddToCartOffer> createState() => _AddToCartOfferState();
}
String? price;
class _AddToCartOfferState extends State<AddToCartOffer> {
@override
void initState() {
super.initState();
price = formatPrice(widget.product.price);
}
@override
Widget build(BuildContext context) {
double totalRating = 0;
for (int i = 0; i < widget.product.rating!.length; i++) {
totalRating += widget.product.rating![i].rating;
}
double averageRating = 0;
if (totalRating != 0) {
averageRating = totalRating / widget.product.rating!.length;
}
return Padding(
padding: const EdgeInsets.all(8.0),
child: SizedBox(
width: 130,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InkWell(
onTap: () {
navigateToProductDetails(
context: context,
product: widget.product,
deliveryDate: getDeliveryDate());
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Image.network(
widget.product.images[0],
height: 130,
width: 130,
),
),
Text(
widget.product.name,
maxLines: 2,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.normal,
color: GlobalVariables.selectedNavBarColor,
overflow: TextOverflow.ellipsis),
),
Row(
children: [
Stars(
rating: averageRating,
size: 20,
),
const SizedBox(
width: 4,
),
Text(
widget.product.rating!.length.toString(),
style: TextStyle(
color: GlobalVariables.selectedNavBarColor,
fontSize: 14,
fontWeight: FontWeight.normal,
),
),
],
),
Text(
'₹$price.00',
maxLines: 2,
style: const TextStyle(
fontSize: 16,
color: Color(0xffB12704),
fontWeight: FontWeight.w400,
overflow: TextOverflow.ellipsis),
),
],
),
),
ElevatedButton(
onPressed: () {
setState(() {
addToCart(context, widget.product);
});
},
style: const ButtonStyle(
padding: MaterialStatePropertyAll(EdgeInsets.zero),
minimumSize: MaterialStatePropertyAll(Size(100, 35)),
maximumSize: MaterialStatePropertyAll(Size(100, 35)),
fixedSize: MaterialStatePropertyAll(Size(100, 35)),
backgroundColor:
MaterialStatePropertyAll(GlobalVariables.yellowColor)),
child: const Text(
'Add to Cart',
style: TextStyle(
fontSize: 12,
color: Colors.black87,
fontWeight: FontWeight.normal),
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/cart | mirrored_repositories/flutterzon_provider/lib/features/cart/widgets/swipe_container.dart | import 'package:flutter/material.dart';
class SwipeContainer extends StatelessWidget {
const SwipeContainer({
super.key,
required this.isDelete,
required this.secondaryBackgroundText,
});
final bool isDelete;
final String secondaryBackgroundText;
@override
Widget build(BuildContext context) {
return Container(
color: isDelete ? const Color(0xffC40202) : const Color(0xffE3E5E4),
child: Row(
children: [
SizedBox(
width: isDelete ? 50 : 250,
),
Text(
isDelete ? 'Delete' : secondaryBackgroundText,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400,
color: isDelete ? Colors.white : Colors.black87),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/cart | mirrored_repositories/flutterzon_provider/lib/features/cart/widgets/cart_icon.dart | import 'package:flutter/material.dart';
import '../../../constants/global_variables.dart';
class CartIcon extends StatelessWidget {
const CartIcon({
super.key,
required this.iconName,
required this.title,
});
final String iconName;
final String title;
@override
Widget build(BuildContext context) {
return Column(
children: [
Image.asset(
'assets/images/cart_screen_icons/$iconName',
height: 55,
width: 55,
),
Text(
title,
style: TextStyle(
fontSize: 14, color: GlobalVariables.selectedNavBarColor),
)
],
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/cart | mirrored_repositories/flutterzon_provider/lib/features/cart/widgets/save_for_later_single.dart | import 'package:amazon_clone_flutter/constants/global_variables.dart';
import 'package:amazon_clone_flutter/constants/utils.dart';
import 'package:amazon_clone_flutter/features/cart/services/cart_services.dart';
import 'package:amazon_clone_flutter/features/cart/widgets/add_to_card_offer.dart';
import 'package:amazon_clone_flutter/features/product_details/services/product_details_services.dart';
import 'package:amazon_clone_flutter/models/product.dart';
import 'package:flutter/material.dart';
import '../../home/services/home_services.dart';
import 'custom_text_button.dart';
class SaveForLaterSingle extends StatefulWidget {
const SaveForLaterSingle({super.key, required this.product});
final Product product;
@override
State<SaveForLaterSingle> createState() => _SaveForLaterSingleState();
}
class _SaveForLaterSingleState extends State<SaveForLaterSingle> {
final ProductDetailsServices productDetailsServices =
ProductDetailsServices();
final HomeServices homeServices = HomeServices();
List<Product>? modalSheetProductList;
fetchCategoryProducts({required String category}) async {
modalSheetProductList = await homeServices.fetchCategoryProducts(
context: context, category: category);
modalSheetProductList!.shuffle();
if (context.mounted) {
setState(() {});
}
}
final CartServices cartServices = CartServices();
void increaseQuantity(Product product) {
productDetailsServices.addToCart(context: context, product: product);
}
void decreaseQuantity(Product product) {
cartServices.removeFromCart(context: context, product: product);
}
void deleteProduct(Product product) {
cartServices.deleteFromCart(context: context, product: product);
}
@override
void initState() {
super.initState();
fetchCategoryProducts(category: widget.product.category);
}
@override
Widget build(BuildContext context) {
Product product = widget.product;
String price = formatPriceWithDecimal(widget.product.price);
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
margin: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: const Color(0xffF8F9FB),
borderRadius: BorderRadius.circular(4)),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Image.network(
product.images[0],
// fit: BoxFit.fitHeight,
height: 140,
width: 140,
),
const SizedBox(width: 15),
Expanded(
flex: 6,
child: Flex(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
direction: Axis.vertical,
children: [
Text(
product.name,
maxLines: 2,
style: const TextStyle(
color: Colors.black87,
fontWeight: FontWeight.normal,
fontSize: 16,
overflow: TextOverflow.ellipsis),
),
Row(
children: [
const Text(
'₹',
style: TextStyle(
fontSize: 14,
color: Colors.black,
fontWeight: FontWeight.bold),
),
Text(
price,
style: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
],
),
const Text(
'Eligible for FREE Shipping',
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 14,
color: Colors.black54,
),
),
const Text(
'In stock',
style: TextStyle(
fontSize: 14,
color: GlobalVariables.greenColor,
),
),
Text(
'7 days Replacement',
style: TextStyle(
fontSize: 14,
color: GlobalVariables.selectedNavBarColor,
),
),
const SizedBox(
height: 4,
),
],
),
),
]),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
child: CustomTextButton(
buttonText: 'Delete',
onPressed: () {
cartServices.deleteFromLater(
context: context, product: product);
}),
),
Expanded(
child: CustomTextButton(
buttonText: 'Compare',
onPressed: () {
showModalBottomSheet(
constraints: const BoxConstraints(
minHeight: 350, maxHeight: 350),
shape: OutlineInputBorder(
borderRadius: BorderRadius.circular(0)),
context: context,
builder: (context) {
return modalSheetProductList == null
? const Center(
child: CircularProgressIndicator(),
)
: MoreLikeThisBottomSheet(
modalSheetProductList:
modalSheetProductList);
});
}),
),
Expanded(
child: CustomTextButton(
buttonText: 'Move to cart',
onPressed: () {
cartServices.moveToCart(
context: context, product: product);
}),
),
],
),
],
));
}
}
class MoreLikeThisBottomSheet extends StatelessWidget {
const MoreLikeThisBottomSheet({
super.key,
required this.modalSheetProductList,
});
final List<Product>? modalSheetProductList;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'More items like this',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
const SizedBox(height: 10),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: modalSheetProductList!.length > 20
? 20
: modalSheetProductList!.length,
itemBuilder: (context, index) {
final product = modalSheetProductList![index];
return AddToCartOffer(product: product);
}),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/cart | mirrored_repositories/flutterzon_provider/lib/features/cart/widgets/cart_product.dart | import 'package:amazon_clone_flutter/constants/global_variables.dart';
import 'package:amazon_clone_flutter/constants/utils.dart';
import 'package:amazon_clone_flutter/features/cart/services/cart_services.dart';
import 'package:amazon_clone_flutter/features/cart/widgets/add_to_card_offer.dart';
import 'package:amazon_clone_flutter/features/product_details/services/product_details_services.dart';
import 'package:amazon_clone_flutter/models/product.dart';
import 'package:amazon_clone_flutter/providers/user_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../home/services/home_services.dart';
import 'custom_icon_button.dart';
import 'custom_text_button.dart';
class CartProduct extends StatefulWidget {
const CartProduct({super.key, required this.index, required this.category});
final int index;
final String category;
@override
State<CartProduct> createState() => _CartProductState();
}
class _CartProductState extends State<CartProduct> {
final ProductDetailsServices productDetailsServices =
ProductDetailsServices();
final HomeServices homeServices = HomeServices();
List<Product>? modalSheetProductList;
fetchCategoryProducts({required String category}) async {
modalSheetProductList = await homeServices.fetchCategoryProducts(
context: context, category: category);
modalSheetProductList!.shuffle();
if (context.mounted) {
setState(() {});
}
}
final CartServices cartServices = CartServices();
void increaseQuantity(Product product) {
productDetailsServices.addToCart(context: context, product: product);
}
void decreaseQuantity(Product product) {
cartServices.removeFromCart(context: context, product: product);
}
void deleteProduct(Product product) {
cartServices.deleteFromCart(context: context, product: product);
}
@override
void initState() {
super.initState();
fetchCategoryProducts(category: widget.category);
}
@override
Widget build(BuildContext context) {
final cartProduct = context.watch<UserProvider>().user.cart[widget.index];
final product = Product.fromMap(cartProduct['product']);
final quantity = cartProduct['quantity'];
String price = formatPriceWithDecimal(product.price);
return Container(
padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
margin: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: const Color(0xffF8F9FB),
borderRadius: BorderRadius.circular(4)),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
spacing: 30,
direction: Axis.vertical,
crossAxisAlignment: WrapCrossAlignment.center,
alignment: WrapAlignment.center,
children: [
Image.network(
product.images[0],
// fit: BoxFit.fitHeight,
height: 140,
width: 140,
),
Row(
children: [
Row(children: [
InkWell(
onTap: () => decreaseQuantity(product),
child: const CustomIconbutton(
iconName: Icons.remove, isRight: false),
),
Container(
height: 30,
width: 40,
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.white,
border: const Border(
top: BorderSide(color: Colors.grey, width: 0.5),
bottom:
BorderSide(color: Colors.grey, width: 0.5)),
boxShadow: [
BoxShadow(
color: Colors.grey.shade200,
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: Text(
quantity.toString(),
style: TextStyle(
color: GlobalVariables.selectedNavBarColor,
fontSize: 16,
fontWeight: FontWeight.w400),
),
),
InkWell(
onTap: () => increaseQuantity(product),
child: const CustomIconbutton(
iconName: Icons.add,
isRight: true,
),
),
])
],
),
],
),
const SizedBox(width: 15),
Expanded(
flex: 6,
child: Flex(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
direction: Axis.vertical,
children: [
Text(
product.name,
maxLines: 2,
style: const TextStyle(
color: Colors.black87,
fontWeight: FontWeight.normal,
fontSize: 16,
overflow: TextOverflow.ellipsis),
),
Row(
children: [
const Text(
'₹',
style: TextStyle(
fontSize: 14,
color: Colors.black,
fontWeight: FontWeight.bold),
),
Text(
price,
style: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
],
),
const Text(
'Eligible for FREE Shipping',
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 14,
color: Colors.black54,
),
),
const Text(
'In stock',
style: TextStyle(
fontSize: 14,
color: GlobalVariables.greenColor,
),
),
Text(
'7 days Replacement',
style: TextStyle(
fontSize: 14,
color: GlobalVariables.selectedNavBarColor,
),
),
const SizedBox(
height: 4,
),
Row(
children: [
CustomTextButton(
buttonText: 'Delete',
onPressed: () {
debugPrint('delete preesed!');
deleteProduct(product);
}),
CustomTextButton(
buttonText: 'Save for later',
onPressed: () {
cartServices.saveForLater(
context: context, product: product);
showSnackBar(context, 'Save for later!');
setState(() {});
}),
],
),
CustomTextButton(
buttonText: 'See more like this',
onPressed: () {
showModalBottomSheet(
constraints: const BoxConstraints(
minHeight: 350, maxHeight: 350),
shape: OutlineInputBorder(
borderRadius: BorderRadius.circular(0)),
context: context,
builder: (context) {
return modalSheetProductList == null
? const Center(
child: CircularProgressIndicator(),
)
: Scaffold(
body: Container(
margin: const EdgeInsets.symmetric(
horizontal: 10, vertical: 16),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
const Text(
'More items like this',
style: TextStyle(
fontSize: 16,
fontWeight:
FontWeight.bold),
),
const SizedBox(height: 10),
Expanded(
child: ListView.builder(
scrollDirection:
Axis.horizontal,
itemCount:
modalSheetProductList!
.length >
20
? 20
: modalSheetProductList!
.length,
itemBuilder:
(context, index) {
final product =
modalSheetProductList![
index];
return AddToCartOffer(
product: product);
}),
)
],
),
),
);
});
}),
],
),
),
]));
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/cart | mirrored_repositories/flutterzon_provider/lib/features/cart/widgets/custom_text_button.dart | import 'package:flutter/material.dart';
class CustomTextButton extends StatelessWidget {
const CustomTextButton(
{super.key,
required this.buttonText,
required this.onPressed,
this.isMenuScreenButton = false});
final String buttonText;
final VoidCallback onPressed;
final bool isMenuScreenButton;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: onPressed,
child: Container(
margin: const EdgeInsets.all(4),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: const Color(0xffD5D9DA),
),
borderRadius: BorderRadius.circular(8),
boxShadow: [
isMenuScreenButton
? const BoxShadow()
: BoxShadow(
color: Colors.grey.shade200,
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: Text(
buttonText,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: isMenuScreenButton ? 14 : 13,
fontWeight: FontWeight.w400,
color: Colors.black87),
),
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/cart | mirrored_repositories/flutterzon_provider/lib/features/cart/widgets/amazon_pay_bannar_ad.dart | import 'package:flutter/material.dart';
class AmazonPayBannarAd extends StatelessWidget {
const AmazonPayBannarAd({
super.key,
});
@override
Widget build(BuildContext context) {
return Container(
height: 70,
width: double.infinity,
decoration: BoxDecoration(
color: const Color(0xffFFF1E4),
border: Border.all(color: Colors.grey, width: 0.5)),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset(
'assets/images/cart_screen_icons/pay_calender.png',
height: 50,
width: 50,
),
SizedBox(
width: 300,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Amazon Pay Later | Get instant credit up to ₹60,000',
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14,
),
),
RichText(
text: const TextSpan(
text: 'Activate & get rewards of ',
style: TextStyle(
fontSize: 14,
color: Colors.black87,
fontWeight: FontWeight.bold),
children: [
TextSpan(
text: '₹600',
style: TextStyle(
fontSize: 14,
color: Color(0xffC40202),
fontWeight: FontWeight.bold)),
TextSpan(
text: '>',
style: TextStyle(
fontSize: 14,
color: Colors.black87,
fontWeight: FontWeight.bold))
],
),
),
const SizedBox(height: 10),
],
),
)
]),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/cart | mirrored_repositories/flutterzon_provider/lib/features/cart/widgets/custom_icon_button.dart | import 'package:flutter/material.dart';
class CustomIconbutton extends StatelessWidget {
const CustomIconbutton({
super.key,
required this.iconName,
required this.isRight,
});
final IconData iconName;
final bool isRight;
@override
Widget build(BuildContext context) {
return Container(
width: 35,
height: 30,
alignment: Alignment.center,
decoration: BoxDecoration(
border: Border.all(color: Colors.grey, width: 0.5),
borderRadius: isRight
? const BorderRadius.only(
topRight: Radius.circular(8), bottomRight: Radius.circular(8))
: const BorderRadius.only(
topLeft: Radius.circular(8), bottomLeft: Radius.circular(8)),
boxShadow: [
BoxShadow(
color: Colors.grey.shade200,
blurRadius: 8,
offset: const Offset(0, 2),
),
],
gradient: const LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0xffF7F8FA), Color(0xffE8E9ED)],
stops: [0.2, 1]),
),
child: Icon(
iconName,
size: 18,
color: Colors.black,
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/cart | mirrored_repositories/flutterzon_provider/lib/features/cart/services/cart_services.dart | import 'dart:convert';
import 'package:amazon_clone_flutter/constants/error_handling.dart';
import 'package:amazon_clone_flutter/constants/global_variables.dart';
import 'package:amazon_clone_flutter/models/product.dart';
import 'package:amazon_clone_flutter/providers/user_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;
import '../../../constants/utils.dart';
import '../../../models/user.dart';
class CartServices {
void removeFromCart({
required BuildContext context,
required Product product,
}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
http.Response res = await http.delete(
Uri.parse("$uri/api/remove-from-cart/${product.id}"),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
);
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
User user = userProvider.user.copyWith(
wishList: jsonDecode(res.body)['wishList'],
cart: jsonDecode(res.body)['cart'],
keepShoppingFor: jsonDecode(res.body)['keepShoppingFor'],
saveForLater: jsonDecode(res.body)['saveForLater'],
);
userProvider.setUserFromModel(user);
});
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
}
void deleteFromCart(
{required BuildContext context, required Product product}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
http.Response res = await http.delete(
Uri.parse("$uri/api/delete-from-cart/${product.id}"),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
);
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
User user = userProvider.user.copyWith(
wishList: jsonDecode(res.body)['wishList'],
cart: jsonDecode(res.body)['cart'],
keepShoppingFor: jsonDecode(res.body)['keepShoppingFor'],
saveForLater: jsonDecode(res.body)['saveForLater'],
);
userProvider.setUserFromModel(user);
});
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
}
void saveForLater(
{required BuildContext context, required Product product}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
http.Response res = await http.post(Uri.parse("$uri/api/save-for-later"),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
body: jsonEncode({
'id': product.id!,
}));
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
User user = userProvider.user.copyWith(
wishList: jsonDecode(res.body)['wishList'],
cart: jsonDecode(res.body)['cart'],
keepShoppingFor: jsonDecode(res.body)['keepShoppingFor'],
saveForLater: jsonDecode(res.body)['saveForLater'],
);
userProvider.setUserFromModel(user);
});
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
}
void deleteFromLater(
{required BuildContext context, required Product product}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
http.Response res = await http.delete(
Uri.parse("$uri/api/delete-from-later/${product.id}"),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
);
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
User user = userProvider.user.copyWith(
wishList: jsonDecode(res.body)['wishList'],
cart: jsonDecode(res.body)['cart'],
keepShoppingFor: jsonDecode(res.body)['keepShoppingFor'],
saveForLater: jsonDecode(res.body)['saveForLater'],
);
userProvider.setUserFromModel(user);
});
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
}
void moveToCart(
{required BuildContext context, required Product product}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
http.Response res = await http.post(Uri.parse("$uri/api/move-to-cart"),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
body: jsonEncode({
'id': product.id!,
}));
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
User user = userProvider.user.copyWith(
wishList: jsonDecode(res.body)['wishList'],
cart: jsonDecode(res.body)['cart'],
keepShoppingFor: jsonDecode(res.body)['keepShoppingFor'],
saveForLater: jsonDecode(res.body)['saveForLater'],
);
userProvider.setUserFromModel(user);
});
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/cart | mirrored_repositories/flutterzon_provider/lib/features/cart/screens/cart_screen.dart | import 'package:amazon_clone_flutter/common/widgets/custom_app_bar.dart';
import 'package:amazon_clone_flutter/common/widgets/custom_elevated_button.dart';
import 'package:amazon_clone_flutter/constants/global_variables.dart';
import 'package:amazon_clone_flutter/constants/utils.dart';
import 'package:amazon_clone_flutter/features/cart/widgets/cart_product.dart';
import 'package:amazon_clone_flutter/features/cart/widgets/cart_subtotal.dart';
import 'package:amazon_clone_flutter/features/product_details/screens/product_details_screen.dart';
import 'package:amazon_clone_flutter/features/product_details/widgets/divider_with_sizedbox.dart';
import 'package:amazon_clone_flutter/providers/cart_offers_provider.dart';
import 'package:amazon_clone_flutter/providers/user_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../models/product.dart';
import '../../address/screens/address_screen.dart';
import '../../home/services/home_services.dart';
import '../services/cart_services.dart';
import '../widgets/add_to_card_offer.dart';
import '../widgets/amazon_pay_bannar_ad.dart';
import '../widgets/cart_icon.dart';
import '../widgets/save_for_later_single.dart';
import '../widgets/swipe_container.dart';
class CartScreen extends StatefulWidget {
static const String routeName = '/cart-screen';
const CartScreen({super.key});
@override
State<CartScreen> createState() => _CartScreenState();
}
class _CartScreenState extends State<CartScreen> {
List<Product>? categoryProductList;
List<Product>? categoryProductList1;
List<Product>? categoryProductList2;
final HomeServices homeServices = HomeServices();
final CartServices cartServices = CartServices();
void navigateToAddressScreen(int sum) {
Navigator.pushNamed(context, AddressScreen.routeName,
arguments: sum.toString());
}
void deleteProduct(Product product) {
cartServices.deleteFromCart(context: context, product: product);
}
void deleteFromLater(Product product) {
cartServices.deleteFromLater(context: context, product: product);
}
void moveToCart(Product product) {
cartServices.moveToCart(context: context, product: product);
}
void saveForLater(Product product) {
cartServices.saveForLater(context: context, product: product);
setState(() {});
}
fetchCategoryProducts({required String category}) async {
List<Product>? list = await homeServices.fetchCategoryProducts(
context: context, category: category);
list.shuffle();
return list;
}
fetchAllCartOffers({required providerCategory}) async {
String randomCategory = getRandomFromMap(GlobalVariables.categoryImages);
String randomCategory1 = getRandomFromMap(GlobalVariables.categoryImages);
categoryProductList =
await fetchCategoryProducts(category: providerCategory);
categoryProductList1 =
await fetchCategoryProducts(category: randomCategory);
categoryProductList2 =
await fetchCategoryProducts(category: randomCategory1);
setState(() {});
}
@override
void initState() {
super.initState();
final category1 = Provider.of<CartOfferProvider>(context, listen: false);
debugPrint(category1.category1);
fetchAllCartOffers(providerCategory: category1.category1);
}
@override
Widget build(BuildContext context) {
final user = context.watch<UserProvider>().user;
int sum = 0;
user.cart
.map((e) => sum += e['quantity'] * e['product']['price'] as int)
.toList();
return Scaffold(
appBar: const PreferredSize(
preferredSize: Size.fromHeight(60), child: CustomAppBar()),
body: SingleChildScrollView(
child: Column(
children: [
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 12).copyWith(top: 20),
child: user.cart.isEmpty
? SizedBox(
height: 200,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ClipOval(
child: Image.asset(
'assets/images/empty_cart.png',
height: 180,
width: 180,
),
),
const Text('Your Amazon Cart is empty')
],
),
)
: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const CartSubtotal(),
const SizedBox(
height: 10,
),
Row(
children: [
const Text(
'EMI Available ',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w400,
color: Colors.black54),
),
Text(
'Details',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w400,
color: GlobalVariables.selectedNavBarColor),
),
],
),
const SizedBox(height: 10),
Row(
children: [
const Icon(
Icons.check_circle,
color: GlobalVariables.greenColor,
size: 25,
),
const SizedBox(width: 6),
Expanded(
child: RichText(
text: TextSpan(
text:
'Your order is eligible for FREE Delivery. ',
style: const TextStyle(
fontSize: 14,
color: GlobalVariables.greenColor,
fontWeight: FontWeight.w500),
children: [
const TextSpan(
text: 'Select this option at checkout. ',
style: TextStyle(
height: 1.4,
fontSize: 14,
color: Colors.black54,
fontWeight: FontWeight.w400),
),
TextSpan(
text: 'Details ',
style: TextStyle(
fontSize: 14,
color: GlobalVariables
.selectedNavBarColor,
fontWeight: FontWeight.w400),
)
])),
),
],
),
const SizedBox(height: 10),
CustomElevatedButton(
buttonText:
'Proceed to Buy (${user.cart.length} items)',
onPressed: () => navigateToAddressScreen(sum),
isRectangle: true,
),
const DividerWithSizedBox(
thickness: 0.5,
sB1Height: 20,
)
],
),
),
Visibility(
visible: user.cart.isNotEmpty,
child: ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
itemCount: user.cart.length,
itemBuilder: ((context, index) {
final product = Product.fromMap(user.cart[index]['product']);
return Dismissible(
movementDuration: const Duration(milliseconds: 100),
onDismissed: (DismissDirection direction) {
if (direction == DismissDirection.startToEnd) {
deleteProduct(product);
} else if (direction == DismissDirection.endToStart) {
saveForLater(product);
showSnackBar(context, 'Saved for later');
}
},
background: const SwipeContainer(
isDelete: true,
secondaryBackgroundText: 'Save for later',
),
secondaryBackground: const SwipeContainer(
isDelete: false,
secondaryBackgroundText: 'Save for later',
),
key: UniqueKey(),
child: InkWell(
onTap: () {
navigateToProductDetails(
context: context,
product:
Product.fromMap(user.cart[index]['product']),
deliveryDate: getDeliveryDate());
},
child: CartProduct(
index: index,
category: user.cart[index]['product']['category']
.toString(),
),
));
}),
),
),
const DividerWithSizedBox(),
const Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
CartIcon(
iconName: 'secure_payment.png',
title: 'Secure Payment',
),
CartIcon(
iconName: 'delivered_alt.png',
title: 'Amazon Delivered',
),
],
),
const SizedBox(height: 15),
const AmazonPayBannarAd(),
const SizedBox(height: 15),
user.saveForLater.isEmpty
? const SizedBox()
: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: const EdgeInsets.all(4),
color: const Color(0xffE9EDEE),
height: 15,
),
Padding(
padding: const EdgeInsets.only(left: 12),
child: Text(
'Saved for later (${user.saveForLater.length} items)',
style: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
),
ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
itemCount: user.saveForLater.length,
itemBuilder: ((context, index) {
final product = Product.fromMap(
user.saveForLater[index]['product']);
return Dismissible(
movementDuration:
const Duration(milliseconds: 100),
onDismissed: (DismissDirection direction) {
if (direction == DismissDirection.startToEnd) {
deleteFromLater(product);
} else if (direction ==
DismissDirection.endToStart) {
moveToCart(product);
}
},
key: UniqueKey(),
background: const SwipeContainer(
isDelete: true,
secondaryBackgroundText: 'Move to cart'),
secondaryBackground: const SwipeContainer(
isDelete: false,
secondaryBackgroundText: 'Move to cart'),
child: InkWell(
onTap: () {
Map<String, dynamic> arguments = {
'product': Product.fromMap(
user.saveForLater[index]['product']),
'deliveryDate': getDeliveryDate(),
};
Navigator.pushNamed(
context, ProductDetailsScreen.routeName,
arguments: arguments);
},
child: SaveForLaterSingle(
product: Product.fromMap(
user.saveForLater[index]['product']),
),
),
);
}))
],
),
const SizedBox(height: 15),
categoryProductList == null || categoryProductList!.isEmpty
? const SizedBox()
: AddToCartWidget(
title: 'Frequently viewed with items in your cart',
isTitleLong: true,
list: categoryProductList),
categoryProductList1 == null || categoryProductList1!.isEmpty
? const SizedBox()
: AddToCartWidget(
title: 'Top picks for you',
isTitleLong: false,
list: categoryProductList1),
categoryProductList2 == null || categoryProductList2!.isEmpty
? const SizedBox()
: AddToCartWidget(
title: 'Recommendations for you',
isTitleLong: false,
list: categoryProductList2),
const SizedBox(height: 15),
],
),
),
);
}
}
class AddToCartWidget extends StatelessWidget {
const AddToCartWidget(
{super.key,
required this.list,
required this.title,
required this.isTitleLong});
final List<Product>? list;
final String title;
final bool isTitleLong;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12).copyWith(top: 18),
width: MediaQuery.sizeOf(context).height,
color: const Color(0xffE9EDEE),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 14).copyWith(top: 12),
color: Colors.white,
height: isTitleLong ? 370 : 340,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 6),
SizedBox(
height: 290,
child: ListView.builder(
// shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: list!.length > 20 ? 20 : list!.length,
itemBuilder: ((context, index) {
Product product = list![index];
return AddToCartOffer(product: product);
})),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/admin | mirrored_repositories/flutterzon_provider/lib/features/admin/widgets/custom_floating_action_button.dart | import 'package:flutter/material.dart';
import '../../../constants/global_variables.dart';
import '../screens/add_product_screen.dart';
class CustomFloatingActionButton extends StatelessWidget {
const CustomFloatingActionButton({
super.key,
});
@override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: () {
Navigator.pushNamed(context, AddProductScreen.routeName);
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
backgroundColor: GlobalVariables.selectedNavBarColor,
tooltip: 'Add a product',
child: const Icon(Icons.add),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/admin | mirrored_repositories/flutterzon_provider/lib/features/admin/models/sales.dart | import 'package:amazon_clone_flutter/constants/global_variables.dart';
import 'package:flutter/material.dart';
class Sales {
final String label;
final int earning;
final Color pointColor = GlobalVariables.secondaryColor;
Sales(this.label, this.earning);
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/admin | mirrored_repositories/flutterzon_provider/lib/features/admin/services/admin_services.dart | import 'dart:convert';
import 'dart:io';
import 'package:amazon_clone_flutter/constants/error_handling.dart';
import 'package:amazon_clone_flutter/constants/global_variables.dart';
import 'package:amazon_clone_flutter/features/admin/models/sales.dart';
import 'package:amazon_clone_flutter/providers/user_provider.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:http/http.dart' as http;
import 'package:amazon_clone_flutter/constants/utils.dart';
import 'package:amazon_clone_flutter/models/product.dart';
import 'package:cloudinary_public/cloudinary_public.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../models/order.dart';
class AdminServices {
void sellProducts({
required BuildContext context,
required String name,
required String description,
required double price,
required int quantity,
required String category,
required List<File> images,
required VoidCallback onSuccess,
}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
final cloudinaryCloudName = dotenv.env['CLOUDINARY_CLOUDNAME'];
final cloudinaryUploadPreset = dotenv.env['CLOUDINARY_UPLOADPRESET'];
final cloudinary =
CloudinaryPublic(cloudinaryCloudName!, cloudinaryUploadPreset!);
List<String> imageUrls = [];
String folderName = formatFolderName(name);
String folder = 'products/$category/$folderName';
for (int i = 0; i < images.length; i++) {
CloudinaryResponse res = await cloudinary.uploadFile(
CloudinaryFile.fromFile(images[i].path, folder: folder),
);
imageUrls.add(res.secureUrl);
}
Product product = Product(
name: name,
description: description,
quantity: quantity,
images: imageUrls,
category: category,
price: price);
http.Response res = await http.post(
Uri.parse('$uri/admin/add-product'),
body: product.toJson(),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
);
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
onSuccess();
},
);
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, '${e.toString()} + from admin_services.dart');
}
}
}
Future<List<Product>> fetchAllProducts(
BuildContext context,
) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
List<Product> productList = [];
try {
http.Response res =
await http.get(Uri.parse('$uri/admin/get-products'), headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
});
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
for (int i = 0; i < jsonDecode(res.body).length; i++) {
productList.add(
Product.fromJson(
jsonEncode(
jsonDecode(res.body)[i],
),
),
);
}
});
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
return productList;
}
void deleteProduct({
required BuildContext context,
required Product product,
required VoidCallback onSuccess,
}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
http.Response res = await http.post(
Uri.parse('$uri/admin/delete-product'),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
body: jsonEncode({
'id': product.id,
}),
);
if (context.mounted) {
httpErrorHandle(
context: context,
response: res,
onSuccess: () {
onSuccess();
},
);
}
} catch (e) {
if (context.mounted) {
showSnackBar(context,
'${e.toString()} from admin_services.dart -> deleteProduct');
}
}
}
Future<List<Order>> fetchaAllOrders(BuildContext context) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
List<Order> orderList = [];
try {
http.Response res = await http.get(
Uri.parse("$uri/admin/get-orders"),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
);
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
for (int i = 0; i < jsonDecode(res.body).length; i++) {
orderList.add(
Order.fromJson(
jsonEncode(
jsonDecode(res.body)[i],
),
),
);
}
});
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
return orderList;
}
void changeOrderStatus(
{required BuildContext context,
required Order order,
required int status,
required VoidCallback onSuccess}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
http.Response res =
await http.post(Uri.parse("$uri/admin/change-order-status"),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
body: jsonEncode({
'id': order.id,
'status': status,
}));
if (context.mounted) {
httpErrorHandle(response: res, context: context, onSuccess: onSuccess);
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
}
Future<Map<String, dynamic>> getEarnings(BuildContext context) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
List<Sales> sales = [];
int totalEarning = 0;
try {
http.Response res = await http.get(
Uri.parse("$uri/admin/analytics"),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
);
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
var response = jsonDecode(res.body);
totalEarning = response['totalEarnings'];
sales = [
Sales('Mobiles', response['mobileEarnings'] ?? 0),
Sales('Fashion', response['fashionEarnings'] ?? 0),
Sales('Electronics', response['electronicsEarnings'] ?? 0),
Sales('Home', response['homeEarnings'] ?? 0),
Sales('Beauty', response['beautyEarnings'] ?? 0),
Sales('Appliances', response['appliancesEarnings'] ?? 0),
Sales('Grocery', response['groceryEarnings'] ?? 0),
Sales('Books', response['booksEarnings'] ?? 0),
Sales('Essentials', response['essentialsEarnings'] ?? 0),
];
});
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
return {
'sales': sales,
'totalEarnings': totalEarning,
};
}
Future<List<Product>> getCategoryProducts(
{required BuildContext context, required String category}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
List<Product> categoryProducts = [];
try {
http.Response res = await http.get(
Uri.parse("$uri/admin/get-category-product/$category"),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
});
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
for (int i = 0; i < jsonDecode(res.body).length; i++) {
categoryProducts.add(
Product.fromJson(
jsonEncode(
jsonDecode(res.body)[i],
),
),
);
}
});
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
return categoryProducts;
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/admin | mirrored_repositories/flutterzon_provider/lib/features/admin/screens/category_products_screen_admin.dart | import 'package:amazon_clone_flutter/common/widgets/custom_app_bar.dart';
import 'package:amazon_clone_flutter/constants/utils.dart';
import 'package:amazon_clone_flutter/features/product_details/screens/product_details_screen.dart';
import 'package:flutter/material.dart';
import '../../../models/product.dart';
import '../../account/widgets/single_product.dart';
import '../services/admin_services.dart';
import '../widgets/custom_floating_action_button.dart';
class CategoryProductsScreenAdmin extends StatefulWidget {
static const String routeName = 'category-product-screen-admin';
const CategoryProductsScreenAdmin({super.key, required this.category});
final String category;
@override
State<CategoryProductsScreenAdmin> createState() =>
_CategoryProductsScreenAdminState();
}
class _CategoryProductsScreenAdminState
extends State<CategoryProductsScreenAdmin> {
final AdminServices adminServices = AdminServices();
List<Product>? productsInitial;
List<Product>? products;
fetchCategoryProducts() async {
productsInitial = await adminServices.getCategoryProducts(
context: context, category: widget.category);
products = productsInitial!.reversed.toList();
setState(() {});
}
goToProductPage(Product productData) {
Map<String, dynamic> arguments = {
'product': productData,
'deliveryDate': getDeliveryDate(),
};
Navigator.pushNamed(context, ProductDetailsScreen.routeName,
arguments: arguments);
}
void deleteProduct(Product product, int index) {
adminServices.deleteProduct(
context: context,
product: product,
onSuccess: () {
products!.removeAt(index);
setState(() {});
});
}
@override
void initState() {
super.initState();
fetchCategoryProducts();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const PreferredSize(
preferredSize: Size.fromHeight(60),
child: CustomAppBar(),
),
floatingActionButton: const CustomFloatingActionButton(),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
body: products == null
? const Center(
child: CircularProgressIndicator(),
)
: Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: GridView.builder(
itemCount: products!.length,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemBuilder: (context, index) {
final productData = products![index];
return InkWell(
onTap: () => goToProductPage(productData),
child: Container(
margin: const EdgeInsets.all(6),
padding: const EdgeInsets.symmetric(vertical: 6),
decoration: BoxDecoration(
border: Border.all(
color: Colors.black12,
width: 1.5,
),
borderRadius: BorderRadius.circular(5)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 6,
child:
SingleProduct(image: productData.images[0]),
),
Expanded(
flex: 2,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(
width: 12,
),
Expanded(
child: Text(
productData.name,
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
),
const SizedBox(
width: 4,
),
Container(
height: 40,
width: 40,
decoration: BoxDecoration(
color: Colors.grey.shade200,
borderRadius:
BorderRadius.circular(25)),
child: IconButton(
onPressed: () =>
deleteProduct(productData, index),
icon: const Icon(
Icons.delete_outline,
color: Colors.redAccent,
),
),
),
const SizedBox(
width: 4,
),
],
),
),
],
),
),
);
}),
),
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/admin | mirrored_repositories/flutterzon_provider/lib/features/admin/screens/analytics_screen.dart | import 'package:amazon_clone_flutter/features/admin/services/admin_services.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import '../../../constants/utils.dart';
import '../models/sales.dart';
class AnalyticsScreen extends StatefulWidget {
const AnalyticsScreen({super.key});
@override
State<AnalyticsScreen> createState() => _AnalyticsScreenState();
}
class _AnalyticsScreenState extends State<AnalyticsScreen> {
final AdminServices adminServices = AdminServices();
int? totalSales;
List<Sales>? earnings;
@override
void initState() {
super.initState();
getEarnings();
}
getEarnings() async {
var earningData = await adminServices.getEarnings(context);
totalSales = earningData['totalEarnings'];
earnings = earningData['sales'];
if (mounted) {
setState(() {});
}
}
List<ColumnSeries<Sales, String>> _getDefaultCategory() {
return <ColumnSeries<Sales, String>>[
ColumnSeries<Sales, String>(
dataSource: earnings!,
xValueMapper: (Sales data, _) => data.label,
yValueMapper: (Sales data, _) => data.earning,
pointColorMapper: (Sales data, _) => data.pointColor,
dataLabelSettings: const DataLabelSettings(isVisible: true),
)
];
}
@override
Widget build(BuildContext context) {
return earnings == null || totalSales == null
? const Center(
child: CircularProgressIndicator(),
)
: SingleChildScrollView(
child: Column(
children: [
const SizedBox(
height: 10,
),
Text(
'Total Earnings - ₹${formatLakhs(totalSales!)}',
style: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 0, vertical: 10),
child: SizedBox(
height: MediaQuery.sizeOf(context).height * 0.7,
width: double.infinity,
child: SfCartesianChart(
primaryXAxis: CategoryAxis(
labelRotation: 270,
majorGridLines: const MajorGridLines(width: 0),
),
primaryYAxis: NumericAxis(
isVisible: true,
placeLabelsNearAxisLine: true,
numberFormat: NumberFormat.compact(locale: 'en_IN'),
// labelRotation: 270,
minimum: 0,
maximum: (totalSales! * 3),
majorGridLines: const MajorGridLines(width: 0.5),
),
series: _getDefaultCategory()),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/admin | mirrored_repositories/flutterzon_provider/lib/features/admin/screens/bottom_bar.dart | import 'package:amazon_clone_flutter/constants/utils.dart';
import 'package:amazon_clone_flutter/features/admin/screens/home_screen_admin.dart';
import 'package:amazon_clone_flutter/features/auth/screens/auth_screen.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../constants/global_variables.dart';
import 'analytics_screen.dart';
import 'orders_screen.dart';
class AdminScreen extends StatefulWidget {
static const String routeName = '/admin-screen';
const AdminScreen({super.key});
@override
State<AdminScreen> createState() => _AdminScreenState();
}
class _AdminScreenState extends State<AdminScreen> {
int _page = 0;
double bottomBarWidth = 38;
double bottomBarBorderWidth = 5;
List<Widget> pages = [
const HomeScreenAdmin(),
const AnalyticsScreen(),
const OrdersScreen()
];
void updatePage(int page) {
setState(() {
_page = page;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: const Size.fromHeight(50),
child: AppBar(
flexibleSpace: Container(
decoration:
const BoxDecoration(gradient: GlobalVariables.appBarGradient),
),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
height: 45,
width: 120,
alignment: Alignment.centerLeft,
child: Image.asset('assets/images/amazon_black_logo.png'),
),
Row(
children: [
const Text(
'Admin',
style: TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(width: 6),
IconButton(
onPressed: () async {
try {
SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
await sharedPreferences.setString('x-auth-token', '');
if (context.mounted) {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: ((context) => const AuthScreen())),
(route) => false);
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
},
icon: const Icon(
Icons.power_settings_new,
size: 25,
))
],
),
],
),
),
),
bottomNavigationBar: Theme(
data: ThemeData(
splashColor: Colors.transparent,
highlightColor: Colors.transparent),
child: BottomNavigationBar(
currentIndex: _page,
selectedLabelStyle: TextStyle(
color: GlobalVariables.selectedNavBarColor, fontSize: 13),
unselectedLabelStyle:
const TextStyle(color: Colors.white, fontSize: 13),
selectedItemColor: GlobalVariables.selectedNavBarColor,
unselectedItemColor: GlobalVariables.unselectedNavBarColor,
backgroundColor: GlobalVariables.backgroundColor,
enableFeedback: false,
iconSize: 28,
elevation: 0,
onTap: updatePage,
items: [
bottomNavBarItem(
icon: const Icon(Icons.home_outlined), page: 0, label: 'Home'),
bottomNavBarItem(
icon: const Icon(Icons.analytics_outlined),
page: 1,
label: 'Analytics'),
bottomNavBarItem(
icon: const Icon(Icons.local_shipping_outlined),
page: 2,
label: 'Orders'),
],
),
),
body: pages[_page],
);
}
BottomNavigationBarItem bottomNavBarItem(
{required Widget icon, required int page, required String label}) {
return BottomNavigationBarItem(
icon: Column(
children: [
Container(
width: bottomBarWidth,
height: 6,
decoration: BoxDecoration(
color: _page == page
? GlobalVariables.selectedNavBarColor
: Colors.white,
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(5),
bottomRight: Radius.circular(5),
),
),
),
const SizedBox(
height: 2,
),
icon
],
),
label: label,
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/admin | mirrored_repositories/flutterzon_provider/lib/features/admin/screens/home_screen_admin.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import '../../../constants/global_variables.dart';
import '../../menu/widgets/container_clipper.dart';
import '../widgets/custom_floating_action_button.dart';
import 'category_products_screen_admin.dart';
class HomeScreenAdmin extends StatefulWidget {
const HomeScreenAdmin({super.key});
@override
State<HomeScreenAdmin> createState() => _HomeScreenAdminState();
}
class _HomeScreenAdminState extends State<HomeScreenAdmin> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: const BoxDecoration(
gradient: LinearGradient(colors: [
Color(0xff84D8E3),
Color(0xffA6E6CE),
Color.fromARGB(255, 241, 249, 252),
], stops: [
0,
0.3,
0.7
], begin: Alignment.topLeft, end: Alignment.bottomCenter),
),
child: GridView.builder(
itemCount: GlobalVariables.menuScreenImages.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisSpacing: 10,
mainAxisSpacing: 10,
childAspectRatio: 1.1,
crossAxisCount: 2),
itemBuilder: ((context, index) {
Map<String, String> category =
GlobalVariables.menuScreenImages[index];
return MenuCategoryContainerAdmin(
title: category['category']!,
category: category['category']!,
imageLink: category['image']!,
);
// );
})),
),
floatingActionButton: const CustomFloatingActionButton(),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
);
}
}
class MenuCategoryContainerAdmin extends StatelessWidget {
const MenuCategoryContainerAdmin({
super.key,
required this.title,
required this.imageLink,
required this.category,
});
final String title;
final String imageLink;
final String category;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
Navigator.pushNamed(context, CategoryProductsScreenAdmin.routeName,
arguments: category);
},
child: Container(
height: 170,
width: 125,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.grey.shade500.withOpacity(0.35),
blurRadius: 3,
offset: const Offset(0, 0),
spreadRadius: 3)
],
border: Border.all(color: Colors.grey.shade500, width: 1),
),
child: Stack(
children: [
Positioned(
bottom: 0,
child: ClipPath(
clipper: ContainerClipper(),
child: Container(
height: 170,
width: 200,
decoration: BoxDecoration(
color: const Color.fromARGB(255, 229, 249, 254),
borderRadius: BorderRadius.circular(8),
),
),
),
),
Positioned(
bottom: 4,
left: 0,
right: 0,
child: CachedNetworkImage(
imageUrl: imageLink,
width: 120,
height: 110,
fit: BoxFit.contain,
),
),
Positioned(
left: 16,
top: 10,
child: SizedBox(
width: 100,
child: Text(
title,
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.normal,
fontSize: 16,
),
),
)),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/admin | mirrored_repositories/flutterzon_provider/lib/features/admin/screens/add_product_screen.dart | import 'dart:io';
import 'package:amazon_clone_flutter/common/widgets/custom_elevated_button.dart';
import 'package:amazon_clone_flutter/common/widgets/custom_textfield.dart';
import 'package:amazon_clone_flutter/constants/global_variables.dart';
import 'package:amazon_clone_flutter/constants/utils.dart';
import 'package:amazon_clone_flutter/features/admin/services/admin_services.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
class AddProductScreen extends StatefulWidget {
static const String routeName = 'addProduct';
const AddProductScreen({super.key});
@override
State<AddProductScreen> createState() => _AddProductScreenState();
}
class _AddProductScreenState extends State<AddProductScreen> {
final TextEditingController productNameController = TextEditingController();
final TextEditingController descriptionController = TextEditingController();
final TextEditingController priceController = TextEditingController();
final TextEditingController quantityController = TextEditingController();
final AdminServices adminServices = AdminServices();
final OutlineInputBorder inputBorderStyle = const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black38),
borderRadius: BorderRadius.all(
Radius.circular(5),
),
);
List<String> productCategories = [
'Category',
'Mobiles',
'Fashion',
'Electronics',
'Home',
'Beauty',
'Appliances',
'Grocery',
'Books',
'Essentials',
];
String category = 'Category';
bool isLoading = false;
List<File> images = [];
final _addProductFormKey = GlobalKey<FormState>();
@override
void dispose() {
super.dispose();
productNameController.dispose();
descriptionController.dispose();
priceController.dispose();
quantityController.dispose();
}
void selectImages() async {
var res = await pickImages();
setState(() {
images = res;
});
}
void sellProducts() {
if (_addProductFormKey.currentState!.validate() &&
images.isNotEmpty &&
category != 'Category') {
setState(() {
isLoading = true;
});
try {
adminServices.sellProducts(
context: context,
name: productNameController.text,
description: descriptionController.text,
price: double.parse(priceController.text),
quantity: int.parse(quantityController.text),
category: category,
images: images,
onSuccess: () {
showSnackBar(context, 'Product added succesfully!');
Navigator.pop(context);
setState(() {
isLoading = false;
});
});
} catch (e) {
setState(() {
isLoading = false;
});
showSnackBar(context, e.toString());
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: const Size.fromHeight(50),
child: AppBar(
centerTitle: true,
flexibleSpace: Container(
decoration:
const BoxDecoration(gradient: GlobalVariables.appBarGradient),
),
title: const Text('Add product'),
),
),
body: isLoading
? const Center(
child: CircularProgressIndicator(),
)
: SingleChildScrollView(
child: Form(
key: _addProductFormKey,
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
child: Column(
children: [
images.isNotEmpty
? Column(
children: [
CarouselSlider(
items: images.map((i) {
return Builder(
builder: (context) => Image.file(
i,
fit: BoxFit.cover,
));
}).toList(),
options: CarouselOptions(
height: 200,
viewportFraction: 1,
),
),
const SizedBox(
height: 10,
),
TextButton.icon(
onPressed: selectImages,
style: const ButtonStyle(
side: MaterialStatePropertyAll(
BorderSide(
width: 1,
color: GlobalVariables
.secondaryColor))),
icon: const Icon(Icons.add),
label: const Text('Add photos'))
],
)
: GestureDetector(
onTap: selectImages,
child: DottedBorder(
borderType: BorderType.RRect,
radius: const Radius.circular(10),
dashPattern: const [10, 4],
strokeCap: StrokeCap.round,
child: Container(
width: double.infinity,
height: 150,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.folder_open_outlined,
size: 40,
),
Text('Select product images',
style: TextStyle(
fontSize: 15,
color: Colors.grey.shade400))
],
),
),
),
),
const SizedBox(
height: 6,
),
CustomTextfield(
controller: productNameController,
hintText: 'Product name'),
const SizedBox(
height: 10,
),
CustomTextfield(
controller: descriptionController,
hintText: 'Description',
maxLines: 8,
),
const SizedBox(
height: 10,
),
CustomTextfield(
controller: priceController, hintText: 'Price'),
const SizedBox(
height: 10,
),
CustomTextfield(
controller: quantityController, hintText: 'Quantity'),
const SizedBox(
height: 10,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: DropdownButtonFormField(
decoration: InputDecoration(
focusedBorder: inputBorderStyle,
enabledBorder: inputBorderStyle,
border: inputBorderStyle,
),
items: productCategories.map((String item) {
return DropdownMenuItem(
value: item,
child: Text(
item,
),
);
}).toList(),
value: category,
onChanged: (newVal) {
setState(() {
category = newVal!;
});
},
icon: const Icon(Icons.keyboard_arrow_down),
),
),
const SizedBox(
height: 10,
),
CustomElevatedButton(
buttonText: 'Sell', onPressed: sellProducts),
const SizedBox(
height: 10,
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/admin | mirrored_repositories/flutterzon_provider/lib/features/admin/screens/orders_screen.dart | import 'package:amazon_clone_flutter/features/account/widgets/single_product.dart';
import 'package:amazon_clone_flutter/features/admin/services/admin_services.dart';
import 'package:amazon_clone_flutter/features/order_details/screens/order_details.dart';
import 'package:flutter/material.dart';
import '../../../models/order.dart';
class OrdersScreen extends StatefulWidget {
const OrdersScreen({super.key});
@override
State<OrdersScreen> createState() => _OrdersScreenState();
}
class _OrdersScreenState extends State<OrdersScreen> {
final AdminServices adminServices = AdminServices();
List<Order>? ordersInitial;
List<Order>? orders;
@override
void initState() {
super.initState();
fetchAllProducts();
}
void fetchAllProducts() async {
ordersInitial = await adminServices.fetchaAllOrders(context);
orders = ordersInitial!.reversed.toList();
if (context.mounted) {
setState(() {});
}
}
@override
Widget build(BuildContext context) {
return orders == null
? const Center(
child: CircularProgressIndicator(),
)
: Padding(
padding: const EdgeInsets.all(8.0),
child: GridView.builder(
itemCount: orders!.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2),
itemBuilder: (context, index) {
final orderData = orders![index];
return InkWell(
onTap: () {
Navigator.pushNamed(context, OrderDetailsScreen.routeName,
arguments: orderData);
},
child: Container(
margin: const EdgeInsets.all(6),
padding: const EdgeInsets.symmetric(vertical: 6),
decoration: BoxDecoration(
border: Border.all(
color: Colors.black12,
width: 1.5,
),
borderRadius: BorderRadius.circular(5)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 6,
child: SingleProduct(
image: orderData.products[0].images[0]),
),
Expanded(
flex: 2,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(
width: 12,
),
Expanded(
child: Text(
orderData.products[0].name,
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
),
const SizedBox(
width: 6,
),
Container(
height: 40,
width: 45,
decoration: BoxDecoration(
color: Colors.grey.shade200,
borderRadius: BorderRadius.circular(25)),
child: IconButton(
onPressed: () {
Navigator.pushNamed(
context, OrderDetailsScreen.routeName,
arguments: orderData);
},
icon: const Icon(
Icons.north_east_outlined,
color: Colors.redAccent,
size: 20,
),
),
),
const SizedBox(
width: 4,
),
],
),
),
],
),
),
);
}),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/widgets/top_buttons.dart | import 'package:amazon_clone_flutter/features/account/screens/wish_list_screen.dart';
import 'package:amazon_clone_flutter/features/account/services/account_services.dart';
import 'package:amazon_clone_flutter/features/account/widgets/account_button.dart';
import 'package:flutter/material.dart';
import '../screens/your_orders.dart';
class TopButtons extends StatelessWidget {
const TopButtons({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
AccountButton(
buttonName: 'Your Orders',
onPressed: () =>
Navigator.pushNamed(context, YourOrders.routeName)),
const SizedBox(
width: 10,
),
AccountButton(buttonName: 'Buy Again', onPressed: () {}),
],
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
AccountButton(
buttonName: 'Log Out',
onPressed: () => AccountServices().logOut(context)),
const SizedBox(
width: 10,
),
AccountButton(
buttonName: 'Wish List',
onPressed: () {
Navigator.pushNamed(context, WishListScreen.routeName);
}),
],
),
],
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/widgets/single_wish_list_product.dart | import 'package:amazon_clone_flutter/features/account/services/account_services.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import '../../../common/widgets/stars.dart';
import '../../../constants/global_variables.dart';
import '../../../constants/utils.dart';
import '../../../models/product.dart';
import '../../product_details/screens/product_details_screen.dart';
import '../../product_details/services/product_details_services.dart';
class SingleWishListProduct extends StatefulWidget {
const SingleWishListProduct({
super.key,
required this.product,
required this.deliveryDate,
});
final Product? product;
final String? deliveryDate;
@override
State<SingleWishListProduct> createState() => _SingleWishListProductState();
}
class _SingleWishListProductState extends State<SingleWishListProduct> {
final AccountServices accountServices = AccountServices();
final ProductDetailsServices productDetailsServices =
ProductDetailsServices();
String? price;
@override
void initState() {
super.initState();
price = formatPrice(widget.product!.price);
}
@override
Widget build(BuildContext context) {
const productTextStyle = TextStyle(
fontSize: 12, color: Colors.black54, fontWeight: FontWeight.normal);
double totalRating = 0;
for (int i = 0; i < widget.product!.rating!.length; i++) {
totalRating += widget.product!.rating![i].rating;
}
double averageRating = 0;
if (totalRating != 0) {
averageRating = totalRating / widget.product!.rating!.length;
}
return GestureDetector(
onTap: () {
Navigator.pushNamed(context, ProductDetailsScreen.routeName,
arguments: {
'product': widget.product,
'deliveryDate': widget.deliveryDate,
});
},
child: Container(
height: 230,
margin: const EdgeInsets.symmetric(vertical: 6),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade300, width: 0.5),
borderRadius: BorderRadius.circular(5)),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: 190,
width: 160,
decoration: const BoxDecoration(color: Color(0xffF7F7F7)),
child: Padding(
padding: const EdgeInsets.all(15),
child: CachedNetworkImage(
imageUrl: widget.product!.images[0],
fit: BoxFit.contain,
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(
left: 10, right: 4, top: 4, bottom: 4),
child: Flex(
direction: Axis.vertical,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
widget.product!.name,
maxLines: 2,
style: const TextStyle(
fontSize: 16, overflow: TextOverflow.ellipsis),
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
averageRating.toStringAsFixed(1),
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
color: GlobalVariables.selectedNavBarColor),
),
Stars(
rating: averageRating,
size: 20,
),
Text('(${widget.product!.rating!.length})',
style: productTextStyle.copyWith(fontSize: 14)),
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(
'₹',
style: TextStyle(
fontSize: 18,
color: Colors.black,
fontWeight: FontWeight.w400),
),
Text(
price!,
style: const TextStyle(
fontSize: 24, fontWeight: FontWeight.w400),
),
],
),
// const SizedBox(height: 4),
RichText(
text: TextSpan(
text: 'Get it by ',
style: productTextStyle,
children: [
TextSpan(
text: widget.deliveryDate,
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: Color(0xff56595A)),
)
]),
),
// const SizedBox(height: 4),
const Text(
'FREE Delivery by Amazon',
style: productTextStyle,
),
// const SizedBox(height: 4),
const Text(
'7 days Replacement',
style: productTextStyle,
),
Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
setState(() {
accountServices.addToCartFromWishList(
context: context,
product: widget.product!);
});
},
style: const ButtonStyle(
backgroundColor: MaterialStatePropertyAll(
GlobalVariables.yellowColor)),
child: const Text(
'Add to cart',
style: TextStyle(
color: Colors.black87,
fontWeight: FontWeight.normal),
)),
),
IconButton(
onPressed: () {
setState(() {
accountServices.deleteFromWishList(
context: context, product: widget.product!);
});
},
icon: const Icon(Icons.delete_outline),
)
],
),
],
),
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/widgets/order_list_single.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import '../../../constants/utils.dart';
import '../../../models/order.dart';
import '../../order_details/screens/order_details.dart';
class OrderListSingle extends StatelessWidget {
const OrderListSingle({
super.key,
required this.order,
});
final Order order;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
Navigator.pushNamed(context, OrderDetailsScreen.routeName,
arguments: order);
},
child: Container(
margin: const EdgeInsets.symmetric(vertical: 2),
padding: const EdgeInsets.symmetric(vertical: 6),
decoration: BoxDecoration(
border: Border(
top:
BorderSide(color: Colors.grey.withOpacity(0.8), width: 0.5),
bottom: BorderSide(
color: Colors.grey.withOpacity(0.8), width: 0.5))),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
CachedNetworkImage(
imageUrl: order.products[0].images[0],
height: 75,
// width: 90,
fit: BoxFit.contain,
),
SizedBox(
width: 220,
height: 80,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
order.products[0].name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 16, fontWeight: FontWeight.bold),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'${order.products.length} item(s)',
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.grey,
fontSize: 14,
fontWeight: FontWeight.normal),
),
Text(
formatDate(order.orderedAt),
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.grey,
fontSize: 14,
fontWeight: FontWeight.normal),
),
],
)
],
),
),
const Icon(
Icons.arrow_forward_ios_outlined,
size: 16,
color: Colors.black87,
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/widgets/keep_shopping_for.dart | import 'package:amazon_clone_flutter/features/home/screens/category_deals_screen.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../constants/global_variables.dart';
import '../../../constants/utils.dart';
import '../../../providers/user_provider.dart';
import '../screens/browsing_history.dart';
class KeepShoppingFor extends StatelessWidget {
const KeepShoppingFor({
super.key,
});
@override
Widget build(BuildContext context) {
final user = context.watch<UserProvider>().user;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Keep shopping for',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w400),
),
TextButton(
onPressed: () {
Navigator.pushNamed(context, BrowsingHistory.routeName);
},
child: Text(
'Browsing history',
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 14,
color: GlobalVariables.selectedNavBarColor),
))
],
),
user.keepShoppingFor.isEmpty
? const SizedBox()
: GridView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
mainAxisSpacing: 8,
crossAxisSpacing: 15,
childAspectRatio: user.keepShoppingFor.length == 1
? 2.0
: user.keepShoppingFor.length == 3
? 0.7
: 1.15,
crossAxisCount: user.keepShoppingFor.length >= 4
? 2
: user.keepShoppingFor.length,
),
itemCount: user.keepShoppingFor.length >= 4
? 4
: user.keepShoppingFor.length,
itemBuilder: (context, index) {
if (user.wishList.length >= 4) {
index =
getUniqueRandomInt(max: user.keepShoppingFor.length);
}
return InkWell(
onTap: () {
Navigator.pushNamed(
context, CategoryDealsScreen.routeName,
arguments: user.keepShoppingFor[index]['product']
['category']);
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(
vertical: 7, horizontal: 6),
width: double.infinity,
decoration: BoxDecoration(
border:
Border.all(color: Colors.black12, width: 1.5),
borderRadius: BorderRadius.circular(5),
),
child: CachedNetworkImage(
imageUrl: user.keepShoppingFor[index]['product']
['images'][0],
height: 110,
),
),
const SizedBox(height: 5),
Text(
' ${user.keepShoppingFor[index]['product']['category']}',
style: const TextStyle(
fontSize: 14, color: Colors.black87),
)
],
),
);
},
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/widgets/single_product.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
class SingleProduct extends StatelessWidget {
const SingleProduct({super.key, required this.image});
final String image;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.white,
),
child: Container(
padding: const EdgeInsets.all(8),
child: CachedNetworkImage(imageUrl: image)),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/widgets/account_button.dart | import 'package:flutter/material.dart';
import '../../../constants/global_variables.dart';
class AccountButton extends StatelessWidget {
const AccountButton(
{super.key, required this.buttonName, required this.onPressed});
final String buttonName;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return Expanded(
child: Container(
height: 45,
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade400, width: 0.5),
borderRadius: BorderRadius.circular(50),
color: Colors.white),
child: OutlinedButton(
onPressed: onPressed,
style: ButtonStyle(
splashFactory: NoSplash.splashFactory,
overlayColor: MaterialStatePropertyAll(Colors.grey.shade100),
backgroundColor: MaterialStatePropertyAll(
Colors.grey.shade100.withOpacity(0.40)),
side: const MaterialStatePropertyAll(
BorderSide(color: GlobalVariables.greyBackgroundColor))),
child: Text(
buttonName,
style: const TextStyle(
fontWeight: FontWeight.normal,
color: Colors.black,
fontSize: 15),
)),
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/widgets/orders.dart | import 'package:amazon_clone_flutter/constants/global_variables.dart';
import 'package:amazon_clone_flutter/features/account/screens/your_orders.dart';
import 'package:amazon_clone_flutter/features/account/services/account_services.dart';
import 'package:amazon_clone_flutter/features/order_details/screens/order_details.dart';
import 'package:flutter/material.dart';
import '../../../models/order.dart';
import 'single_product.dart';
class Orders extends StatefulWidget {
const Orders({super.key});
@override
State<Orders> createState() => _OrdersState();
}
class _OrdersState extends State<Orders> {
List<Order>? orders;
final AccountServices accountServices = AccountServices();
@override
void initState() {
super.initState();
fetchOrders();
}
void fetchOrders() async {
orders = await accountServices.fetchMyOrders(context: context);
orders = orders!.reversed.toList();
if (context.mounted) {
setState(() {});
}
}
void navigateToOrderDetailsScreen(Order order) {
Navigator.pushNamed(context, OrderDetailsScreen.routeName,
arguments: order);
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Your Orders',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w400),
),
TextButton(
onPressed: () =>
Navigator.pushNamed(context, YourOrders.routeName),
child: Text(
'See all',
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 14,
color: GlobalVariables.selectedNavBarColor),
))
],
),
orders == null
? SizedBox(
height: 170,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 5,
itemBuilder: (context, index) {
return Container(
width: 200,
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: Colors.white,
border:
Border.all(color: Colors.black12, width: 1.5),
borderRadius: BorderRadius.circular(5),
),
);
}),
)
: SizedBox(
height: 170,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: orders!.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () =>
navigateToOrderDetailsScreen(orders![index]),
child: Container(
width: 200,
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
border: Border.all(
color: Colors.black12, width: 1.5),
borderRadius: BorderRadius.circular(5),
),
child: orders![index].products.length == 1
? SingleProduct(
image:
orders![index].products[0].images[0],
)
: Row(
children: [
SingleProduct(
image: orders![index]
.products[0]
.images[0],
),
Text(
'+ ${orders![index].products.length - 1}',
style: TextStyle(
fontSize: 16,
color: Colors.grey.shade500,
),
)
],
)),
);
}),
)
],
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/widgets/account_screen_app_bar.dart | import 'package:flutter/material.dart';
import '../../../constants/global_variables.dart';
class AccuntScreenAppBar extends StatelessWidget {
const AccuntScreenAppBar({
super.key,
});
@override
Widget build(BuildContext context) {
return AppBar(
flexibleSpace: Container(
decoration:
const BoxDecoration(gradient: GlobalVariables.appBarGradient),
),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
height: 45,
width: 120,
alignment: Alignment.centerLeft,
child: Image.asset('assets/images/amazon_black_logo.png'),
),
Row(
children: [
IconButton(
icon: const Icon(Icons.notifications_outlined),
onPressed: () {},
),
IconButton(
icon: const Icon(Icons.search),
onPressed: () {},
),
],
)
],
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/widgets/name_bar.dart | import 'package:amazon_clone_flutter/constants/utils.dart';
import 'package:amazon_clone_flutter/providers/user_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class NameBar extends StatelessWidget {
const NameBar({super.key});
@override
Widget build(BuildContext context) {
final user = Provider.of<UserProvider>(context).user.name;
return Container(
height: 120,
padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 10),
width: MediaQuery.sizeOf(context).width,
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xff92DDE6),
Color(0xffA6E6CE),
]),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Hello, ',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.w400),
),
Text(
capitalizeFirstLetter(string: user),
style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
),
],
));
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/widgets/wish_list.dart | import 'package:amazon_clone_flutter/constants/utils.dart';
import 'package:amazon_clone_flutter/features/product_details/screens/product_details_screen.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../constants/global_variables.dart';
import '../../../models/product.dart';
import '../../../providers/user_provider.dart';
import '../screens/wish_list_screen.dart';
class WishList extends StatelessWidget {
const WishList({
super.key,
});
@override
Widget build(BuildContext context) {
final user = context.watch<UserProvider>().user;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Your Wish List',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w400),
),
TextButton(
onPressed: () {
Navigator.pushNamed(context, WishListScreen.routeName);
},
child: Text(
'See all',
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 14,
color: GlobalVariables.selectedNavBarColor),
))
],
),
user.wishList.isEmpty
? const SizedBox()
: GridView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
mainAxisSpacing: 8,
crossAxisSpacing: 15,
childAspectRatio: user.wishList.length == 1
? 2.0
: user.wishList.length == 3
? 0.7
: 1.15,
crossAxisCount:
user.wishList.length >= 4 ? 2 : user.wishList.length,
),
itemCount:
user.wishList.length >= 4 ? 4 : user.wishList.length,
itemBuilder: (context, index) {
if (user.wishList.length >= 6) {
index = getUniqueRandomInt(max: user.wishList.length);
}
return InkWell(
onTap: () {
Map<String, dynamic> arguments = {
'product':
Product.fromMap(user.wishList[index]['product']),
'deliveryDate': getDeliveryDate(),
};
Navigator.pushNamed(
context, ProductDetailsScreen.routeName,
arguments: arguments);
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(
vertical: 7, horizontal: 6),
width: double.infinity,
decoration: BoxDecoration(
border:
Border.all(color: Colors.black12, width: 1.5),
borderRadius: BorderRadius.circular(5),
),
child: CachedNetworkImage(
imageUrl: user.wishList[index]['product']
['images'][0],
height: 110,
),
),
const SizedBox(height: 5),
Text(
' ${user.wishList[index]['product']['name']}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 14, color: Colors.black87),
)
],
),
);
},
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/services/account_services.dart | import 'dart:convert';
import 'package:amazon_clone_flutter/constants/error_handling.dart';
import 'package:amazon_clone_flutter/constants/utils.dart';
import 'package:amazon_clone_flutter/features/auth/screens/auth_screen.dart';
import 'package:amazon_clone_flutter/models/order.dart';
import 'package:amazon_clone_flutter/providers/user_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../../../constants/global_variables.dart';
import '../../../models/product.dart';
import '../../../models/user.dart';
class AccountServices {
Future<List<Order>> fetchMyOrders({
required BuildContext context,
}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
List<Order> orderList = [];
try {
http.Response res =
await http.get(Uri.parse('$uri/api/orders/me'), headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
});
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
for (int i = 0; i < jsonDecode(res.body).length; i++) {
orderList.add(
Order.fromJson(
jsonEncode(
jsonDecode(res.body)[i],
),
),
);
}
},
);
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
return orderList;
}
void logOut(BuildContext context) async {
try {
SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
await sharedPreferences.setString('x-auth-token', '');
if (context.mounted) {
Navigator.pushNamedAndRemoveUntil(
context, AuthScreen.routeName, (route) => false);
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
}
Future<List<Order>> searchOrder(
{required BuildContext context, required String searchQuery}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
List<Order> orders = [];
try {
http.Response res = await http
.get(Uri.parse("$uri/api/orders/search/$searchQuery"), headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
});
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
for (int i = 0; i < jsonDecode(res.body).length; i++) {
orders.add(
Order.fromJson(
jsonEncode(
jsonDecode(res.body)[i],
),
),
);
}
});
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
return orders;
}
void keepShoppingFor(
{required BuildContext context, required Product product}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
http.Response res = await http.post(
Uri.parse('$uri/api/keep-shopping-for'),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
body: jsonEncode(
{
'id': product.id!,
},
),
);
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
User user = userProvider.user.copyWith(
wishList: jsonDecode(res.body)['wishList'],
cart: jsonDecode(res.body)['cart'],
keepShoppingFor: jsonDecode(res.body)['keepShoppingFor'],
saveForLater: jsonDecode(res.body)['saveForLater'],
);
userProvider.setUserFromModel(user);
});
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
}
void addToWishList(
{required BuildContext context, required Product product}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
http.Response res = await http.post(
Uri.parse("$uri/api/add-to-wish-list"),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
body: jsonEncode(
{
'id': product.id!,
},
),
);
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
User user = userProvider.user.copyWith(
wishList: jsonDecode(res.body)['wishList'],
cart: jsonDecode(res.body)['cart'],
keepShoppingFor: jsonDecode(res.body)['keepShoppingFor'],
saveForLater: jsonDecode(res.body)['saveForLater'],
);
userProvider.setUserFromModel(user);
},
);
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
}
void deleteFromWishList(
{required BuildContext context, required Product product}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
http.Response res = await http.delete(
Uri.parse("$uri/api/delete-from-wish-list/${product.id}"),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
);
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
User user = userProvider.user.copyWith(
wishList: jsonDecode(res.body)['wishList'],
cart: jsonDecode(res.body)['cart'],
keepShoppingFor: jsonDecode(res.body)['keepShoppingFor'],
saveForLater: jsonDecode(res.body)['saveForLater'],
);
userProvider.setUserFromModel(user);
});
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
}
void addToCartFromWishList(
{required BuildContext context, required Product product}) async {
final userProvider = Provider.of<UserProvider>(context, listen: false);
try {
http.Response res = await http.post(
Uri.parse("$uri/api/add-to-cart-from-wish-list"),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-auth-token': userProvider.user.token,
},
body: jsonEncode(
{
'id': product.id!,
},
),
);
if (context.mounted) {
httpErrorHandle(
response: res,
context: context,
onSuccess: () {
User user = userProvider.user.copyWith(
wishList: jsonDecode(res.body)['wishList'],
cart: jsonDecode(res.body)['cart'],
keepShoppingFor: jsonDecode(res.body)['keepShoppingFor'],
saveForLater: jsonDecode(res.body)['saveForLater'],
);
userProvider.setUserFromModel(user);
});
}
} catch (e) {
if (context.mounted) {
showSnackBar(context, e.toString());
}
}
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/screens/your_orders.dart | import 'package:amazon_clone_flutter/common/widgets/custom_app_bar.dart';
import 'package:amazon_clone_flutter/constants/global_variables.dart';
import 'package:amazon_clone_flutter/features/account/screens/search_orders_screen.dart';
import 'package:amazon_clone_flutter/features/account/services/account_services.dart';
import 'package:amazon_clone_flutter/models/order.dart';
import 'package:flutter/material.dart';
import '../widgets/order_list_single.dart';
class YourOrders extends StatefulWidget {
static const String routeName = 'your-orders';
const YourOrders({super.key});
@override
State<YourOrders> createState() => _YourOrdersState();
}
class _YourOrdersState extends State<YourOrders> {
final AccountServices accountServices = AccountServices();
List<Order>? orderList;
void fetchOrders() async {
orderList = await accountServices.fetchMyOrders(context: context);
orderList = orderList!.reversed.toList();
if (context.mounted) {
setState(() {});
}
}
@override
void initState() {
super.initState();
fetchOrders();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const PreferredSize(
preferredSize: Size.fromHeight(60),
child: CustomAppBar(),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.symmetric(horizontal: 14, vertical: 8),
child: Text(
'Your Orders',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
),
),
Container(
height: 52,
padding: const EdgeInsets.only(bottom: 3),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey.withOpacity(0.8), width: 0.5),
top: BorderSide(
color: Colors.grey.withOpacity(0.8), width: 0.5),
),
),
child: Center(
child: TextFormField(
onFieldSubmitted: (query) {
Navigator.pushNamed(context, SearchOrderScreeen.routeName,
arguments: query);
},
decoration: InputDecoration(
prefixIcon: const Icon(
Icons.search_outlined,
size: 30,
),
suffixIconConstraints:
const BoxConstraints(minHeight: 42, maxHeight: 42),
suffixIcon: Container(
margin: const EdgeInsets.only(top: 5),
height: 10,
width: 95,
alignment: Alignment.center,
decoration: BoxDecoration(
border: Border(
left: BorderSide(
color: Colors.grey.withOpacity(0.8),
width: 0.5),
),
),
child: const Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
'Filter',
style: TextStyle(
fontSize: 16, color: Colors.black87),
),
Icon(
Icons.arrow_forward_ios_outlined,
size: 16,
color: Colors.black87,
)
],
),
),
hintText: 'Search all orders',
hintStyle: const TextStyle(
color: Colors.black54, fontWeight: FontWeight.normal),
prefixIconColor: GlobalVariables.selectedNavBarColor,
border: InputBorder.none),
),
),
),
const SizedBox(
height: 10,
),
orderList == null
? const Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: orderList!.length,
itemBuilder: ((context, index) {
return OrderListSingle(
order: orderList![index],
);
}))
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/screens/wish_list_screen.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../common/widgets/custom_app_bar.dart';
import '../../../constants/utils.dart';
import '../../../models/product.dart';
import '../../../providers/user_provider.dart';
import '../widgets/single_wish_list_product.dart';
class WishListScreen extends StatefulWidget {
static const String routeName = '/wish-list-screen';
const WishListScreen({super.key});
@override
State<WishListScreen> createState() => _WishListScreenState();
}
class _WishListScreenState extends State<WishListScreen> {
@override
Widget build(BuildContext context) {
final userProvider = Provider.of<UserProvider>(context);
return Scaffold(
appBar: const PreferredSize(
preferredSize: Size.fromHeight(60),
child: CustomAppBar(),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Your Wish List',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
color: Colors.black87),
),
const SizedBox(height: 10),
userProvider.user.wishList.isEmpty
? const Center(
child: Text(
'Your wishlist is empty.',
style: TextStyle(fontSize: 14, color: Colors.black87),
),
)
: ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: userProvider.user.wishList.length,
itemBuilder: ((context, index) {
Product product = Product.fromMap(
userProvider.user.wishList[index]['product']);
return SingleWishListProduct(
product: product, deliveryDate: getDeliveryDate());
})),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutterzon_provider/lib/features/account | mirrored_repositories/flutterzon_provider/lib/features/account/screens/account_screen.dart | import 'package:amazon_clone_flutter/features/account/services/account_services.dart';
import 'package:amazon_clone_flutter/features/account/widgets/name_bar.dart';
import 'package:amazon_clone_flutter/features/product_details/widgets/divider_with_sizedbox.dart';
import 'package:amazon_clone_flutter/models/order.dart';
import 'package:amazon_clone_flutter/providers/user_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../widgets/account_screen_app_bar.dart';
import '../widgets/keep_shopping_for.dart';
import '../widgets/orders.dart';
import '../widgets/top_buttons.dart';
import '../widgets/wish_list.dart';
class AccountScreen extends StatefulWidget {
static const routeName = '/account-screen';
const AccountScreen({super.key});
@override
State<AccountScreen> createState() => _AccountScreenState();
}
List<Order>? orders;
final AccountServices accountServices = AccountServices();
class _AccountScreenState extends State<AccountScreen> {
void fetchOrders() async {
orders = await accountServices.fetchMyOrders(context: context);
orders = orders!.reversed.toList();
if (context.mounted) {
setState(() {});
}
}
@override
void initState() {
super.initState();
fetchOrders();
}
@override
Widget build(BuildContext context) {
final userProvider = Provider.of<UserProvider>(context, listen: false);
return Scaffold(
appBar: const PreferredSize(
preferredSize: Size.fromHeight(50),
child: AccuntScreenAppBar(),
),
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 180,
width: MediaQuery.sizeOf(context).width,
child: Stack(
children: [
const Positioned(top: 0, child: NameBar()),
Positioned(
top: 50,
child: Container(
height: 80,
width: MediaQuery.sizeOf(context).width,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.white.withOpacity(0.1),
Colors.white.withOpacity(0.9)
],
stops: const [
0,
0.45
],
begin: AlignmentDirectional.topCenter,
end: Alignment.bottomCenter),
),
)),
Positioned(
top: 60,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12),
height: 200,
width: MediaQuery.sizeOf(context).width,
child: const TopButtons()),
),
],
),
),
orders == null || orders!.isEmpty
? const SizedBox()
: const Orders(),
const DividerWithSizedBox(
thickness: 4,
sB1Height: 15,
sB2Height: 0,
),
userProvider.user.keepShoppingFor.isNotEmpty
? const Column(
children: [
KeepShoppingFor(),
DividerWithSizedBox(
thickness: 4,
sB1Height: 15,
sB2Height: 4,
),
],
)
: const SizedBox(),
userProvider.user.wishList.isNotEmpty
? const WishList()
: const SizedBox(),
const SizedBox(height: 20),
],
),
),
);
}
}
| 0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.