This commit is contained in:
2026-07-12 04:33:48 +08:00
parent f8a90ad305
commit e7ce0f7bae
151 changed files with 2765 additions and 2947 deletions

View File

@@ -3,10 +3,9 @@ import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart'; import 'package:photo_view/photo_view.dart';
class ImageViewer extends StatefulWidget { class ImageViewer extends StatefulWidget {
final Key key;
final ImageProvider imageProvider; final ImageProvider imageProvider;
ImageViewer(this.imageProvider, {this.key}) : ImageViewer(this.imageProvider, {Key? key}) :
super(key: key); super(key: key);
@override @override

View File

@@ -33,18 +33,15 @@ AlertDialog logoutDialog(BuildContext context) {
.yes_i_am_sure), .yes_i_am_sure),
onPressed: () { onPressed: () {
Navigator.of(context).pop(); Navigator.of(context).pop();
Utils.getBox().then((box) { Utils.prefs?.remove(Constants.KEY_USER_ID);
box.delete(Constants.KEY_USER_ID); Utils.prefs?.remove(Constants.KEY_ACCESS_TOKEN);
box.delete( store.dispatch(
Constants.KEY_ACCESS_TOKEN); new UpdateCurrentUser(null));
store.dispatch( eventBus.fire(
new UpdateCurrentUser(null)); new OnCurrentUserUpdated());
eventBus.fire( Routes.router.navigateTo(
new OnCurrentUserUpdated()); context, '/', replace: true,
Routes.router.navigateTo( clearStack: true);
context, '/', replace: true,
clearStack: true);
});
}, },
) )
], ],

View File

@@ -87,7 +87,7 @@ class OnProductWillAddToCart {
double price; double price;
String description; String description;
Business business; Business business;
GlobalKey buttonKey; GlobalKey? buttonKey;
OnProductWillAddToCart(this.product, this.selections, this.price, this.description, this.business, {this.buttonKey}); OnProductWillAddToCart(this.product, this.selections, this.price, this.description, this.business, {this.buttonKey});
} }

View File

@@ -1,9 +1,4 @@
import 'dart:async';
import 'package:catcher/catcher.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_redux/flutter_redux.dart'; import 'package:flutter_redux/flutter_redux.dart';
import 'package:flutter_wisetronic/pages/buy_service.dart'; import 'package:flutter_wisetronic/pages/buy_service.dart';
@@ -14,12 +9,8 @@ import 'pages/create_online_store_1.dart';
import 'pages/download.dart'; import 'pages/download.dart';
import 'pages/me.dart'; import 'pages/me.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:splashscreen/splashscreen.dart';
// import 'package:uni_links/uni_links.dart';
import 'constants.dart'; import 'constants.dart';
import 'events/eventbus.dart';
import 'events/events.dart';
import 'generated/l10n.dart'; import 'generated/l10n.dart';
import 'pages/home.dart'; import 'pages/home.dart';
import 'pages/plain_page.dart'; import 'pages/plain_page.dart';
@@ -34,20 +25,14 @@ import 'utils/utils.dart';
void main() { void main() {
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
// Enable configureApp will cause route problem.
// configureApp();
setPathUrlStrategy(); setPathUrlStrategy();
runApp(MyApp()); runApp(MyApp());
} }
class MyApp extends StatelessWidget { class MyApp extends StatelessWidget {
String _to = '/';
MyApp() { MyApp() {
Routes.configure(); Routes.configure();
Utils().init(); Utils().init();
Util().init();
// getCurrentPosition();
} }
static getCurrentPosition() async { static getCurrentPosition() async {
@@ -95,27 +80,8 @@ class MyApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
Widget _buildBody() {
return SplashScreen(
seconds: 5,
routeName: _to,
navigateAfterSeconds: Home(title: Constants.APP_TITLE,),
styleTextUnderTheLoader: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
imageBackground: (Image.network(Constants.BASE_API_URL + 'gallery/get-minimanager-splash/')).image,
backgroundColor: Colors.white,
onClick: () {
},
loaderColor: Colors.blue,
);
}
return MaterialApp( return MaterialApp(
debugShowCheckedModeBanner: Constants.DEBUG, debugShowCheckedModeBanner: Constants.DEBUG,
navigatorKey: kIsWeb ? null : Catcher.navigatorKey,
localizationsDelegates: [ localizationsDelegates: [
GlobalMaterialLocalizations.delegate, GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate, GlobalWidgetsLocalizations.delegate,
@@ -124,20 +90,26 @@ class MyApp extends StatelessWidget {
S.delegate, S.delegate,
], ],
supportedLocales: S.delegate.supportedLocales, supportedLocales: S.delegate.supportedLocales,
localeResolutionCallback: (Locale locale, Iterable<Locale> supportedLocales) { localeResolutionCallback: (Locale? locale, Iterable<Locale>? supportedLocales) {
print('Language code: ${locale.languageCode}, Country code: ${locale.countryCode}'); print('Language code: ${locale?.languageCode}, Country code: ${locale?.countryCode}');
for (final supportedLocale in supportedLocales) { if (locale != null && supportedLocales != null) {
if (supportedLocale.languageCode == locale.languageCode) { for (final supportedLocale in supportedLocales) {
store.dispatch(UpdateLocale(locale)); if (supportedLocale.languageCode == locale.languageCode) {
return supportedLocale; store.dispatch(UpdateLocale(locale));
return supportedLocale;
}
} }
} store.dispatch(UpdateLocale(supportedLocales.first));
store.dispatch(UpdateLocale(supportedLocales.first));
return supportedLocales.first; return supportedLocales.first;
}
return null;
}, },
onGenerateRoute: (RouteSettings settings) { onGenerateRoute: (RouteSettings settings) {
final List<String> pathElements = settings.name.split('/'); final uri = Uri.parse(settings.name!);
print('path elements: $pathElements'); final path = uri.path;
print('path: $path');
final List<String> pathElements = path.split('/');
print('path elements --> $pathElements');
if (pathElements[0] != '') { if (pathElements[0] != '') {
return null; return null;
} }

View File

@@ -1,21 +1,21 @@
import 'dart:convert'; import 'dart:convert';
class Address { class Address {
int id; int? id;
String addressLine1; String? addressLine1;
String addressLine2; String? addressLine2;
String city; String? city;
String state; String? state;
String country; String? country;
String zip; String? zip;
String phone; String? phone;
String fax; String? fax;
String email; String? email;
String contactName; String? contactName;
int gender; int? gender;
String lat; String? lat;
String lng; String? lng;
String fullAddress; String? fullAddress;
Address.fromJson(Map<String, dynamic> json) Address.fromJson(Map<String, dynamic> json)
: id = json['id'], : id = json['id'],

View File

@@ -58,7 +58,7 @@ class Business {
String chaseXLogin; String chaseXLogin;
String chaseTransactionKey; String chaseTransactionKey;
String chaseResponseKey; String chaseResponseKey;
DistanceInfo distanceInfo; DistanceInfo? distanceInfo;
int commentsCount; int commentsCount;
bool forceClose; bool forceClose;
bool isPublic; bool isPublic;

View File

@@ -7,18 +7,18 @@ import 'cart_line_item.dart';
import 'extra_fee.dart'; import 'extra_fee.dart';
class CartInfo { class CartInfo {
int id; int? id;
double originPrice; double? originPrice;
double discountPrice; double? discountPrice;
double totalPrice; double? totalPrice;
Business businessInfo; Business? businessInfo;
List<CartLineItem> productList; List<CartLineItem>? productList;
List<ExtraFee> extraFeeList; List<ExtraFee>? extraFeeList;
List<ExtraFee> discountList; List<ExtraFee>? discountList;
int deliveryMethod; int? deliveryMethod;
String shippingMethod; String? shippingMethod;
double amountPaid; double? amountPaid;
String extraData; String? extraData;
CartInfo.fromJson(Map<String, dynamic> json) CartInfo.fromJson(Map<String, dynamic> json)
: id = json['id'], : id = json['id'],
@@ -53,7 +53,7 @@ class CartInfo {
if (productList == null) { if (productList == null) {
productList = [item]; productList = [item];
} else { } else {
productList.add(item); productList!.add(item);
} }
} }
@@ -74,19 +74,19 @@ class CartInfo {
originPrice = 0.0; originPrice = 0.0;
discountPrice = 0.0; discountPrice = 0.0;
totalPrice = 0.0; totalPrice = 0.0;
for (var i = 0; i < productList.length; i++) { for (var i = 0; i < productList!.length; i++) {
newTotal += productList[i].getTotalPrice(); newTotal += productList![i].getTotalPrice();
} }
originPrice = newTotal; originPrice = newTotal;
totalPrice = newTotal; totalPrice = newTotal;
return totalPrice; return totalPrice!;
} }
int getProductListTotalQuantity() { int getProductListTotalQuantity() {
int qty = 0; int qty = 0;
if (productList != null && productList.length > 0) { if (productList != null && productList!.length > 0) {
for (var i = 0; i < productList.length; i++) { for (var i = 0; i < productList!.length; i++) {
qty += productList[i].quantity.round(); qty += productList![i].quantity!.round();
} }
} }
return qty; return qty;

View File

@@ -6,15 +6,15 @@ import 'package:uuid/uuid.dart';
import 'product.dart'; import 'product.dart';
class CartLineItem { class CartLineItem {
int id; int? id;
double unitPrice; double? unitPrice;
double totalPrice; double? totalPrice;
Product product; Product? product;
String name; String? name;
String description; String? description;
double quantity; double? quantity;
String uuid; String? uuid;
String parentUuid; String? parentUuid;
CartLineItem() { CartLineItem() {
uuid = Uuid().v4(); uuid = Uuid().v4();
@@ -48,7 +48,7 @@ class CartLineItem {
} }
double getTotalPrice() { double getTotalPrice() {
totalPrice = unitPrice * quantity; totalPrice = unitPrice! * quantity!;
return totalPrice; return totalPrice!;
} }
} }

View File

@@ -9,7 +9,7 @@ class Coupon {
String description; String description;
String expirationDate; String expirationDate;
double minAmount; double minAmount;
Business store; Business? store;
double valueAmount; double valueAmount;
bool isPercentage; bool isPercentage;

View File

@@ -4,9 +4,9 @@ import 'dart:convert';
import 'text_value.dart'; import 'text_value.dart';
class DistanceInfo { class DistanceInfo {
TextValue duration; TextValue? duration;
TextValue distance; TextValue? distance;
String status; String? status;
DistanceInfo.fromJson(Map<String, dynamic> json) DistanceInfo.fromJson(Map<String, dynamic> json)
: duration = json['duration'] != null ? TextValue.fromJson(json['duration']) : null, : duration = json['duration'] != null ? TextValue.fromJson(json['duration']) : null,

View File

@@ -14,8 +14,8 @@ class Order {
int id; int id;
int userId; int userId;
int businessId; int businessId;
Business businessInfo; Business? businessInfo;
CartInfo cartInfo; CartInfo? cartInfo;
int status; int status;
double originPrice; double originPrice;
double discountPrice; double discountPrice;
@@ -23,7 +23,7 @@ class Order {
String consignee; String consignee;
String phone; String phone;
String address; String address;
Address shippingAddress; Address? shippingAddress;
int payMethod; int payMethod;
String remark; String remark;
String orderNum; String orderNum;
@@ -33,11 +33,11 @@ class Order {
String paymentStatus; // UNPAID, PAID, PARTIALPAID String paymentStatus; // UNPAID, PAID, PARTIALPAID
double amountPaid; double amountPaid;
List<Fulfillment> fulfillments; List<Fulfillment> fulfillments;
String extraData; String? extraData;
bool hasComment; bool hasComment;
double fee; double fee;
UserPosition shipperPosition; UserPosition shipperPosition;
DistanceInfo deliveryDistance; DistanceInfo? deliveryDistance;
Order.fromJson(Map<String, dynamic> json) Order.fromJson(Map<String, dynamic> json)
: id = json['id'], : id = json['id'],
@@ -100,8 +100,10 @@ class Order {
double getSubtotal() { double getSubtotal() {
double subtotal = 0.0; double subtotal = 0.0;
for (CartLineItem lineItem in cartInfo.productList) { if (cartInfo != null) {
subtotal += lineItem.getTotalPrice(); for (CartLineItem lineItem in cartInfo!.productList!) {
subtotal += lineItem.getTotalPrice();
}
} }
return subtotal; return subtotal;
} }

View File

@@ -6,19 +6,19 @@ import 'package:flutter/cupertino.dart';
import '../generated/l10n.dart'; import '../generated/l10n.dart';
class PaymentPlatform { class PaymentPlatform {
int id; int? id;
String name; String? name;
String code; String? code;
String method; String? method;
String icon; String? icon;
String xLogin; String? xLogin;
String transactionKey; String? transactionKey;
String responseKey; String? responseKey;
String squareAppId; String? squareAppId;
String squareAccessToken; String? squareAccessToken;
String squareLocationId; String? squareLocationId;
String publishableKey; String? publishableKey;
String merchantId; String? merchantId;
PaymentPlatform(this.code); PaymentPlatform(this.code);
@@ -57,16 +57,12 @@ class PaymentPlatform {
switch(code) { switch(code) {
case 'chase': case 'chase':
return S.of(context).credit_debit_card; return S.of(context).credit_debit_card;
break;
case 'web-credit-card': case 'web-credit-card':
return S.of(context).credit_card; return S.of(context).credit_card;
break;
case 'ALIPAY': case 'ALIPAY':
return S.of(context).alipay; return S.of(context).alipay;
break;
case 'WECHATPAY': case 'WECHATPAY':
return S.of(context).wechatpay; return S.of(context).wechatpay;
break;
case 'paypal': case 'paypal':
return S.of(context).paypal; return S.of(context).paypal;
case 'payondeliverypickup': case 'payondeliverypickup':

View File

@@ -3,7 +3,7 @@ class Position {
final double latitude; final double latitude;
final double longitude; final double longitude;
Position({this.latitude, this.longitude}); Position({required this.latitude, required this.longitude});
@override @override
bool operator ==(other) { bool operator ==(other) {

View File

@@ -5,23 +5,23 @@ import 'Subproduct.dart';
import 'product_attribute.dart'; import 'product_attribute.dart';
class Product { class Product {
int id; int? id;
int businessId; int? businessId;
int categoryId; int? categoryId;
String name; String? name;
double price; double? price;
double regularPrice; double? regularPrice;
String description; String? description;
String detailDescription; String? detailDescription;
String imagePath; String? imagePath;
String secondImagePath; String? secondImagePath;
double monthSales; double? monthSales;
int rate; int? rate;
double leftNum; double? leftNum;
List<ProductAttribute> productAttributes; List<ProductAttribute>? productAttributes;
bool nonInventory; bool? nonInventory;
String extraData; String? extraData;
List<Subproduct> subproducts; List<Subproduct>? subproducts;
Product(int id, int businessId, String name, double price, String description, Product(int id, int businessId, String name, double price, String description,
String imagePath, List<ProductAttribute> productAttributes) { String imagePath, List<ProductAttribute> productAttributes) {

View File

@@ -10,7 +10,7 @@ class ProductAttribute {
bool singleSelection; bool singleSelection;
bool byQuantity; bool byQuantity;
bool required; bool required;
String extra; String? extra;
bool disabled; bool disabled;
ProductAttribute.fromJson(Map<String, dynamic> json) ProductAttribute.fromJson(Map<String, dynamic> json)

View File

@@ -4,8 +4,8 @@ import 'dart:convert';
import 'waiting_line_item.dart'; import 'waiting_line_item.dart';
class WaitingLine { class WaitingLine {
List<WaitingLineItem> waitingLines; List<WaitingLineItem>? waitingLines;
String storeSn; String? storeSn;
WaitingLine.fromJson(Map<String, dynamic> json) WaitingLine.fromJson(Map<String, dynamic> json)
: waitingLines = (json['waiting_lines'] as List).map((i) => WaitingLineItem.fromJson(i)).toList(), : waitingLines = (json['waiting_lines'] as List).map((i) => WaitingLineItem.fromJson(i)).toList(),

View File

@@ -8,19 +8,16 @@ import '../models/product.dart';
class AttributeSelection extends StatelessWidget { class AttributeSelection extends StatelessWidget {
final Product product; final Product product;
final Business business; final Business business;
final GlobalKey startKey; final GlobalKey? startKey;
const AttributeSelection({Key key, this.product, this.business, this.startKey}) : super(key: key); const AttributeSelection({Key? key, required this.product, required this.business, this.startKey}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ResponsiveBuilder( return ScreenTypeLayout.builder(
builder: (context, sizingInformation) => mobile: (context) => MobileAttributeSelection(product: product, business: business, startKey: startKey),
ScreenTypeLayout( tablet: (context) => MobileAttributeSelection(product: product, business: business, startKey: startKey),
mobile: MobileAttributeSelection(product: product, business: business, startKey: startKey,), desktop: (context) => MobileAttributeSelection(product: product, business: business, startKey: startKey),
tablet: MobileAttributeSelection(product: product, business: business, startKey: startKey,),
desktop: MobileAttributeSelection(product: product, business: business, startKey: startKey,),
),
); );
} }

View File

@@ -8,24 +8,20 @@ import '../widgets/desktop/desktop_blog.dart';
import '../widgets/mobile/mobile_blog.dart'; import '../widgets/mobile/mobile_blog.dart';
class Blog extends StatelessWidget { class Blog extends StatelessWidget {
final Key key;
final int businessId; final int businessId;
const Blog({this.key, int businessId}) : const Blog({Key? key, required int businessId}) :
businessId = businessId ?? Constants.BUSINESS_ID; businessId = businessId ?? Constants.BUSINESS_ID;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ResponsiveBuilder( return ScreenTypeLayout.builder(
builder: (context, sizingInformation) => mobile: (context) => MobileBlog(businessId: businessId),
ScreenTypeLayout( tablet: (context) => DesktopBlog(businessId: businessId),
mobile: MobileBlog(businessId: businessId,), desktop: (context) => Scrollbar(
tablet: DesktopBlog(businessId: businessId,), thumbVisibility: true,
desktop: Scrollbar( child: DesktopBlog(businessId: businessId),
isAlwaysShown: true, ),
child: DesktopBlog(businessId: businessId,),
),
),
); );
} }

View File

@@ -19,10 +19,10 @@ import '../widgets/mobile/mobile_renew_license.dart';
class BuyService extends StatefulWidget { class BuyService extends StatefulWidget {
final int gid; final int gid;
final String serviceName; final String serviceName;
final String domain; final String? domain;
final int sid; final int? sid;
const BuyService(this.gid, this.serviceName, {Key key, this.domain, this.sid = 0}) : const BuyService(this.gid, this.serviceName, {Key? key, this.domain, this.sid = 0}) :
super(key: key); super(key: key);
@override @override
@@ -30,7 +30,7 @@ class BuyService extends StatefulWidget {
} }
class BuyServiceState extends State<BuyService> { class BuyServiceState extends State<BuyService> {
Map<String, dynamic> data; Map<String, dynamic>? data;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -48,13 +48,10 @@ class BuyServiceState extends State<BuyService> {
); );
} }
return ResponsiveBuilder( return ScreenTypeLayout.builder(
builder: (context, sizingInformation) => mobile: (context) => MobileBuyService(data),
ScreenTypeLayout( tablet: (context) => DesktopBuyService(data),
mobile: MobileBuyService(data), desktop: (context) => DesktopBuyService(data),
tablet: DesktopBuyService(data),
desktop: DesktopBuyService(data),
),
); );
} }
@@ -73,7 +70,7 @@ class BuyServiceState extends State<BuyService> {
} }
).then((value) { ).then((value) {
data = value; data = value;
data['domain'] = widget.domain; data?['domain'] = widget.domain;
print('data: $data'); print('data: $data');
setState(() {}); setState(() {});
}).onError((error, stackTrace) { }).onError((error, stackTrace) {

View File

@@ -15,7 +15,7 @@ import '../widgets/mobile/mobile_change_mobile_or_email.dart';
class ChangeMobileOrEmail extends StatelessWidget { class ChangeMobileOrEmail extends StatelessWidget {
final bool isMobile; final bool isMobile;
const ChangeMobileOrEmail(this.isMobile, {Key key}) : super(key: key); const ChangeMobileOrEmail(this.isMobile, {Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -31,15 +31,15 @@ class ChangeMobileOrEmail extends StatelessWidget {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: null, drawer: null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileChangeMobileOrEmail(isMobile), mobile: (context) => MobileChangeMobileOrEmail(isMobile),
tablet: DesktopChangeMobileOrEmail(isMobile), tablet: (context) => DesktopChangeMobileOrEmail(isMobile),
desktop: DesktopChangeMobileOrEmail(isMobile), desktop: (context) => DesktopChangeMobileOrEmail(isMobile),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 0,), mobile: (context) => MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -29,15 +29,15 @@ class ChangePassword extends StatelessWidget {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: null, drawer: null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileChangePassword(), mobile: (context) => MobileChangePassword(),
tablet: DesktopChangePassword(), tablet: (context) => DesktopChangePassword(),
desktop: DesktopChangePassword(), desktop: (context) => DesktopChangePassword(),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 0,), mobile: (context) => MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -11,7 +11,7 @@ import '../widgets/mobile/mobile_checkout.dart';
class Checkout extends StatelessWidget { class Checkout extends StatelessWidget {
final int businessId; final int businessId;
const Checkout(this.businessId, {Key key}) : const Checkout(this.businessId, {Key? key}) :
super(key: key); super(key: key);
@override @override
@@ -20,10 +20,10 @@ class Checkout extends StatelessWidget {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileCheckout(businessId), mobile: (context) => MobileCheckout(businessId),
tablet: DesktopCheckout(businessId), tablet: (context) => DesktopCheckout(businessId),
desktop: DesktopCheckout(businessId), desktop: (context) => DesktopCheckout(businessId),
), ),
); );
} }

View File

@@ -14,7 +14,7 @@ import '../widgets/mobile/mobile_contact_us.dart';
class ContactUs extends StatefulWidget { class ContactUs extends StatefulWidget {
final int businessId; final int businessId;
const ContactUs({this.businessId, Key key}) : const ContactUs({required this.businessId, Key? key}) :
super(key: key); super(key: key);
@override @override
@@ -22,7 +22,7 @@ class ContactUs extends StatefulWidget {
} }
class ContactUsState extends State<ContactUs> { class ContactUsState extends State<ContactUs> {
Business business; Business? business;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -42,10 +42,10 @@ class ContactUsState extends State<ContactUs> {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileContactUs(business), mobile: (context) => MobileContactUs(business!),
tablet: DesktopContactUs(business), tablet: (context) => DesktopContactUs(business!),
desktop: DesktopContactUs(business), desktop: (context) => DesktopContactUs(business!),
), ),
); );
} }

View File

@@ -10,7 +10,7 @@ import '../widgets/mobile/mobile_coupons.dart';
class Coupons extends StatelessWidget { class Coupons extends StatelessWidget {
final int contactId; final int contactId;
const Coupons(this.contactId, {Key key}) : const Coupons(this.contactId, {Key? key}) :
super(key: key); super(key: key);
@@ -20,10 +20,10 @@ class Coupons extends StatelessWidget {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileCoupons(contactId,), mobile: (context) => MobileCoupons(contactId,),
tablet: DesktopCoupons(contactId,), tablet: (context) => DesktopCoupons(contactId,),
desktop: DesktopCoupons(contactId,), desktop: (context) => DesktopCoupons(contactId,),
), ),
); );
} }

View File

@@ -11,7 +11,7 @@ import '../widgets/mobile/create_online_store_1.dart' as mobile;
class CreateOnlineStore1 extends StatefulWidget { class CreateOnlineStore1 extends StatefulWidget {
const CreateOnlineStore1({Key key}) : const CreateOnlineStore1({Key? key}) :
super(key: key); super(key: key);
@override @override
@@ -33,10 +33,10 @@ class CreateOnlineStore1State extends State<CreateOnlineStore1> {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: mobile.CreateOnlineStore1(Constants.BUSINESS_ID), mobile: (context) => mobile.CreateOnlineStore1(Constants.BUSINESS_ID),
tablet: desktop.CreateOnlineStore1(Constants.BUSINESS_ID), tablet: (context) => desktop.CreateOnlineStore1(Constants.BUSINESS_ID),
desktop: desktop.CreateOnlineStore1(Constants.BUSINESS_ID), desktop: (context) => desktop.CreateOnlineStore1(Constants.BUSINESS_ID),
), ),
); );
} }

View File

@@ -30,7 +30,7 @@ class Download extends StatefulWidget {
class DownloadState extends State<Download> { class DownloadState extends State<Download> {
final _scaffoldKey = GlobalKey<ScaffoldState>(); final _scaffoldKey = GlobalKey<ScaffoldState>();
Map<String, dynamic> data; Map<String, dynamic>? data;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -57,18 +57,18 @@ class DownloadState extends State<Download> {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? MobileNavigationDrawer() : null, drawer: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? MobileNavigationDrawer() : null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileDownloadApps(data), mobile: (context) => MobileDownloadApps(data!),
tablet: DesktopDownloadApps(data), tablet: (context) => DesktopDownloadApps(data!),
desktop: Scrollbar( desktop: (context) => Scrollbar(
isAlwaysShown: true, thumbVisibility: true,
child: DesktopDownloadApps(data), child: DesktopDownloadApps(data!),
), ),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(), mobile: (context) => MobileBottomNav(),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );
@@ -79,7 +79,7 @@ class DownloadState extends State<Download> {
super.initState(); super.initState();
eventBus.on<OpenDrawer>().listen((event) { eventBus.on<OpenDrawer>().listen((event) {
if (mounted) { if (mounted) {
_scaffoldKey.currentState.openDrawer(); _scaffoldKey.currentState?.openDrawer();
} }
}); });
_loadData(); _loadData();

View File

@@ -13,20 +13,19 @@ import '../widgets/general/navigationbar.dart';
import '../widgets/mobile/MobileBottomNav.dart'; import '../widgets/mobile/MobileBottomNav.dart';
class EditAddress extends StatelessWidget { class EditAddress extends StatelessWidget {
final Key key; final Address? address;
final Address address; final int? businessId;
final int businessId; const EditAddress(this.address, {Key? key, int? businessId}) :
const EditAddress(this.address, {this.key, int businessId}) :
businessId = businessId ?? Constants.BUSINESS_ID; businessId = businessId ?? Constants.BUSINESS_ID;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileEditAddress(address, businessId: businessId,), mobile: (context) => MobileEditAddress(address, businessId: businessId,),
tablet: DesktopEditAddress(address, businessId: businessId,), tablet: (context) => DesktopEditAddress(address, businessId: businessId,),
desktop: DesktopEditAddress(address, businessId: businessId,), desktop: (context) => DesktopEditAddress(address, businessId: businessId,),
), ),
); );
} }

View File

@@ -12,7 +12,7 @@ import '../widgets/general/navigationbar.dart';
import '../widgets/mobile/MobileBottomNav.dart'; import '../widgets/mobile/MobileBottomNav.dart';
class ForgotPassword extends StatelessWidget { class ForgotPassword extends StatelessWidget {
const ForgotPassword({Key key}) : super(key: key); const ForgotPassword({Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -28,15 +28,15 @@ class ForgotPassword extends StatelessWidget {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: null, drawer: null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileForgotPassword(), mobile: (context) => MobileForgotPassword(),
tablet: DesktopForgotPassword(), tablet: (context) => DesktopForgotPassword(),
desktop: DesktopForgotPassword(), desktop: (context) => DesktopForgotPassword(),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 0,), mobile: (context) => MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -34,7 +34,7 @@ import '../widgets/mobile/mobile_navigation_drawer.dart';
class Home extends StatefulWidget { class Home extends StatefulWidget {
final String title; final String title;
Home({Key key, this.title = ''}) : super(key: key); Home({Key? key, this.title = ''}) : super(key: key);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
@@ -46,11 +46,11 @@ class Home extends StatefulWidget {
class HomeState extends State<Home> { class HomeState extends State<Home> {
final _scaffoldKey = GlobalKey<ScaffoldState>(); final _scaffoldKey = GlobalKey<ScaffoldState>();
List<Gallery> galleries = []; List<Gallery> galleries = [];
String content1Message; String? content1Message;
Map<String, dynamic> content2; Map<String, dynamic>? content2;
StreamSubscription _sub; StreamSubscription? _sub;
Uri _latestUri; Uri? _latestUri;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -74,8 +74,8 @@ class HomeState extends State<Home> {
appBar: MiniNavigationBar(), appBar: MiniNavigationBar(),
drawer: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? MobileNavigationDrawer() : null, drawer: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? MobileNavigationDrawer() : null,
body: DoubleBackToCloseAppWrapper( body: DoubleBackToCloseAppWrapper(
child: ScreenTypeLayout( child: ScreenTypeLayout.builder(
mobile: SingleChildScrollView( mobile: (context) => SingleChildScrollView(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
@@ -86,7 +86,7 @@ class HomeState extends State<Home> {
], ],
), ),
), ),
tablet: SingleChildScrollView( tablet: (context) => SingleChildScrollView(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
@@ -98,8 +98,8 @@ class HomeState extends State<Home> {
], ],
), ),
), ),
desktop: Scrollbar( desktop: (context) => Scrollbar(
isAlwaysShown: true, thumbVisibility: true,
child: SingleChildScrollView( child: SingleChildScrollView(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
@@ -115,10 +115,10 @@ class HomeState extends State<Home> {
), ),
), ),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 0,), mobile: (context) => MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );
@@ -136,7 +136,7 @@ class HomeState extends State<Home> {
_loadData(); _loadData();
eventBus.on<OpenDrawer>().listen((event) { eventBus.on<OpenDrawer>().listen((event) {
if (mounted) { if (mounted) {
_scaffoldKey.currentState.openDrawer(); _scaffoldKey.currentState?.openDrawer();
} }
}); });
WidgetsBinding.instance.addPostFrameCallback((timeStamp) { WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
@@ -163,7 +163,9 @@ class HomeState extends State<Home> {
if (!mounted) return; if (!mounted) return;
_latestUri = Uri.base; _latestUri = Uri.base;
print('uri base $_latestUri'); print('uri base $_latestUri');
eventBus.fire(OnGotDeepLinkUri(_latestUri)); if (_latestUri != null) {
eventBus.fire(OnGotDeepLinkUri(_latestUri!));
}
} else { } else {
// _sub = getUriLinksStream().listen((Uri uri) { // _sub = getUriLinksStream().listen((Uri uri) {
// print('_sub should get uri $uri'); // print('_sub should get uri $uri');

View File

@@ -16,7 +16,7 @@ import '../widgets/mobile/MobileBottomNav.dart';
import '../widgets/mobile/mobile_igoshow_learn_more.dart'; import '../widgets/mobile/mobile_igoshow_learn_more.dart';
class IGoShowLearnMore extends StatefulWidget { class IGoShowLearnMore extends StatefulWidget {
const IGoShowLearnMore({Key key}) : super(key: key); const IGoShowLearnMore({Key? key}) : super(key: key);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
@@ -26,7 +26,7 @@ class IGoShowLearnMore extends StatefulWidget {
class IGoShowLearnMoreState extends State<IGoShowLearnMore> { class IGoShowLearnMoreState extends State<IGoShowLearnMore> {
final _scaffoldKey = GlobalKey<ScaffoldState>(); final _scaffoldKey = GlobalKey<ScaffoldState>();
Map<String, dynamic> data; Map<String, dynamic>? data;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -55,15 +55,15 @@ class IGoShowLearnMoreState extends State<IGoShowLearnMore> {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: null, drawer: null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileiGoShowLearnMore(data), mobile: (context) => MobileiGoShowLearnMore(data!),
tablet: DesktopiGoShowLearnMore(data), tablet: (context) => DesktopiGoShowLearnMore(data!),
desktop: DesktopiGoShowLearnMore(data), desktop: (context) => DesktopiGoShowLearnMore(data!),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 0,), mobile: (context) => MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -14,9 +14,7 @@ import '../widgets/mobile/MobileBottomNav.dart';
import '../widgets/mobile/mobile_login.dart'; import '../widgets/mobile/mobile_login.dart';
class Login extends StatefulWidget { class Login extends StatefulWidget {
final Key key; const Login({Key? key}) : super(key: key);
const Login({this.key}) : super(key: key);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
@@ -50,15 +48,15 @@ class LoginState extends State<Login> {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: null, drawer: null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileLogin(), mobile: (context) => MobileLogin(),
tablet: DesktopLogin(), tablet: (context) => DesktopLogin(),
desktop: DesktopLogin(), desktop: (context) => DesktopLogin(),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 0,), mobile: (context) => MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -15,9 +15,7 @@ import '../widgets/mobile/MobileBottomNav.dart';
import '../widgets/mobile/mobile_me.dart'; import '../widgets/mobile/mobile_me.dart';
class Me extends StatefulWidget { class Me extends StatefulWidget {
final Key key; const Me({Key? key}) : super(key: key);
const Me({this.key}) : super(key: key);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
@@ -52,16 +50,16 @@ class MeState extends State<Me> {
), ),
drawer: null, drawer: null,
body: DoubleBackToCloseAppWrapper( body: DoubleBackToCloseAppWrapper(
child: ScreenTypeLayout( child: ScreenTypeLayout.builder(
mobile: MobileMe(), mobile: (context) => MobileMe(),
tablet: DesktopMe(), tablet: (context) => DesktopMe(),
desktop: DesktopMe(), desktop: (context) => DesktopMe(),
), ),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 3,), mobile: (context) => MobileBottomNav(currentIndex: 3,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -16,7 +16,7 @@ import '../widgets/mobile/MobileBottomNav.dart';
import '../widgets/mobile/mobile_minipos_learn_more.dart'; import '../widgets/mobile/mobile_minipos_learn_more.dart';
class MiniPosLearnMore extends StatefulWidget { class MiniPosLearnMore extends StatefulWidget {
const MiniPosLearnMore({Key key}) : super(key: key); const MiniPosLearnMore({Key? key}) : super(key: key);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
@@ -26,7 +26,7 @@ class MiniPosLearnMore extends StatefulWidget {
class MiniPosLearnMoreState extends State<MiniPosLearnMore> { class MiniPosLearnMoreState extends State<MiniPosLearnMore> {
final _scaffoldKey = GlobalKey<ScaffoldState>(); final _scaffoldKey = GlobalKey<ScaffoldState>();
Map<String, dynamic> data; Map<String, dynamic>? data;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -42,35 +42,36 @@ class MiniPosLearnMoreState extends State<MiniPosLearnMore> {
); );
} }
return WillPopScope( return ResponsiveBuilder(
child: ResponsiveBuilder( builder: (context, sizingInformation) => PopScope(
builder: (context, sizingInformation) => canPop: true,
Scaffold( onPopInvokedWithResult: (didPop, result) {
key: _scaffoldKey, if (didPop) return;
appBar: MiniNavigationBar( // 可以在这里处理返回逻辑
title: S.of(context).minipos, },
back: true, child: Scaffold(
breadCrumbs: [ key: _scaffoldKey,
BreadCrumb(S.of(context).minipos, null), appBar: MiniNavigationBar(
], title: S.of(context).minipos,
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, back: true,
), breadCrumbs: [
drawer: null, BreadCrumb(S.of(context).minipos, null),
body: ScreenTypeLayout( ],
mobile: MobileMiniPosLearnMore(data), breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
tablet: DesktopMiniPosLearnMore(data),
desktop: DesktopMiniPosLearnMore(data),
),
bottomNavigationBar: ScreenTypeLayout(
mobile: MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(),
desktop: BottomNav(),
),
), ),
drawer: null,
body: ScreenTypeLayout.builder(
mobile: (context) => MobileMiniPosLearnMore(data!),
tablet: (context) => DesktopMiniPosLearnMore(data!),
desktop: (context) => DesktopMiniPosLearnMore(data!),
),
bottomNavigationBar: ScreenTypeLayout.builder(
mobile: (context) => MobileBottomNav(currentIndex: 0),
tablet: (context) => BottomNav(),
desktop: (context) => BottomNav(),
),
),
), ),
onWillPop: () async {
return true;
},
); );
} }

View File

@@ -8,20 +8,19 @@ import '../widgets/desktop/desktop_my_addresses.dart';
import '../widgets/mobile/mobile_my_addresses.dart'; import '../widgets/mobile/mobile_my_addresses.dart';
class MyAddresses extends StatelessWidget { class MyAddresses extends StatelessWidget {
final Key key;
final int businessId; final int businessId;
const MyAddresses({this.key, int businessId}) : const MyAddresses({Key? key, int? businessId}) :
businessId = businessId ?? Constants.BUSINESS_ID; businessId = businessId ?? Constants.BUSINESS_ID;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileMyAddresses(businessId: businessId,), mobile: (context) => MobileMyAddresses(businessId: businessId,),
tablet: DesktopMyAddresses(businessId: businessId,), tablet: (context) => DesktopMyAddresses(businessId: businessId,),
desktop: DesktopMyAddresses(businessId: businessId,), desktop: (context) => DesktopMyAddresses(businessId: businessId,),
), ),
); );
} }

View File

@@ -35,10 +35,10 @@ class MyCards extends StatelessWidget {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileMyCards(), mobile: (context) => MobileMyCards(),
tablet: DesktopMyCards(), tablet: (context) => DesktopMyCards(),
desktop: DesktopMyCards(), desktop: (context) => DesktopMyCards(),
), ),
); );
} }

View File

@@ -8,20 +8,19 @@ import '../widgets/desktop/desktop_my_support.dart';
import '../widgets/mobile/mobile_my_support.dart'; import '../widgets/mobile/mobile_my_support.dart';
class MySupport extends StatelessWidget { class MySupport extends StatelessWidget {
final Key key;
final int businessId; final int businessId;
const MySupport({this.key, int businessId}) : const MySupport({Key? key, int? businessId}) :
businessId = businessId ?? Constants.BUSINESS_ID; businessId = businessId ?? Constants.BUSINESS_ID;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileMySupport(businessId: businessId,), mobile: (context) => MobileMySupport(businessId: businessId,),
tablet: DesktopMySupport(businessId: businessId,), tablet: (context) => DesktopMySupport(businessId: businessId,),
desktop: DesktopMySupport(businessId: businessId,), desktop: (context) => DesktopMySupport(businessId: businessId,),
), ),
); );
} }

View File

@@ -7,25 +7,24 @@ import '../widgets/desktop/desktop_new_address.dart';
import '../widgets/mobile/mobile_new_address.dart'; import '../widgets/mobile/mobile_new_address.dart';
class NewAddress extends StatelessWidget { class NewAddress extends StatelessWidget {
final Key key; final LocatedAddress? locatedAddress;
final LocatedAddress locatedAddress; final int? businessId;
final int businessId; const NewAddress({Key? key, this.locatedAddress, this.businessId}) : super(key: key);
const NewAddress({this.key, this.locatedAddress, this.businessId}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileNewAddress( mobile: (context) => MobileNewAddress(
locatedAddress: locatedAddress, locatedAddress: locatedAddress,
businessId: businessId, businessId: businessId,
), ),
tablet: DesktopNewAddress( tablet: (context) => DesktopNewAddress(
locatedAddress: locatedAddress, locatedAddress: locatedAddress,
businessId: businessId, businessId: businessId,
), ),
desktop: DesktopNewAddress( desktop: (context) => DesktopNewAddress(
locatedAddress: locatedAddress, locatedAddress: locatedAddress,
businessId: businessId, businessId: businessId,
), ),

View File

@@ -10,7 +10,7 @@ import '../widgets/mobile/mobile_new_comment.dart';
class NewComment extends StatelessWidget { class NewComment extends StatelessWidget {
final int orderId; final int orderId;
const NewComment(this.orderId, {Key key}) : const NewComment(this.orderId, {Key? key}) :
super(key: key); super(key: key);
@@ -20,10 +20,10 @@ class NewComment extends StatelessWidget {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileNewComment(orderId,), mobile: (context) => MobileNewComment(orderId,),
tablet: DesktopNewComment(orderId,), tablet: (context) => DesktopNewComment(orderId,),
desktop: DesktopNewComment(orderId,), desktop: (context) => DesktopNewComment(orderId,),
), ),
); );
} }

View File

@@ -14,10 +14,9 @@ import '../widgets/mobile/MobileBottomNav.dart';
import '../widgets/mobile/mobile_new_ticket.dart'; import '../widgets/mobile/mobile_new_ticket.dart';
class NewTicket extends StatefulWidget { class NewTicket extends StatefulWidget {
final Key key; final int? businessId;
final int businessId;
const NewTicket({this.key, int businessId}) : const NewTicket({Key? key, int? businessId}) :
businessId = businessId ?? Constants.BUSINESS_ID; businessId = businessId ?? Constants.BUSINESS_ID;
@override @override
@@ -52,15 +51,15 @@ class NewTicketState extends State<NewTicket> {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: null, drawer: null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileNewTicket(businessId: widget.businessId,), mobile: (context) => MobileNewTicket(businessId: widget.businessId!,),
tablet: DesktopNewTicket(businessId: widget.businessId,), tablet: (context) => DesktopNewTicket(businessId: widget.businessId!,),
desktop: DesktopNewTicket(businessId: widget.businessId,), desktop: (context) => DesktopNewTicket(businessId: widget.businessId!,),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 0,), mobile: (context) => MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -12,7 +12,7 @@ import '../widgets/mobile/MobileBottomNav.dart';
import '../widgets/mobile/mobile_new_user.dart'; import '../widgets/mobile/mobile_new_user.dart';
class NewUser extends StatelessWidget { class NewUser extends StatelessWidget {
const NewUser({Key key}) : super(key: key); const NewUser({Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -28,15 +28,15 @@ class NewUser extends StatelessWidget {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: null, drawer: null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileNewUser(), mobile: (context) => MobileNewUser(),
tablet: DesktopNewUser(), tablet: (context) => DesktopNewUser(),
desktop: DesktopNewUser(), desktop: (context) => DesktopNewUser(),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 0,), mobile: (context) => MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -11,7 +11,7 @@ class OrderDetail extends StatelessWidget {
final int orderId; final int orderId;
final bool fromOrders; final bool fromOrders;
const OrderDetail(this.orderId, {this.fromOrders = false, Key key}) : const OrderDetail(this.orderId, {this.fromOrders = false, Key? key}) :
super(key: key); super(key: key);
@override @override
@@ -20,10 +20,10 @@ class OrderDetail extends StatelessWidget {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileOrderDetail(orderId, fromOrders: fromOrders,), mobile: (context) => MobileOrderDetail(orderId, fromOrders: fromOrders,),
tablet: DesktopOrderDetail(orderId, fromOrders: fromOrders,), tablet: (context) => DesktopOrderDetail(orderId, fromOrders: fromOrders,),
desktop: DesktopOrderDetail(orderId, fromOrders: fromOrders,), desktop: (context) => DesktopOrderDetail(orderId, fromOrders: fromOrders,),
), ),
); );
} }

View File

@@ -10,7 +10,7 @@ import '../widgets/mobile/mobile_pay_now.dart';
class PayNow extends StatelessWidget { class PayNow extends StatelessWidget {
final int orderId; final int orderId;
const PayNow(this.orderId, {Key key}) : const PayNow(this.orderId, {Key? key}) :
super(key: key); super(key: key);
@@ -20,10 +20,10 @@ class PayNow extends StatelessWidget {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobilePayNow(orderId,), mobile: (context) => MobilePayNow(orderId,),
tablet: DesktopPayNow(orderId,), tablet: (context) => DesktopPayNow(orderId,),
desktop: DesktopPayNow(orderId,), desktop: (context) => DesktopPayNow(orderId,),
), ),
); );
} }

View File

@@ -13,9 +13,9 @@ import '../utils/utils.dart';
class PlainPage extends StatefulWidget { class PlainPage extends StatefulWidget {
final int businessId; final int businessId;
final String slug; final String? slug;
const PlainPage(this.slug, {this.businessId, Key key}) : const PlainPage(this.slug, {required this.businessId, Key? key}) :
super(key: key); super(key: key);
@override @override
@@ -23,7 +23,7 @@ class PlainPage extends StatefulWidget {
} }
class PlainPageState extends State<PlainPage> { class PlainPageState extends State<PlainPage> {
Blog blog; Blog? blog;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -43,10 +43,10 @@ class PlainPageState extends State<PlainPage> {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobilePlainPage(blog), mobile: (context) => MobilePlainPage(blog!),
tablet: DesktopPlainPage(blog), tablet: (context) => DesktopPlainPage(blog!),
desktop: DesktopPlainPage(blog), desktop: (context) => DesktopPlainPage(blog!),
), ),
); );
} }

View File

@@ -13,7 +13,7 @@ class ProductDetailPage extends StatelessWidget {
final Business business; final Business business;
final Product product; final Product product;
const ProductDetailPage({this.business, this.product, Key key}) : const ProductDetailPage({required this.business, required this.product, Key? key}) :
super(key: key); super(key: key);
@@ -23,10 +23,10 @@ class ProductDetailPage extends StatelessWidget {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileProductDetailPage(business: business, product: product,), mobile: (context) => MobileProductDetailPage(business: business, product: product,),
tablet: DesktopProductDetailPage(business: business, product: product,), tablet: (context) => DesktopProductDetailPage(business: business, product: product,),
desktop: DesktopProductDetailPage(business: business, product: product,), desktop: (context) => DesktopProductDetailPage(business: business, product: product,),
), ),
); );
} }

View File

@@ -9,16 +9,16 @@ import '../widgets/mobile/product_search.dart' as mobile;
class ProductSearch extends StatelessWidget { class ProductSearch extends StatelessWidget {
final Business business; final Business business;
const ProductSearch(this.business, {Key key}) : super(key: key); const ProductSearch(this.business, {Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: mobile.ProductSearch(business), mobile: (context) => mobile.ProductSearch(business),
tablet: desktop.ProductSearch(business), tablet: (context) => desktop.ProductSearch(business),
desktop: desktop.ProductSearch(business), desktop: (context) => desktop.ProductSearch(business),
), ),
); );
} }

View File

@@ -12,7 +12,7 @@ import '../widgets/mobile/mobile_renew_license.dart';
class RenewLicense extends StatefulWidget { class RenewLicense extends StatefulWidget {
const RenewLicense({Key key}) : const RenewLicense({Key? key}) :
super(key: key); super(key: key);
@override @override
@@ -28,10 +28,10 @@ class RenewLicenseState extends State<RenewLicense> {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileRenewLicense(Constants.BUSINESS_ID), mobile: (context) => MobileRenewLicense(Constants.BUSINESS_ID),
tablet: DesktopRenewLicense(Constants.BUSINESS_ID), tablet: (context) => DesktopRenewLicense(Constants.BUSINESS_ID),
desktop: DesktopRenewLicense(Constants.BUSINESS_ID), desktop: (context) => DesktopRenewLicense(Constants.BUSINESS_ID),
), ),
); );
} }

View File

@@ -17,7 +17,7 @@ import '../widgets/mobile/mobile_renew_license.dart';
class RenewMiniOffice extends StatefulWidget { class RenewMiniOffice extends StatefulWidget {
final int gid; final int gid;
const RenewMiniOffice(this.gid, {Key key}) : const RenewMiniOffice(this.gid, {Key? key}) :
super(key: key); super(key: key);
@override @override
@@ -25,7 +25,7 @@ class RenewMiniOffice extends StatefulWidget {
} }
class RenewMiniOfficeState extends State<RenewMiniOffice> { class RenewMiniOfficeState extends State<RenewMiniOffice> {
Map<String, dynamic> data; Map<String, dynamic>? data;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -45,10 +45,10 @@ class RenewMiniOfficeState extends State<RenewMiniOffice> {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileRenewMiniOffice(data), mobile: (context) => MobileRenewMiniOffice(data!),
tablet: DesktopRenewMiniOffice(data), tablet: (context) => DesktopRenewMiniOffice(data!),
desktop: DesktopRenewMiniOffice(data), desktop: (context) => DesktopRenewMiniOffice(data!),
), ),
); );
} }

View File

@@ -14,7 +14,7 @@ import '../widgets/mobile/mobile_reset_password.dart';
class ResetPassword extends StatelessWidget { class ResetPassword extends StatelessWidget {
final String mobile; final String mobile;
final String code; final String code;
const ResetPassword(this.mobile, {Key key, this.code}) : super(key: key); const ResetPassword(this.mobile, {Key? key, required this.code}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -30,15 +30,15 @@ class ResetPassword extends StatelessWidget {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: null, drawer: null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileResetPassword(mobile, code: code,), mobile: (context) => MobileResetPassword(mobile, code: code,),
tablet: DesktopResetPassword(mobile, code: code,), tablet: (context) => DesktopResetPassword(mobile, code: code,),
desktop: DesktopResetPassword(mobile, code: code,), desktop: (context) => DesktopResetPassword(mobile, code: code,),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 0,), mobile: (context) => MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -5,18 +5,17 @@ import '../widgets/mobile/mobile_search_place.dart';
import 'package:responsive_builder/responsive_builder.dart'; import 'package:responsive_builder/responsive_builder.dart';
class SearchPlace extends StatelessWidget { class SearchPlace extends StatelessWidget {
final Key key;
final int businessId; final int businessId;
const SearchPlace(this.businessId, {this.key}) : super(key: key); const SearchPlace(this.businessId, {Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileSearchPlace(businessId), mobile: (context) => MobileSearchPlace(businessId),
tablet: DesktopSearchPlace(businessId), tablet: (context) => DesktopSearchPlace(businessId),
desktop: DesktopSearchPlace(businessId), desktop: (context) => DesktopSearchPlace(businessId),
), ),
); );
} }

View File

@@ -14,7 +14,7 @@ import '../widgets/mobile/mobile_set_password.dart';
class SetPassword extends StatelessWidget { class SetPassword extends StatelessWidget {
final String mobile; final String mobile;
final String code; final String code;
const SetPassword(this.mobile, {Key key, this.code}) : super(key: key); const SetPassword(this.mobile, {Key? key, required this.code}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -30,15 +30,15 @@ class SetPassword extends StatelessWidget {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: null, drawer: null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileSetPassword(mobile, code: code,), mobile: (context) => MobileSetPassword(mobile, code: code,),
tablet: DesktopSetPassword(mobile, code: code,), tablet: (context) => DesktopSetPassword(mobile, code: code,),
desktop: DesktopSetPassword(mobile, code: code,), desktop: (context) => DesktopSetPassword(mobile, code: code,),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 0,), mobile: (context) => MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -8,9 +8,9 @@ import '../widgets/desktop/shop.dart' as desktop;
import '../widgets/mobile/shop.dart' as mobile; import '../widgets/mobile/shop.dart' as mobile;
class Shop extends StatefulWidget { class Shop extends StatefulWidget {
final int businessId; final int? businessId;
const Shop({this.businessId, Key key}) : super(key: key); const Shop({this.businessId, Key? key}) : super(key: key);
@override @override
State<StatefulWidget> createState() => ShopState(); State<StatefulWidget> createState() => ShopState();
@@ -20,17 +20,17 @@ class ShopState extends State<Shop> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
int _businessId = int _businessId =
widget.businessId == null ? Utils.getBusinessId() : widget.businessId; widget.businessId == null ? Utils.getBusinessId() : widget.businessId!;
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => ScreenTypeLayout( builder: (context, sizingInformation) => ScreenTypeLayout.builder(
mobile: mobile.Shop( mobile: (context) => mobile.Shop(
businessId: _businessId, businessId: _businessId,
), ),
tablet: desktop.Shop( tablet: (context) => desktop.Shop(
businessId: _businessId, businessId: _businessId,
), ),
desktop: desktop.Shop( desktop: (context) => desktop.Shop(
businessId: _businessId, businessId: _businessId,
), ),
), ),

View File

@@ -15,7 +15,7 @@ import '../widgets/mobile/mobile_store_product_search.dart';
class StoreProductSearch extends StatelessWidget { class StoreProductSearch extends StatelessWidget {
final Business business; final Business business;
const StoreProductSearch(this.business, {Key key}) : super(key: key); const StoreProductSearch(this.business, {Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -31,15 +31,15 @@ class StoreProductSearch extends StatelessWidget {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: null, drawer: null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileStoreProductSearch(business,), mobile: (context) => MobileStoreProductSearch(business,),
tablet: DesktopStoreProductSearch(business), tablet: (context) => DesktopStoreProductSearch(business),
desktop: DesktopStoreProductSearch(business), desktop: (context) => DesktopStoreProductSearch(business),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 1,), mobile: (context) => MobileBottomNav(currentIndex: 1,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -13,7 +13,7 @@ import '../widgets/mobile/mobile_stripe_pay_web.dart';
class StripePayWeb extends StatelessWidget { class StripePayWeb extends StatelessWidget {
final Order order; final Order order;
final PaymentPlatform paymentPlatform; final PaymentPlatform paymentPlatform;
final StripePaymentMethod stripePaymentMethod; final StripePaymentMethod? stripePaymentMethod;
const StripePayWeb(this.order, this.paymentPlatform, {this.stripePaymentMethod}); const StripePayWeb(this.order, this.paymentPlatform, {this.stripePaymentMethod});
@@ -23,10 +23,10 @@ class StripePayWeb extends StatelessWidget {
return ResponsiveBuilder( return ResponsiveBuilder(
builder: (context, sizingInformation) => builder: (context, sizingInformation) =>
ScreenTypeLayout( ScreenTypeLayout.builder(
mobile: MobileStripePayWeb(order, paymentPlatform, stripePaymentMethod: stripePaymentMethod,), mobile: (context) => MobileStripePayWeb(order, paymentPlatform, stripePaymentMethod: stripePaymentMethod,),
tablet: DesktopStripePayWeb(order, paymentPlatform, stripePaymentMethod: stripePaymentMethod,), tablet: (context) => DesktopStripePayWeb(order, paymentPlatform, stripePaymentMethod: stripePaymentMethod,),
desktop: DesktopStripePayWeb(order, paymentPlatform, stripePaymentMethod: stripePaymentMethod,), desktop: (context) => DesktopStripePayWeb(order, paymentPlatform, stripePaymentMethod: stripePaymentMethod,),
), ),
); );
} }

View File

@@ -13,7 +13,7 @@ import '../widgets/mobile/MobileBottomNav.dart';
import '../widgets/mobile/mobile_user_profile.dart'; import '../widgets/mobile/mobile_user_profile.dart';
class UserProfile extends StatelessWidget { class UserProfile extends StatelessWidget {
const UserProfile({Key key}) : super(key: key); const UserProfile({Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -29,15 +29,15 @@ class UserProfile extends StatelessWidget {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: null, drawer: null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileUserProfile(), mobile: (context) => MobileUserProfile(),
tablet: DesktopUserProfile(), tablet: (context) => DesktopUserProfile(),
desktop: DesktopUserProfile(), desktop: (context) => DesktopUserProfile(),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 0,), mobile: (context) => MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -14,10 +14,9 @@ import '../widgets/mobile/MobileBottomNav.dart';
import '../widgets/mobile/mobile_view_blog.dart'; import '../widgets/mobile/mobile_view_blog.dart';
class ViewBlog extends StatefulWidget { class ViewBlog extends StatefulWidget {
final Key key;
final int bid; final int bid;
const ViewBlog(this.bid, {this.key}) : super(key: key); const ViewBlog(this.bid, {Key? key}) : super(key: key);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
@@ -51,15 +50,15 @@ class ViewBlogState extends State<ViewBlog> {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: null, drawer: null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileViewBlog(widget.bid), mobile: (context) => MobileViewBlog(widget.bid),
tablet: DesktopViewBlog(widget.bid), tablet: (context) => DesktopViewBlog(widget.bid),
desktop: DesktopViewBlog(widget.bid), desktop: (context) => DesktopViewBlog(widget.bid),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 0,), mobile: (context) => MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -14,10 +14,9 @@ import '../widgets/mobile/MobileBottomNav.dart';
import '../widgets/mobile/mobile_view_ticket.dart'; import '../widgets/mobile/mobile_view_ticket.dart';
class ViewTicket extends StatefulWidget { class ViewTicket extends StatefulWidget {
final Key key;
final int ticketId; final int ticketId;
const ViewTicket(this.ticketId, {this.key}) : super(key: key); const ViewTicket(this.ticketId, {Key? key}) : super(key: key);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
@@ -51,15 +50,15 @@ class ViewTicketState extends State<ViewTicket> {
breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT, breadCrumbHeight: sizingInformation.deviceScreenType == DeviceScreenType.mobile ? null : Constants.BREADCRUMB_HEIGHT,
), ),
drawer: null, drawer: null,
body: ScreenTypeLayout( body: ScreenTypeLayout.builder(
mobile: MobileViewTicket(widget.ticketId), mobile: (context) => MobileViewTicket(widget.ticketId),
tablet: DesktopViewTicket(widget.ticketId), tablet: (context) => DesktopViewTicket(widget.ticketId),
desktop: DesktopViewTicket(widget.ticketId), desktop: (context) => DesktopViewTicket(widget.ticketId),
), ),
bottomNavigationBar: ScreenTypeLayout( bottomNavigationBar: ScreenTypeLayout.builder(
mobile: MobileBottomNav(currentIndex: 0,), mobile: (context) => MobileBottomNav(currentIndex: 0,),
tablet: BottomNav(), tablet: (context) => BottomNav(),
desktop: BottomNav(), desktop: (context) => BottomNav(),
), ),
), ),
); );

View File

@@ -44,169 +44,169 @@ class Routes {
static void configure() { static void configure() {
router.define('/', handler: new Handler( router.define('/', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return Home(title: Constants.APP_TITLE,); return Home(title: Constants.APP_TITLE,);
}), }),
transitionType: TransitionType.fadeIn transitionType: TransitionType.fadeIn
); );
router.define('/download', handler: new Handler( router.define('/download', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return Download(); return Download();
}), }),
transitionType: TransitionType.inFromRight transitionType: TransitionType.inFromRight
); );
router.define('/minipos-learn-more', handler: new Handler( router.define('/minipos-learn-more', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return MiniPosLearnMore(); return MiniPosLearnMore();
}), }),
transitionType: TransitionType.inFromRight transitionType: TransitionType.inFromRight
); );
router.define('/igoshow-learn-more', handler: new Handler( router.define('/igoshow-learn-more', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return IGoShowLearnMore(); return IGoShowLearnMore();
}), }),
transitionType: TransitionType.inFromRight transitionType: TransitionType.inFromRight
); );
router.define('/login', handler: new Handler( router.define('/login', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return Login(); return Login();
}), }),
transitionType: TransitionType.inFromRight transitionType: TransitionType.inFromRight
); );
router.define('/me', handler: new Handler( router.define('/me', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return Me(); return Me();
}), }),
transitionType: TransitionType.inFromRight transitionType: TransitionType.inFromRight
); );
router.define('/change-password', handler: new Handler( router.define('/change-password', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return ChangePassword(); return ChangePassword();
}), }),
transitionType: TransitionType.inFromRight transitionType: TransitionType.inFromRight
); );
router.define('/user-profile', handler: new Handler( router.define('/user-profile', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return UserProfile(); return UserProfile();
}), }),
transitionType: TransitionType.inFromRight transitionType: TransitionType.inFromRight
); );
router.define('/new-user', handler: new Handler( router.define('/new-user', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return NewUser(); return NewUser();
}), }),
transitionType: TransitionType.inFromRight transitionType: TransitionType.inFromRight
); );
router.define('/set-password/:mobile/:code', handler: new Handler( router.define('/set-password/:mobile/:code', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return SetPassword(params['mobile'][0], code: params['code'][0]); return SetPassword(params['mobile']![0], code: params['code']![0]);
} }
)); ));
router.define('/forgot-password', handler: new Handler( router.define('/forgot-password', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return ForgotPassword(); return ForgotPassword();
} }
)); ));
router.define('/reset-password/:mobile/:code', handler: new Handler( router.define('/reset-password/:mobile/:code', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return ResetPassword(params['mobile'][0], code: params['code'][0]); return ResetPassword(params['mobile']![0], code: params['code']![0]);
} }
)); ));
router.define('/change-mobile-email/:ismobile', handler: new Handler( router.define('/change-mobile-email/:ismobile', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
if (params['ismobile'][0] == '1') { if (params['ismobile']![0] == '1') {
return ChangeMobileOrEmail(true); return ChangeMobileOrEmail(true);
} }
return ChangeMobileOrEmail(false); return ChangeMobileOrEmail(false);
} }
)); ));
router.define('/my-addresses/:business_id', handler: new Handler( router.define('/my-addresses/:business_id', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return MyAddresses(businessId: int.parse(params['business_id'][0]),); return MyAddresses(businessId: int.parse(params['business_id']![0]),);
} }
)); ));
router.define('/my-support/:business_id', handler: new Handler( router.define('/my-support/:business_id', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return MySupport(businessId: int.parse(params['business_id'][0]),); return MySupport(businessId: int.parse(params['business_id']![0]),);
} }
)); ));
router.define('/new-ticket/:business_id', handler: new Handler( router.define('/new-ticket/:business_id', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return NewTicket(businessId: int.parse(params['business_id'][0]),); return NewTicket(businessId: int.parse(params['business_id']![0]),);
} }
)); ));
router.define('/search-place/:business_id', handler: new Handler( router.define('/search-place/:business_id', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return SearchPlace(int.parse(params['business_id'][0])); return SearchPlace(int.parse(params['business_id']![0]));
} }
)); ));
router.define('/view-ticket/:ticket_id', handler: new Handler( router.define('/view-ticket/:ticket_id', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return ViewTicket(int.parse(params['ticket_id'][0]),); return ViewTicket(int.parse(params['ticket_id']![0]),);
} }
)); ));
router.define('/blog/:business_id', handler: new Handler( router.define('/blog/:business_id', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return Blog(businessId: int.parse(params['business_id'][0]),); return Blog(businessId: int.parse(params['business_id']![0]),);
} }
)); ));
router.define('/view-blog/:bid', handler: new Handler( router.define('/view-blog/:bid', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return ViewBlog(int.parse(params['bid'][0]),); return ViewBlog(int.parse(params['bid']![0]),);
} }
)); ));
router.define('/shop/:business_id', handler: new Handler( router.define('/shop/:business_id', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return Shop(businessId: int.parse(params['business_id'][0]),); return Shop(businessId: int.parse(params['business_id']![0]),);
} }
)); ));
router.define('/shop', handler: new Handler( router.define('/shop', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return Shop(); return Shop();
} }
)); ));
// router.define('/ocr-scan', handler: new Handler( // router.define('/ocr-scan', handler: new Handler(
// handlerFunc: (BuildContext context, Map<String, List<String>> params) { // handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
// return OCRScan(); // return OCRScan();
// } // }
// )); // ));
router.define('/checkout/:id', handler: new Handler( router.define('/checkout/:id', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return Checkout(int.parse(params['id'][0])); return Checkout(int.parse(params['id']![0]));
}), }),
); );
router.define('/paynow/:orderId', handler: new Handler( router.define('/paynow/:orderId', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return PayNow(int.parse(params['orderId'][0])); return PayNow(int.parse(params['orderId']![0]));
}), }),
); );
router.define('/orders', handler: new Handler( router.define('/orders', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return Orders(); return Orders();
} }
)); ));
router.define('/my-cards', handler: new Handler( router.define('/my-cards', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return MyCards(); return MyCards();
} }
)); ));
router.define('/orderdetail/:orderId', handler: new Handler( router.define('/orderdetail/:orderId', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return OrderDetail(int.parse(params['orderId'][0])); return OrderDetail(int.parse(params['orderId']![0]));
}), }),
); );
router.define('/new-comment/:orderId', handler: new Handler( router.define('/new-comment/:orderId', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return NewComment(int.parse(params['orderId'][0])); return NewComment(int.parse(params['orderId']![0]));
}), }),
); );
router.define('/coupons/:contactId', handler: new Handler( router.define('/coupons/:contactId', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return Coupons(int.parse(params['contactId'][0])); return Coupons(int.parse(params['contactId']![0]));
}), }),
); );
router.define('/service-policy', handler: new Handler( router.define('/service-policy', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return PlainPage( return PlainPage(
'service-policy', 'service-policy',
// businessId: Constants.BUSINESS_ID, // businessId: Constants.BUSINESS_ID,
@@ -215,7 +215,7 @@ class Routes {
}), }),
); );
router.define('/return-policy', handler: new Handler( router.define('/return-policy', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return PlainPage( return PlainPage(
'return-policy', 'return-policy',
// businessId: Constants.BUSINESS_ID, // businessId: Constants.BUSINESS_ID,
@@ -224,7 +224,7 @@ class Routes {
}), }),
); );
router.define('/privacy-policy', handler: new Handler( router.define('/privacy-policy', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return PlainPage( return PlainPage(
'privacy-policy', 'privacy-policy',
// businessId: Constants.BUSINESS_ID, // businessId: Constants.BUSINESS_ID,
@@ -233,7 +233,7 @@ class Routes {
}), }),
); );
router.define('/end-user-license-agreement', handler: new Handler( router.define('/end-user-license-agreement', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return PlainPage( return PlainPage(
'end-user-license-agreement', 'end-user-license-agreement',
// businessId: Constants.BUSINESS_ID, // businessId: Constants.BUSINESS_ID,
@@ -242,7 +242,7 @@ class Routes {
}), }),
); );
router.define('/about-us', handler: new Handler( router.define('/about-us', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return PlainPage( return PlainPage(
'about-us', 'about-us',
// businessId: Constants.BUSINESS_ID, // businessId: Constants.BUSINESS_ID,
@@ -251,29 +251,29 @@ class Routes {
}), }),
); );
router.define('/contact-us', handler: new Handler( router.define('/contact-us', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return ContactUs( return ContactUs(
businessId: Constants.BUSINESS_ID, businessId: Constants.BUSINESS_ID,
); );
}), }),
); );
router.define('/renew-license', handler: new Handler( router.define('/renew-license', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return RenewLicense(); return RenewLicense();
} }
)); ));
router.define('/renew-minioffice/:gid', handler: new Handler( router.define('/renew-minioffice/:gid', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return RenewMiniOffice(int.parse(params['gid'][0])); return RenewMiniOffice(int.parse(params['gid']![0]));
} }
)); ));
router.define('/buy-service/:gid/:servicename', handler: new Handler( router.define('/buy-service/:gid/:servicename', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return BuyService(int.parse(params['gid'][0]), params['servicename'][0]); return BuyService(int.parse(params['gid']![0]), params['servicename']![0]);
} }
)); ));
router.define('/contact-stores', handler: new Handler( router.define('/contact-stores', handler: new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return CreateOnlineStore1(); return CreateOnlineStore1();
} }
)); ));

View File

@@ -10,17 +10,17 @@ class UpdateContext {
} }
class UpdateLocale { class UpdateLocale {
final Locale locale; final Locale? locale;
UpdateLocale(this.locale); UpdateLocale(this.locale);
} }
class UpdateCurrentUser { class UpdateCurrentUser {
final User user; final User? user;
UpdateCurrentUser(this.user); UpdateCurrentUser(this.user);
} }
class UpdateRedirectRoute { class UpdateRedirectRoute {
final String route; final String? route;
UpdateRedirectRoute(this.route); UpdateRedirectRoute(this.route);
} }

View File

@@ -4,10 +4,10 @@ import 'package:redux/redux.dart';
import '../actions.dart'; import '../actions.dart';
final cartInfoReducer = combineReducers<List<CartInfo>>([ final cartInfoReducer = combineReducers<List<CartInfo>?>([
TypedReducer<List<CartInfo>, UpdateCartInfo>(_updateCartInfo) TypedReducer<List<CartInfo>?, UpdateCartInfo>(_updateCartInfo)
]); ]);
List<CartInfo> _updateCartInfo(List<CartInfo> cartInfos, action) { List<CartInfo> _updateCartInfo(List<CartInfo>? cartInfos, action) {
return action.cartInfos; return action.cartInfos;
} }

View File

@@ -3,10 +3,10 @@ import 'package:flutter/material.dart';
import 'package:flutter_wisetronic/store/actions.dart'; import 'package:flutter_wisetronic/store/actions.dart';
import 'package:redux/redux.dart'; import 'package:redux/redux.dart';
final contextReducer = combineReducers<BuildContext>([ final contextReducer = combineReducers<BuildContext?>([
TypedReducer<BuildContext, UpdateContext>(_updateContext) TypedReducer<BuildContext?, UpdateContext>(_updateContext)
]); ]);
BuildContext _updateContext(BuildContext context, action) { BuildContext _updateContext(BuildContext? context, action) {
return action.context; return action.context;
} }

View File

@@ -2,10 +2,10 @@ import 'package:redux/redux.dart';
import '../actions.dart'; import '../actions.dart';
final deviceIdReducer = combineReducers<String>([ final deviceIdReducer = combineReducers<String?>([
TypedReducer<String, UpdateDeviceId>(_updateDeviceId) TypedReducer<String?, UpdateDeviceId>(_updateDeviceId)
]); ]);
String _updateDeviceId(String deviceId, action) { String _updateDeviceId(String? deviceId, action) {
return action.deviceId; return action.deviceId;
} }

View File

@@ -2,10 +2,10 @@ import 'package:redux/redux.dart';
import '../actions.dart'; import '../actions.dart';
final fcmtokenReducer = combineReducers<String>([ final fcmtokenReducer = combineReducers<String?>([
TypedReducer<String, UpdateFcmToken>(_updateFcmToken) TypedReducer<String?, UpdateFcmToken>(_updateFcmToken)
]); ]);
String _updateFcmToken(String token, action) { String _updateFcmToken(String? token, action) {
return action.token; return action.token;
} }

View File

@@ -2,10 +2,10 @@ import 'package:redux/redux.dart';
import '../actions.dart'; import '../actions.dart';
final lastVisitReducer = combineReducers<List<int>>([ final lastVisitReducer = combineReducers<List<int>?>([
TypedReducer<List<int>, UpdateLastVisit>(_updateLastVisit) TypedReducer<List<int>?, UpdateLastVisit>(_updateLastVisit)
]); ]);
List<int> _updateLastVisit(List<int> lastVisit, action) { List<int> _updateLastVisit(List<int>? lastVisit, action) {
return action.lastVisit; return action.lastVisit;
} }

View File

@@ -2,10 +2,10 @@ import 'package:flutter/material.dart';
import 'package:flutter_wisetronic/store/actions.dart'; import 'package:flutter_wisetronic/store/actions.dart';
import 'package:redux/redux.dart'; import 'package:redux/redux.dart';
final localeReducer = combineReducers<Locale>([ final localeReducer = combineReducers<Locale?>([
TypedReducer<Locale, UpdateLocale>(_updateLocale) TypedReducer<Locale?, UpdateLocale>(_updateLocale)
]); ]);
Locale _updateLocale(Locale locale, action) { Locale _updateLocale(Locale? locale, action) {
return action.locale; return action.locale;
} }

View File

@@ -3,10 +3,10 @@ import 'package:redux/redux.dart';
import '../../models/located_address.dart'; import '../../models/located_address.dart';
import '../actions.dart'; import '../actions.dart';
final locatedAddressReducer = combineReducers<LocatedAddress>([ final locatedAddressReducer = combineReducers<LocatedAddress?>([
TypedReducer<LocatedAddress, UpdateLocatedAddress>(_updateLocatedAddress) TypedReducer<LocatedAddress?, UpdateLocatedAddress>(_updateLocatedAddress)
]); ]);
LocatedAddress _updateLocatedAddress(LocatedAddress locatedAddress, action) { LocatedAddress _updateLocatedAddress(LocatedAddress? locatedAddress, action) {
return action.locatedAddress; return action.locatedAddress;
} }

View File

@@ -2,10 +2,10 @@
import 'package:redux/redux.dart'; import 'package:redux/redux.dart';
import '../actions.dart'; import '../actions.dart';
final redirectRouteReducer = combineReducers<String>([ final redirectRouteReducer = combineReducers<String?>([
TypedReducer<String, UpdateRedirectRoute>(_updateRedirectRoute) TypedReducer<String?, UpdateRedirectRoute>(_updateRedirectRoute)
]); ]);
String _updateRedirectRoute(String route, action) { String? _updateRedirectRoute(String? route, action) {
return action.route; return action.route;
} }

View File

@@ -2,10 +2,10 @@ import 'package:redux/redux.dart';
import '../actions.dart'; import '../actions.dart';
final tableNumberReducer = combineReducers<String>([ final tableNumberReducer = combineReducers<String?>([
TypedReducer<String, UpdateTableNumber>(_updateTableNumber) TypedReducer<String?, UpdateTableNumber>(_updateTableNumber)
]); ]);
String _updateTableNumber(String tableNumber, action) { String _updateTableNumber(String? tableNumber, action) {
return action.tableNumber; return action.tableNumber;
} }

View File

@@ -4,10 +4,10 @@ import 'package:flutter_wisetronic/models/user.dart';
import '../actions.dart'; import '../actions.dart';
final userReducer = combineReducers<User>([ final userReducer = combineReducers<User?>([
TypedReducer<User, UpdateCurrentUser>(_updateCurrentUser) TypedReducer<User?, UpdateCurrentUser>(_updateCurrentUser)
]); ]);
User _updateCurrentUser(User user, action) { User? _updateCurrentUser(User? user, action) {
return action.user; return action.user;
} }

View File

@@ -6,16 +6,16 @@ import '../../models/user.dart';
@immutable @immutable
class AppState { class AppState {
final BuildContext context; final BuildContext? context;
final Locale locale; final Locale? locale;
final User user; final User? user;
final String redirectRoute; final String? redirectRoute;
final List<CartInfo> cartInfos; final List<CartInfo>? cartInfos;
final LocatedAddress locatedAddress; final LocatedAddress? locatedAddress;
final String fcmToken; final String? fcmToken;
final List<int> lastVisit; final List<int>? lastVisit;
final String deviceId; final String? deviceId;
final String tableNumber; final String? tableNumber;
AppState({this.context, this.locale, this.user, this.redirectRoute, AppState({this.context, this.locale, this.user, this.redirectRoute,
this.cartInfos, this.locatedAddress, this.fcmToken, this.lastVisit, this.cartInfos, this.locatedAddress, this.fcmToken, this.lastVisit,
@@ -24,8 +24,8 @@ class AppState {
factory AppState.init() => AppState(); factory AppState.init() => AppState();
AppState copyWith({ AppState copyWith({
BuildContext context, BuildContext? context,
Locale locale}) { Locale? locale}) {
return AppState( return AppState(
context: context ?? this.context, context: context ?? this.context,
locale: locale ?? this.locale, locale: locale ?? this.locale,

View File

@@ -21,9 +21,9 @@ class DoubleBackToCloseApp extends StatefulWidget {
/// Creates a widget that allows the user to close the app by double tapping /// Creates a widget that allows the user to close the app by double tapping
/// the back-button. /// the back-button.
const DoubleBackToCloseApp({ const DoubleBackToCloseApp({
Key key, Key? key,
@required this.snackBar, required this.snackBar,
@required this.child, required this.child,
}) : assert(snackBar != null), }) : assert(snackBar != null),
assert(child != null), assert(child != null),
super(key: key); super(key: key);
@@ -34,7 +34,7 @@ class DoubleBackToCloseApp extends StatefulWidget {
class _DoubleBackToCloseAppState extends State<DoubleBackToCloseApp> { class _DoubleBackToCloseAppState extends State<DoubleBackToCloseApp> {
/// The last time the user tapped Android's back-button. /// The last time the user tapped Android's back-button.
DateTime _lastTimeBackButtonWasTapped; DateTime? _lastTimeBackButtonWasTapped;
/// Returns whether the current platform is Android. /// Returns whether the current platform is Android.
bool get _isAndroid => Theme.of(context).platform == TargetPlatform.android; bool get _isAndroid => Theme.of(context).platform == TargetPlatform.android;
@@ -50,7 +50,7 @@ class _DoubleBackToCloseAppState extends State<DoubleBackToCloseApp> {
bool get _isSnackBarVisible => bool get _isSnackBarVisible =>
(_lastTimeBackButtonWasTapped != null) && (_lastTimeBackButtonWasTapped != null) &&
(widget.snackBar.duration > (widget.snackBar.duration >
DateTime.now().difference(_lastTimeBackButtonWasTapped)); DateTime.now().difference(_lastTimeBackButtonWasTapped!));
/// Returns whether the next back navigation of this route will be handled /// Returns whether the next back navigation of this route will be handled
/// internally. /// internally.
@@ -59,7 +59,7 @@ class _DoubleBackToCloseAppState extends State<DoubleBackToCloseApp> {
/// local-history of the current route, in order to handle pop. This is done /// local-history of the current route, in order to handle pop. This is done
/// by [Drawer], for example, so it can close on pop. /// by [Drawer], for example, so it can close on pop.
bool get _willHandlePopInternally => bool get _willHandlePopInternally =>
ModalRoute.of(context).willHandlePopInternally; ModalRoute.of(context)!.willHandlePopInternally;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {

View File

@@ -2,9 +2,9 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
class IFrameWeb extends StatefulWidget { class IFrameWeb extends StatefulWidget {
final String width; final String? width;
final String height; final String? height;
final String src; final String? src;
const IFrameWeb({this.width, this.height, this.src}); const IFrameWeb({this.width, this.height, this.src});

View File

@@ -7,14 +7,12 @@ import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import '../store/store.dart'; import '../store/store.dart';
import 'utils.dart'; import 'utils.dart';
import 'package:hive/hive.dart';
import 'package:universal_io/io.dart';
import '../constants.dart'; import '../constants.dart';
typedef void PostCallback(Response response); typedef void PostCallback(Response response);
String generateSignature(String string, {String key}) { String generateSignature(String string, {String? key}) {
if (key == null) { if (key == null) {
key = Constants.API_SECRET; key = Constants.API_SECRET;
} }
@@ -37,17 +35,17 @@ class HttpUtil {
'Http-Contact-Authorization': '', 'Http-Contact-Authorization': '',
'Http-Device-Type': Utils.getOs(checkWeb: true), 'Http-Device-Type': Utils.getOs(checkWeb: true),
'Http-Api-Branch': 'flutter', 'Http-Api-Branch': 'flutter',
'Http-Language-Code': store.state.locale.languageCode, 'Http-Language-Code': (store == null || store.state == null || store.state.locale == null) ? 'en' : store.state.locale!.languageCode,
'Http-Country-Code': store.state.locale.countryCode, 'Http-Country-Code': (store == null || store.state == null || store.state.locale == null) ? 'US' : store.state.locale!.countryCode!,
}; };
static Future<dynamic> httpGet(String url, static Future<dynamic> httpGet(String url,
{ {
Map<String, dynamic> queryParameters, Map<String, dynamic>? queryParameters,
int businessId = 0, int businessId = 0,
Function(int, int) receiveProgress, Function(int, int)? receiveProgress,
bool returnError = false, bool returnError = false,
Map<String, String> additionalHeaders, Map<String, String>? additionalHeaders,
}) async { }) async {
Map<String, dynamic> localHeaders = json.decode(json.encode(headers)); Map<String, dynamic> localHeaders = json.decode(json.encode(headers));
if (additionalHeaders != null) { if (additionalHeaders != null) {
@@ -59,8 +57,7 @@ class HttpUtil {
} }
localHeaders['Http-Business-Id'] = businessId == 0 ? '${Constants.BUSINESS_ID}' : businessId.toString(); localHeaders['Http-Business-Id'] = businessId == 0 ? '${Constants.BUSINESS_ID}' : businessId.toString();
Box box = await Utils.getBox(); localHeaders['Http-Contact-Authorization'] = Utils.prefs?.getString(Constants.KEY_ACCESS_TOKEN) ?? '';
localHeaders['Http-Contact-Authorization'] = box.get(Constants.KEY_ACCESS_TOKEN, defaultValue: '');
localHeaders['Http-App-Key'] = platformName; localHeaders['Http-App-Key'] = platformName;
localHeaders['Http-Device-Type'] = platformName; localHeaders['Http-Device-Type'] = platformName;
String requestUrl = Constants.BASE_API_URL + url; String requestUrl = Constants.BASE_API_URL + url;
@@ -69,7 +66,9 @@ class HttpUtil {
requestUrl = url; requestUrl = url;
} }
Utils.jsonPrettyPrint(queryParameters); if (queryParameters != null) {
Utils.jsonPrettyPrint(queryParameters!);
}
Dio dio = Dio(); Dio dio = Dio();
try { try {
@@ -84,9 +83,9 @@ class HttpUtil {
// print('response data: ${response.data}'); // print('response data: ${response.data}');
// Utils.jsonPrettyPrint(response.data); // Utils.jsonPrettyPrint(response.data);
int statusCode = response.statusCode; int statusCode = response.statusCode!;
return response.data; return response.data;
} on DioError catch(e) { } on DioException catch(e) {
print('HttpGet failed, request: $requestUrl, headers: $localHeaders, error ${e.response}'); print('HttpGet failed, request: $requestUrl, headers: $localHeaders, error ${e.response}');
if (returnError) { if (returnError) {
return e; return e;
@@ -95,16 +94,16 @@ class HttpUtil {
} }
} }
static Future<dynamic> httpPost(String url, PostCallback callback, static Future<dynamic> httpPost(String url, PostCallback? callback,
{ {
Map<String, dynamic> queryParameters, Map<String, dynamic>? queryParameters,
int businessId = 0, int businessId = 0,
bool isFormData = false, bool isFormData = false,
Map<String, String> additionalHeaders, Map<String, String>? additionalHeaders,
Map<String, dynamic> body, Map<String, dynamic>? body,
FormData formData, FormData? formData,
Function(int, int) sendProgress, Function(int, int)? sendProgress,
Function(int, int) receiveProgress, Function(int, int)? receiveProgress,
bool returnError = false, bool returnError = false,
}) async { }) async {
@@ -116,8 +115,7 @@ class HttpUtil {
localHeaders['Http-Signature'] = generateSignature(url); localHeaders['Http-Signature'] = generateSignature(url);
} }
localHeaders['Http-Business-Id'] = businessId == 0 ? '${Constants.BUSINESS_ID}' : businessId.toString(); localHeaders['Http-Business-Id'] = businessId == 0 ? '${Constants.BUSINESS_ID}' : businessId.toString();
Box box = await Utils.getBox(); localHeaders['Http-Contact-Authorization'] = Utils.prefs?.getString(Constants.KEY_ACCESS_TOKEN) ?? '';
localHeaders['Http-Contact-Authorization'] = box.get(Constants.KEY_ACCESS_TOKEN, defaultValue: '');
localHeaders['Http-App-Key'] = platformName; localHeaders['Http-App-Key'] = platformName;
localHeaders['Http-Device-Type'] = platformName; localHeaders['Http-Device-Type'] = platformName;
@@ -138,7 +136,7 @@ class HttpUtil {
Response response = await dio.post( Response response = await dio.post(
requestUrl, requestUrl,
queryParameters: queryParameters == null ? {} : queryParameters, queryParameters: queryParameters == null ? {} : queryParameters,
data: isFormData ? ((formData != null)?formData:FormData.fromMap(body)) : json.encode(body), data: isFormData ? ((formData != null)?formData:FormData.fromMap(body!)) : json.encode(body),
options: Options( options: Options(
headers: localHeaders, headers: localHeaders,
contentType: isFormData ? Headers.formUrlEncodedContentType : Headers.jsonContentType, contentType: isFormData ? Headers.formUrlEncodedContentType : Headers.jsonContentType,
@@ -149,17 +147,17 @@ class HttpUtil {
// Utils.jsonPrettyPrint(response.data); // Utils.jsonPrettyPrint(response.data);
int statusCode = response.statusCode; int statusCode = response.statusCode!;
if (callback != null) { if (callback != null) {
callback(response); callback(response);
} }
return response.data; return response.data;
} on DioError catch(e, stacktrace) { } on DioException catch(e, stacktrace) {
if (e.response != null) { if (e.response != null) {
try { try {
Utils.jsonPrettyPrint(e.response.data); Utils.jsonPrettyPrint(e.response?.data);
} catch (err) { } catch (err) {
print(e.response.data); print(e.response?.data);
} }
} }
if (returnError) { if (returnError) {
@@ -169,14 +167,14 @@ class HttpUtil {
} }
} }
static Future<dynamic> httpPut(String url, PostCallback callback, static Future<dynamic> httpPut(String url, PostCallback? callback,
{ {
Map<String, dynamic> queryParameters, Map<String, dynamic>? queryParameters,
int businessId = 0, int businessId = 0,
Map<String, String> additionalHeaders, Map<String, String>? additionalHeaders,
Map<String, dynamic> body, Map<String, dynamic>? body,
Function(int, int) sendProgress, Function(int, int)? sendProgress,
Function(int, int) receiveProgress, Function(int, int)? receiveProgress,
bool returnError = false, bool returnError = false,
}) async { }) async {
@@ -190,8 +188,7 @@ class HttpUtil {
} }
localHeaders['Http-Business-Id'] = businessId == 0 ? '${Constants.BUSINESS_ID}' : businessId.toString(); localHeaders['Http-Business-Id'] = businessId == 0 ? '${Constants.BUSINESS_ID}' : businessId.toString();
Box box = await Utils.getBox(); localHeaders['Http-Contact-Authorization'] = Utils.prefs?.getString(Constants.KEY_ACCESS_TOKEN) ?? '';
localHeaders['Http-Contact-Authorization'] = box.get(Constants.KEY_ACCESS_TOKEN, defaultValue: '');
localHeaders['Http-App-Key'] = platformName; localHeaders['Http-App-Key'] = platformName;
localHeaders['Http-Device-Type'] = platformName; localHeaders['Http-Device-Type'] = platformName;
@@ -218,14 +215,14 @@ class HttpUtil {
// Utils.jsonPrettyPrint(response.data); // Utils.jsonPrettyPrint(response.data);
int statusCode = response.statusCode; int statusCode = response.statusCode!;
if (callback != null) { if (callback != null) {
callback(response); callback(response);
} }
return response.data; return response.data;
} on DioError catch(e) { } on DioException catch(e) {
if (e.response != null) { if (e.response != null) {
Utils.jsonPrettyPrint(e.response.data); Utils.jsonPrettyPrint(e.response!.data);
} }
if (returnError) { if (returnError) {
return e; return e;
@@ -234,14 +231,14 @@ class HttpUtil {
} }
} }
static Future<dynamic> httpPatch(String url, PostCallback callback, static Future<dynamic> httpPatch(String url, PostCallback? callback,
{ {
Map<String, dynamic> queryParameters, Map<String, dynamic>? queryParameters,
int businessId = 0, int businessId = 0,
Map<String, String> additionalHeaders, Map<String, String>? additionalHeaders,
Map<String, dynamic> body, Map<String, dynamic>? body,
Function(int, int) sendProgress, Function(int, int)? sendProgress,
Function(int, int) receiveProgress, Function(int, int)? receiveProgress,
bool returnError = false, bool returnError = false,
}) async { }) async {
@@ -255,8 +252,7 @@ class HttpUtil {
} }
localHeaders['Http-Business-Id'] = businessId == 0 ? '${Constants.BUSINESS_ID}' : businessId.toString(); localHeaders['Http-Business-Id'] = businessId == 0 ? '${Constants.BUSINESS_ID}' : businessId.toString();
Box box = await Utils.getBox(); localHeaders['Http-Contact-Authorization'] = Utils.prefs?.getString(Constants.KEY_ACCESS_TOKEN) ?? '';
localHeaders['Http-Contact-Authorization'] = box.get(Constants.KEY_ACCESS_TOKEN, defaultValue: '');
localHeaders['Http-App-Key'] = platformName; localHeaders['Http-App-Key'] = platformName;
localHeaders['Http-Device-Type'] = platformName; localHeaders['Http-Device-Type'] = platformName;
@@ -268,7 +264,9 @@ class HttpUtil {
requestUrl = url; requestUrl = url;
} }
Utils.jsonPrettyPrint(body); if (body != null) {
Utils.jsonPrettyPrint(body!);
}
Dio dio = Dio(); Dio dio = Dio();
try { try {
@@ -285,14 +283,14 @@ class HttpUtil {
// Utils.jsonPrettyPrint(response.data); // Utils.jsonPrettyPrint(response.data);
int statusCode = response.statusCode; int statusCode = response.statusCode!;
if (callback != null) { if (callback != null) {
callback(response); callback(response);
} }
return response.data; return response.data;
} on DioError catch(e) { } on DioException catch(e) {
if (e.response != null) { if (e.response != null) {
Utils.jsonPrettyPrint(e.response.data); Utils.jsonPrettyPrint(e.response!.data);
} }
if (returnError) { if (returnError) {
return e; return e;
@@ -301,12 +299,12 @@ class HttpUtil {
} }
} }
static Future<dynamic> httpDelete(String url, PostCallback callback, static Future<dynamic> httpDelete(String url, PostCallback? callback,
{ {
Map<String, dynamic> queryParameters, Map<String, dynamic>? queryParameters,
int businessId = 0, int businessId = 0,
Map<String, String> additionalHeaders, Map<String, String>? additionalHeaders,
Map<String, dynamic> body, Map<String, dynamic>? body,
bool returnError = false, bool returnError = false,
}) async { }) async {
@@ -320,8 +318,7 @@ class HttpUtil {
} }
localHeaders['Http-Business-Id'] = businessId == 0 ? '${Constants.BUSINESS_ID}' : businessId.toString(); localHeaders['Http-Business-Id'] = businessId == 0 ? '${Constants.BUSINESS_ID}' : businessId.toString();
Box box = await Utils.getBox(); localHeaders['Http-Contact-Authorization'] = Utils.prefs?.getString(Constants.KEY_ACCESS_TOKEN) ?? '';
localHeaders['Http-Contact-Authorization'] = box.get(Constants.KEY_ACCESS_TOKEN, defaultValue: '');
localHeaders['Http-App-Key'] = platformName; localHeaders['Http-App-Key'] = platformName;
localHeaders['Http-Device-Type'] = platformName; localHeaders['Http-Device-Type'] = platformName;
@@ -333,7 +330,9 @@ class HttpUtil {
requestUrl = url; requestUrl = url;
} }
Utils.jsonPrettyPrint(body); if (body != null) {
Utils.jsonPrettyPrint(body);
}
Dio dio = Dio(); Dio dio = Dio();
try { try {
@@ -348,14 +347,14 @@ class HttpUtil {
// Utils.jsonPrettyPrint(response.data); // Utils.jsonPrettyPrint(response.data);
int statusCode = response.statusCode; int statusCode = response.statusCode!;
if (callback != null) { if (callback != null) {
callback(response); callback(response);
} }
return response.data; return response.data;
} on DioError catch(e) { } on DioException catch(e) {
if (e.response != null) { if (e.response != null) {
Utils.jsonPrettyPrint(e.response.data); Utils.jsonPrettyPrint(e.response!.data);
} }
if(returnError) { if(returnError) {
return e; return e;

View File

@@ -14,7 +14,7 @@ class ShopScrollController extends ScrollController {
this.coordinator, { this.coordinator, {
double initialScrollOffset = 0.0, double initialScrollOffset = 0.0,
this.keepScrollOffset = true, this.keepScrollOffset = true,
this.debugLabel, required this.debugLabel,
}) : assert(initialScrollOffset != null), }) : assert(initialScrollOffset != null),
assert(keepScrollOffset != null), assert(keepScrollOffset != null),
_initialScrollOffset = initialScrollOffset; _initialScrollOffset = initialScrollOffset;
@@ -61,7 +61,7 @@ class ShopScrollController extends ScrollController {
'ScrollController not attached to any scroll views.'); 'ScrollController not attached to any scroll views.');
assert(_positions.length == 1, assert(_positions.length == 1,
'ScrollController attached to multiple scroll views.'); 'ScrollController attached to multiple scroll views.');
return _positions.single; return _positions.single as ShopScrollPosition;
} }
/// 可滚动小部件的当前滚动偏移量 /// 可滚动小部件的当前滚动偏移量
@@ -83,12 +83,12 @@ class ShopScrollController extends ScrollController {
/// 持续时间不能为零。 要在没有动画的情况下跳至特定值,请使用[jumpTo]。 /// 持续时间不能为零。 要在没有动画的情况下跳至特定值,请使用[jumpTo]。
Future<void> animateTo( Future<void> animateTo(
double offset, { double offset, {
@required Duration duration, required Duration duration,
@required Curve curve, required Curve curve,
}) { }) {
assert(_positions.isNotEmpty, assert(_positions.isNotEmpty,
'ScrollController not attached to any scroll views.'); 'ScrollController not attached to any scroll views.');
final List<Future<void>> animations = List<Future<void>>(_positions.length); final List<Future<void>> animations = List<Future<void>>.filled(_positions.length, Future<void>.value());
for (int i = 0; i < _positions.length; i += 1) for (int i = 0; i < _positions.length; i += 1)
animations[i] = animations[i] =
_positions[i].animateTo(offset, duration: duration, curve: curve); _positions[i].animateTo(offset, duration: duration, curve: curve);
@@ -149,7 +149,7 @@ class ShopScrollController extends ScrollController {
/// 则它将是前一个实例。 当环境已更改并且[Scrollable]需要重新创建[ScrollPosition] /// 则它将是前一个实例。 当环境已更改并且[Scrollable]需要重新创建[ScrollPosition]
/// 对象时,将使用此方法。 第一次创建[ScrollPosition]时为null。 /// 对象时,将使用此方法。 第一次创建[ScrollPosition]时为null。
ScrollPosition createScrollPosition(ScrollPhysics physics, ScrollPosition createScrollPosition(ScrollPhysics physics,
ScrollContext context, ScrollPosition oldPosition) { ScrollContext context, ScrollPosition? oldPosition) {
return ShopScrollPosition( return ShopScrollPosition(
coordinator: coordinator, coordinator: coordinator,
physics: physics, physics: physics,

View File

@@ -12,15 +12,15 @@ class ShopScrollCoordinator {
/// 页面主 CustomScrollView 控制 /// 页面主 CustomScrollView 控制
final String pageLabel = "page"; final String pageLabel = "page";
ShopScrollController _pageScrollController; ShopScrollController? _pageScrollController;
double Function() pinnedHeaderSliverHeightBuilder; double Function()? pinnedHeaderSliverHeightBuilder;
ShopScrollPosition get _pageScrollPosition => _pageScrollController.position; ShopScrollPosition get _pageScrollPosition => _pageScrollController!.position;
ScrollDragController scrollDragController; ScrollDragController? scrollDragController;
/// 主页面滑动部件默认位置 /// 主页面滑动部件默认位置
double _pageInitialOffset; double? _pageInitialOffset;
/// 获取主页面滑动控制器 /// 获取主页面滑动控制器
ShopScrollController pageScrollController([double initialOffset = 0.0]) { ShopScrollController pageScrollController([double initialOffset = 0.0]) {
@@ -28,27 +28,27 @@ class ShopScrollCoordinator {
_pageInitialOffset = initialOffset; _pageInitialOffset = initialOffset;
_pageScrollController = ShopScrollController(this, _pageScrollController = ShopScrollController(this,
debugLabel: pageLabel, initialScrollOffset: initialOffset); debugLabel: pageLabel, initialScrollOffset: initialOffset);
return _pageScrollController; return _pageScrollController!;
} }
/// 创建并获取一个子滑动控制器 /// 创建并获取一个子滑动控制器
ShopScrollController newChildScrollController([String debugLabel]) => ShopScrollController newChildScrollController([String? debugLabel]) =>
ShopScrollController(this, debugLabel: debugLabel); ShopScrollController(this, debugLabel: debugLabel ?? '');
/// 子部件滑动数据协调 /// 子部件滑动数据协调
/// [userScrollDirection]用户滑动方向 /// [userScrollDirection]用户滑动方向
/// [position]被滑动的子部件的位置信息 /// [position]被滑动的子部件的位置信息
void applyUserOffset(double delta, void applyUserOffset(double delta,
[ScrollDirection userScrollDirection, ShopScrollPosition position]) { [ScrollDirection? userScrollDirection, ShopScrollPosition? position]) {
if (userScrollDirection == ScrollDirection.reverse) { if (userScrollDirection == ScrollDirection.reverse) {
updateUserScrollDirection(_pageScrollPosition, userScrollDirection); updateUserScrollDirection(_pageScrollPosition, userScrollDirection!);
final innerDelta = _pageScrollPosition.applyClampedDragUpdate(delta); final innerDelta = _pageScrollPosition.applyClampedDragUpdate(delta);
if (innerDelta != 0.0) { if (innerDelta != 0.0) {
updateUserScrollDirection(position, userScrollDirection); updateUserScrollDirection(position!, userScrollDirection);
position.applyFullDragUpdate(innerDelta); position.applyFullDragUpdate(innerDelta);
} }
} else { } else {
updateUserScrollDirection(position, userScrollDirection); updateUserScrollDirection(position!, userScrollDirection!);
final outerDelta = position.applyClampedDragUpdate(delta); final outerDelta = position.applyClampedDragUpdate(delta);
if (outerDelta != 0.0) { if (outerDelta != 0.0) {
updateUserScrollDirection(_pageScrollPosition, userScrollDirection); updateUserScrollDirection(_pageScrollPosition, userScrollDirection);
@@ -60,7 +60,7 @@ class ShopScrollCoordinator {
bool applyContentDimensions(double minScrollExtent, double maxScrollExtent, bool applyContentDimensions(double minScrollExtent, double maxScrollExtent,
ShopScrollPosition position) { ShopScrollPosition position) {
if (pinnedHeaderSliverHeightBuilder != null) { if (pinnedHeaderSliverHeightBuilder != null) {
maxScrollExtent = maxScrollExtent - pinnedHeaderSliverHeightBuilder(); maxScrollExtent = maxScrollExtent - pinnedHeaderSliverHeightBuilder!();
maxScrollExtent = math.max(0.0, maxScrollExtent); maxScrollExtent = math.max(0.0, maxScrollExtent);
} }
return position.applyContentDimensions( return position.applyContentDimensions(
@@ -77,9 +77,9 @@ class ShopScrollCoordinator {
/// 当手指离开屏幕 /// 当手指离开屏幕
void onPointerUp(PointerUpEvent event) { void onPointerUp(PointerUpEvent event) {
final double _pagePixels = _pageScrollPosition.pixels; final double _pagePixels = _pageScrollPosition.pixels;
if (0.0 < _pagePixels && _pagePixels < _pageInitialOffset) { if (0.0 < _pagePixels && _pagePixels < _pageInitialOffset!) {
if (pageExpand == PageExpandState.NotExpand && if (pageExpand == PageExpandState.NotExpand &&
_pageInitialOffset - _pagePixels > _scrollRedundancy) { _pageInitialOffset! - _pagePixels > _scrollRedundancy) {
_pageScrollPosition _pageScrollPosition
.animateTo(0.0, .animateTo(0.0,
duration: const Duration(milliseconds: 400), curve: Curves.ease) duration: const Duration(milliseconds: 400), curve: Curves.ease)
@@ -87,7 +87,7 @@ class ShopScrollCoordinator {
} else { } else {
pageExpand = PageExpandState.Expanding; pageExpand = PageExpandState.Expanding;
_pageScrollPosition _pageScrollPosition
.animateTo(_pageInitialOffset, .animateTo(_pageInitialOffset!,
duration: const Duration(milliseconds: 400), curve: Curves.ease) duration: const Duration(milliseconds: 400), curve: Curves.ease)
.then((value) => pageExpand = PageExpandState.NotExpand); .then((value) => pageExpand = PageExpandState.NotExpand);
} }

View File

@@ -11,17 +11,17 @@ import 'shop_scroll_coordinator.dart';
class ShopScrollPosition extends ScrollPosition class ShopScrollPosition extends ScrollPosition
implements ScrollActivityDelegate { implements ScrollActivityDelegate {
final ShopScrollCoordinator coordinator; // 协调器 final ShopScrollCoordinator coordinator; // 协调器
ScrollDragController _currentDrag; ScrollDragController? _currentDrag;
double _heldPreviousVelocity = 0.0; double _heldPreviousVelocity = 0.0;
ShopScrollPosition( ShopScrollPosition(
{@required ScrollPhysics physics, {required ScrollPhysics physics,
@required ScrollContext context, required ScrollContext context,
double initialPixels = 0.0, double initialPixels = 0.0,
bool keepScrollOffset = true, bool keepScrollOffset = true,
ScrollPosition oldPosition, ScrollPosition? oldPosition,
String debugLabel, String? debugLabel,
@required this.coordinator}) required this.coordinator})
: super( : super(
physics: physics, physics: physics,
context: context, context: context,
@@ -40,7 +40,7 @@ class ShopScrollPosition extends ScrollPosition
@override @override
double setPixels(double newPixels) { double setPixels(double newPixels) {
assert(activity.isScrolling); assert(activity!.isScrolling);
return super.setPixels(newPixels); return super.setPixels(newPixels);
} }
@@ -51,13 +51,13 @@ class ShopScrollPosition extends ScrollPosition
goIdle(); goIdle();
return; return;
} }
activity.updateDelegate(this); activity!.updateDelegate(this);
final ShopScrollPosition typedOther = other as ShopScrollPosition; final ShopScrollPosition typedOther = other as ShopScrollPosition;
_userScrollDirection = typedOther._userScrollDirection; _userScrollDirection = typedOther._userScrollDirection;
assert(_currentDrag == null); assert(_currentDrag == null);
if (typedOther._currentDrag != null) { if (typedOther._currentDrag != null) {
_currentDrag = typedOther._currentDrag; _currentDrag = typedOther._currentDrag;
_currentDrag.updateDelegate(this); _currentDrag?.updateDelegate(this);
typedOther._currentDrag = null; typedOther._currentDrag = null;
} }
} }
@@ -131,14 +131,14 @@ class ShopScrollPosition extends ScrollPosition
} }
@override @override
void beginActivity(ScrollActivity newActivity) { void beginActivity(ScrollActivity? newActivity) {
_heldPreviousVelocity = 0.0; _heldPreviousVelocity = 0.0;
if (newActivity == null) return; if (newActivity == null) return;
assert(newActivity.delegate == this); assert(newActivity.delegate == this);
super.beginActivity(newActivity); super.beginActivity(newActivity);
_currentDrag?.dispose(); _currentDrag?.dispose();
_currentDrag = null; _currentDrag = null;
if (!activity.isScrolling) updateUserScrollDirection(ScrollDirection.idle); if (!activity!.isScrolling) updateUserScrollDirection(ScrollDirection.idle);
} }
/// 将[用户滚动方向]设置为给定值。 /// 将[用户滚动方向]设置为给定值。
@@ -154,7 +154,7 @@ class ShopScrollPosition extends ScrollPosition
@override @override
ScrollHoldController hold(VoidCallback holdCancelCallback) { ScrollHoldController hold(VoidCallback holdCancelCallback) {
final double previousVelocity = activity.velocity; final double previousVelocity = activity!.velocity;
final HoldScrollActivity holdActivity = final HoldScrollActivity holdActivity =
HoldScrollActivity(delegate: this, onHoldCanceled: holdCancelCallback); HoldScrollActivity(delegate: this, onHoldCanceled: holdCancelCallback);
beginActivity(holdActivity); beginActivity(holdActivity);
@@ -195,10 +195,10 @@ class ShopScrollPosition extends ScrollPosition
if (coordinator.pageExpand == PageExpandState.Expanding) return; if (coordinator.pageExpand == PageExpandState.Expanding) return;
} }
assert(pixels != null); assert(pixels != null);
final Simulation simulation = final Simulation? simulation =
physics.createBallisticSimulation(this, velocity); physics.createBallisticSimulation(this, velocity);
if (simulation != null) { if (simulation != null) {
beginActivity(BallisticScrollActivity(this, simulation, context.vsync)); beginActivity(BallisticScrollActivity(this, simulation, context.vsync, true));
} else { } else {
goIdle(); goIdle();
} }
@@ -220,8 +220,8 @@ class ShopScrollPosition extends ScrollPosition
@override @override
Future<void> animateTo( Future<void> animateTo(
double to, { double to, {
@required Duration duration, required Duration duration,
@required Curve curve, required Curve curve,
}) { }) {
if (nearEqual(to, pixels, physics.tolerance.distance)) { if (nearEqual(to, pixels, physics.tolerance.distance)) {
// 跳过动画,直接移到我们已经靠近的位置。 // 跳过动画,直接移到我们已经靠近的位置。

View File

@@ -6,15 +6,11 @@ import 'dart:ui' as ui;
import 'package:cached_network_image/cached_network_image.dart'; import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
// import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:hive/hive.dart';
import 'package:image_picker/image_picker.dart'; import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart'; import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:stripe_payment/stripe_payment.dart'; import 'package:stripe_payment/stripe_payment.dart';
import '../constants.dart'; import '../constants.dart';
@@ -42,174 +38,17 @@ class Util {
} }
Util._internal(); Util._internal();
// final FirebaseMessaging firebaseMessaging = FirebaseMessaging();
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
static bool notificationTapped = false; static bool notificationTapped = false;
init() { static Widget showImage(String imageUrl, {double? width, double? height,
// initLocalNotification(); BoxFit? fit, Widget Function(BuildContext, String, dynamic)? errorWidget}) {
// initFirebaseMessaging(); if (imageUrl.isNotEmpty && imageUrl.startsWith('https:')) {
// ePmqRwRUTmKuFNfbHA-6zq:APA91bEFEQx1YgJqfx0V0VYo86uRDGjG6SP1SPCAZW4OvQ7gMOeKWDQ47bfuEM00YavtKq7ZGpsWfFL7B3ypm00ZA6crjJJLK_-j_H8bS_dnQbLFwyRcW67IXCs5sRkro71bRZv7L1WM
// eventBus.on<SubscribeToTopic>().listen((event) {
// if (firebaseMessaging != null) {
// firebaseMessaging.subscribeToTopic(event.topic);
// }
// });
// eventBus.on<UnSubscribeToTopic>().listen((event) {
// if (firebaseMessaging != null) {
// firebaseMessaging.unsubscribeFromTopic(event.topic);
// }
// });
}
initLocalNotification() async {
var initializationSettingsAndroid = new AndroidInitializationSettings('ic_launcher');
var initializationSettingsIOS = new IOSInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification);
var initializationSettings = new InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
}
Future onSelectNotification(String payload, {bool replace=false}) async {
print('payload: $payload');
if (payload != null && payload.isNotEmpty) {
Routes.router.navigateTo(store.state.context, payload, replace: replace);
}
}
// initFirebaseMessaging() {
// if (Platform.isIOS) {
// iosPermission();
// }
// firebaseMessaging.getToken().then((token) {
// print('FCM token: $token');
// store.dispatch(UpdateFcmToken(token));
// });
// firebaseMessaging.configure(
// onMessage: (Map<String, dynamic> message) {
// print('FCM onMessage: $message');
// // eventBus.fire(OnFcmReceived(message));
// showNotificationWithDefaultSound(message);
// return;
// },
// onBackgroundMessage: Platform.isIOS ? null : backgroundMessageHandler,
// onResume: (Map<String, dynamic> message) {
// print('FCM onResume: $message');
// if (Platform.isAndroid) {
// if (message != null && message['data'] != null && message['data']['route'] != null) {
// notificationTapped = true;
// onSelectNotification(message['data']['route']);
// }
// } else {
// if (message != null && message['route'] != null) {
// notificationTapped = true;
// onSelectNotification(message['route']);
// }
// }
// return;
// },
// onLaunch: (Map<String, dynamic> message) {
// print('FCM onLaunch: $message');
// if (Platform.isAndroid) {
// if (message != null && message['data'] != null && message['data']['route'] != null) {
// notificationTapped = true;
// onSelectNotification(message['data']['route'], replace: true);
// }
// } else {
// if (message != null && message['route'] != null) {
// notificationTapped = true;
// onSelectNotification(message['route'], replace: true);
// }
// }
// return;
// },
// );
// }
Future onDidReceiveLocalNotification(int id, String title, String body, String payload) async {
showDialog(
context: store.state.context,
builder: (BuildContext context) => CupertinoAlertDialog(
title: Text(title),
content: Text(body),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: Text(S.of(context).ok),
onPressed: () async {
Navigator.of(context, rootNavigator: true).pop();
if (payload != null && payload.isNotEmpty) {
Routes.router.navigateTo(context, payload);
}
},
)
],
),
);
}
Future showNotificationWithDefaultSound(Map<String, dynamic> message) async {
var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
'channelId',
'channelName',
'channelDescription',
importance: Importance.max,
priority: Priority.high,
);
var iOSPlatformChannelSpecifics = new IOSNotificationDetails(presentSound: true, badgeNumber: 1);
var platformChannelSpecifics = new NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iOSPlatformChannelSpecifics,
);
await flutterLocalNotificationsPlugin.show(
0,
Platform.isAndroid ? message['notification']['title'] : message['title'],
Platform.isAndroid ? message['notification']['body'] : message['body'],
platformChannelSpecifics,
payload: Platform.isAndroid ? message['data']['route'] : message['route'],
);
}
// iosPermission() {
// firebaseMessaging.requestNotificationPermissions(
// const IosNotificationSettings(
// sound: true,
// badge: true,
// alert: true,
// )
// );
// firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings settings) {
// print('IOS settings registered: $settings');
// });
// }
static Future<dynamic> backgroundMessageHandler(Map<String, dynamic> message) {
print('FCM background message handler: $message');
return Future<void>.value();
}
static Future<Box> getBox() async {
final dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
Box box = await Hive.openBox('app_data');
return box;
}
static Widget showImage(String imageUrl, {double width, double height,
BoxFit fit, Widget Function(BuildContext, String, dynamic) errorWidget}) {
if (imageUrl != null && imageUrl.isNotEmpty && imageUrl.startsWith('https:')) {
return CachedNetworkImage( return CachedNetworkImage(
imageUrl: imageUrl, imageUrl: imageUrl,
width: width, width: width,
height: width, height: width,
fit: fit, fit: fit,
placeholder: (context, url) => Utils.imageLoadingIndicator(width: width, height: height), placeholder: (context, url) => Utils.imageLoadingIndicator(width: width ?? 30, height: height ?? 30),
errorWidget: errorWidget != null ? errorWidget : (context, url, error) { errorWidget: errorWidget != null ? errorWidget : (context, url, error) {
return Image.asset( return Image.asset(
'assets/images/not_found.png', 'assets/images/not_found.png',
@@ -219,13 +58,13 @@ class Util {
); );
}, },
); );
} else if (imageUrl != null && imageUrl.isNotEmpty) { } else if (imageUrl.isNotEmpty) {
return Image.file( return Image.file(
File(imageUrl), File(imageUrl),
width: width, width: width,
height: height, height: height,
fit: fit, fit: fit,
errorBuilder: (BuildContext context, Object object, StackTrace stackTrace) { errorBuilder: (BuildContext context, Object object, StackTrace? stackTrace) {
return Image.asset( return Image.asset(
'assets/images/not_found.png', 'assets/images/not_found.png',
width: width, width: width,
@@ -319,14 +158,14 @@ class Util {
final picker = ImagePicker(); final picker = ImagePicker();
var image = await picker.pickImage(source: ImageSource.gallery); var image = await picker.pickImage(source: ImageSource.gallery);
Navigator.of(context).pop(); Navigator.of(context).pop();
uploadPicture(context, File(image.path), user, commentId: commentId, orderId: orderId); uploadPicture(context, File(image!.path), user, commentId: commentId, orderId: orderId);
} }
void getPictureFromCamera(BuildContext context, User user, {int commentId = -1, int orderId = 0}) async { void getPictureFromCamera(BuildContext context, User user, {int commentId = -1, int orderId = 0}) async {
final picker = ImagePicker(); final picker = ImagePicker();
var image = await picker.pickImage(source: ImageSource.camera); var image = await picker.pickImage(source: ImageSource.camera);
Navigator.of(context).pop(); Navigator.of(context).pop();
uploadPicture(context, File(image.path), user, commentId: commentId, orderId: orderId); uploadPicture(context, File(image!.path), user, commentId: commentId, orderId: orderId);
} }
void uploadPicture(BuildContext context, File image, User user, {int commentId = -1, int orderId = 0}) async { void uploadPicture(BuildContext context, File image, User user, {int commentId = -1, int orderId = 0}) async {
@@ -456,18 +295,18 @@ class Util {
ImagePicker picker = ImagePicker(); ImagePicker picker = ImagePicker();
var image = await picker.pickImage(source: ImageSource.gallery); var image = await picker.pickImage(source: ImageSource.gallery);
Navigator.of(context).pop(); Navigator.of(context).pop();
onGotFile(imageId, image.path); onGotFile(imageId, image!.path);
} }
void getPictureFromCamera2(BuildContext context, int imageId, OnGotFile onGotFile) async { void getPictureFromCamera2(BuildContext context, int imageId, OnGotFile onGotFile) async {
ImagePicker picker = ImagePicker(); ImagePicker picker = ImagePicker();
var image = await picker.pickImage(source: ImageSource.camera); var image = await picker.pickImage(source: ImageSource.camera);
Navigator.of(context).pop(); Navigator.of(context).pop();
onGotFile(imageId, image.path); onGotFile(imageId, image!.path);
} }
Future<void> createTicket(BuildContext context, String msg, List<Map<String, dynamic>> images, Future<void> createTicket(BuildContext context, String msg, List<Map<String, dynamic>> images,
OnSuccess onSuccess, OnError onError, {int id}) { OnSuccess onSuccess, OnError onError, {int? id}) async {
var formData = FormData(); var formData = FormData();
formData.fields.add(MapEntry("msg", msg)); formData.fields.add(MapEntry("msg", msg));
formData.fields.add(MapEntry('id', id == null ? '0' : id.toString())); formData.fields.add(MapEntry('id', id == null ? '0' : id.toString()));
@@ -562,7 +401,7 @@ class Util {
PaymentPlatform paymentPlatform, { PaymentPlatform paymentPlatform, {
bool googlePay=false, bool googlePay=false,
bool applePay=false, bool applePay=false,
StripePaymentMethod stripePaymentMethod, StripePaymentMethod? stripePaymentMethod,
}) { }) {
switch(paymentPlatform.code) { switch(paymentPlatform.code) {
case Constants.PAYMENT_METHOD_CODE_SQUARE: case Constants.PAYMENT_METHOD_CODE_SQUARE:
@@ -587,7 +426,7 @@ class Util {
StripePayment.setOptions( StripePayment.setOptions(
StripeOptions(publishableKey: paymentPlatform.publishableKey, StripeOptions(publishableKey: paymentPlatform.publishableKey,
merchantId: paymentPlatform.merchantId, merchantId: paymentPlatform.merchantId,
androidPayMode: paymentPlatform.publishableKey.contains('_test_') androidPayMode: paymentPlatform.publishableKey!.contains('_test_')
? 'test' ? 'test'
: 'production' : 'production'
) )
@@ -595,14 +434,14 @@ class Util {
StripePayment.paymentRequestWithNativePay( StripePayment.paymentRequestWithNativePay(
androidPayOptions: AndroidPayPaymentRequest( androidPayOptions: AndroidPayPaymentRequest(
totalPrice: order.totalPrice.toStringAsFixed(2), totalPrice: order.totalPrice.toStringAsFixed(2),
currencyCode: order.businessInfo.currency, currencyCode: order.businessInfo!.currency,
), ),
applePayOptions: ApplePayPaymentOptions( applePayOptions: ApplePayPaymentOptions(
currencyCode: order.businessInfo.currency, currencyCode: order.businessInfo!.currency,
countryCode: order.businessInfo.address.country, countryCode: order.businessInfo!.address.country,
items: [ items: [
ApplePayItem( ApplePayItem(
label: order.businessInfo.name, label: order.businessInfo!.name,
amount: order.totalPrice.toStringAsFixed(2), amount: order.totalPrice.toStringAsFixed(2),
), ),
], ],
@@ -633,7 +472,7 @@ class Util {
), ),
); );
if (paymentMethod != null) { if (paymentMethod != null) {
Utils.stripePaymentIntent(order, null, paymentMethod.id, paymentMethod.type, (response) { Utils.stripePaymentIntent(order, null, paymentMethod.id!, paymentMethod.type!, (response) {
if (response.data['status'] == Constants.STRIPE_STATUS_REQUIRES_CONFIRMATION) { if (response.data['status'] == Constants.STRIPE_STATUS_REQUIRES_CONFIRMATION) {
StripePayment.confirmPaymentIntent( StripePayment.confirmPaymentIntent(
PaymentIntent( PaymentIntent(
@@ -643,8 +482,8 @@ class Util {
).then((paymentIntentResult) { ).then((paymentIntentResult) {
if (paymentIntentResult.status == Constants.STRIPE_STATUS_SUCCEDED) { if (paymentIntentResult.status == Constants.STRIPE_STATUS_SUCCEDED) {
Utils.stripeChargedSuccess(order, Utils.stripeChargedSuccess(order,
paymentMethod.id, paymentMethod.id!,
paymentIntentResult.paymentIntentId, paymentIntentResult.paymentIntentId!,
(response) { (response) {
StripePayment.completeNativePayRequest().then((_) { StripePayment.completeNativePayRequest().then((_) {
eventBus.fire(OnOrderUpdated()); eventBus.fire(OnOrderUpdated());
@@ -680,10 +519,10 @@ class Util {
} }
} }
static Future<Uint8List> getBytesFromAsset(String path, int width) async { static Future<Uint8List?> getBytesFromAsset(String path, int width) async {
ByteData data = await rootBundle.load(path); ByteData data = await rootBundle.load(path);
ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(), targetWidth: width); ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(), targetWidth: width);
ui.FrameInfo fi = await codec.getNextFrame(); ui.FrameInfo fi = await codec.getNextFrame();
return (await fi.image.toByteData(format: ui.ImageByteFormat.png)).buffer.asUint8List(); return (await fi.image.toByteData(format: ui.ImageByteFormat.png))?.buffer.asUint8List();
} }
} }

View File

@@ -5,8 +5,6 @@ import 'dart:typed_data';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart'; import 'package:fluttertoast/fluttertoast.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
import '../constants.dart'; import '../constants.dart';
@@ -36,27 +34,21 @@ class Util {
} }
static Future<Box> getBox() async { static Widget showImage(String imageUrl, {double? width, double? height,
Hive.initFlutter(); BoxFit? fit, Widget Function(BuildContext, String?, dynamic)? errorWidget}) {
Box box = await Hive.openBox('wisetronic_app_data');
return box;
}
static Widget showImage(String imageUrl, {double width, double height,
BoxFit fit, Widget Function(BuildContext, String, dynamic) errorWidget}) {
return Image.network(imageUrl, return Image.network(imageUrl,
fit: fit, fit: fit,
width: width, width: width,
height: height, height: height,
cacheWidth: width != null ? width.round() : null, cacheWidth: width != null ? width.round() : null,
cacheHeight: height != null ? height.round() : null, cacheHeight: height != null ? height.round() : null,
loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent loadingProgress) { loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) return child; if (loadingProgress == null) return child;
return Center( return Center(
child: Utils.imageLoadingIndicator(), child: Utils.imageLoadingIndicator(),
); );
}, },
errorBuilder: (BuildContext context, Object object, StackTrace stackTrace) { errorBuilder: (BuildContext context, Object object, StackTrace? stackTrace) {
print('StackTrace: $stackTrace'); print('StackTrace: $stackTrace');
if (errorWidget != null) { if (errorWidget != null) {
return errorWidget(context, null, null); return errorWidget(context, null, null);
@@ -106,16 +98,16 @@ class Util {
} }
void startFilePicker(BuildContext context, User user, {int commentId = -1, int orderId = 0}) async { void startFilePicker(BuildContext context, User user, {int commentId = -1, int orderId = 0}) async {
InputElement uploadInput = FileUploadInputElement(); InputElement uploadInput = FileUploadInputElement() as InputElement;
uploadInput.click(); uploadInput.click();
uploadInput.onChange.listen((e) { uploadInput.onChange.listen((e) {
final files = uploadInput.files; final files = uploadInput.files;
if (files.length >= 1) { if (files!.length >= 1) {
final File file = files[0]; final File file = files[0];
final FileReader reader = new FileReader(); final FileReader reader = new FileReader();
reader.onLoadEnd.listen((e) { reader.onLoadEnd.listen((e) {
uploadPicture(context, reader.result, file.name, user, commentId: commentId, orderId: orderId); uploadPicture(context, reader.result as Uint8List, file.name, user, commentId: commentId, orderId: orderId);
}); });
reader.onError.listen((e) { reader.onError.listen((e) {
Fluttertoast.showToast( Fluttertoast.showToast(
@@ -210,11 +202,11 @@ class Util {
void startFilePicker2(BuildContext context, int imageId, OnGotFile onGotFile) async { void startFilePicker2(BuildContext context, int imageId, OnGotFile onGotFile) async {
final _image = await WebImagePicker().pickImage(); final _image = await WebImagePicker().pickImage();
onGotFile(imageId, _image.dataScheme); onGotFile(imageId, _image!.dataScheme);
} }
void createTicket(BuildContext context, String msg, List<Map<String, dynamic>> images, void createTicket(BuildContext context, String msg, List<Map<String, dynamic>> images,
OnSuccess onSuccess, OnError onError, {int id}) { OnSuccess onSuccess, OnError onError, {int? id}) {
var formData = FormData(); var formData = FormData();
formData.fields.add(MapEntry("msg", msg)); formData.fields.add(MapEntry("msg", msg));
formData.fields.add(MapEntry('id', id == null ? '0' : id.toString())); formData.fields.add(MapEntry('id', id == null ? '0' : id.toString()));
@@ -252,7 +244,7 @@ class Util {
PaymentPlatform paymentPlatform, { PaymentPlatform paymentPlatform, {
bool googlePay=false, bool googlePay=false,
bool applePay=false, bool applePay=false,
StripePaymentMethod stripePaymentMethod, StripePaymentMethod? stripePaymentMethod,
}) { }) {
switch(paymentPlatform.code) { switch(paymentPlatform.code) {
case Constants.PAYMENT_METHOD_CODE_SQUARE: case Constants.PAYMENT_METHOD_CODE_SQUARE:
@@ -293,36 +285,36 @@ class Util {
} }
class ImageInfo { class ImageInfo {
String name; String name = '';
String data; String data = '';
String dataScheme; String dataScheme = '';
String path; String path = '';
} }
class WebImagePicker { class WebImagePicker {
Future<ImageInfo> pickImage() async { Future<ImageInfo?> pickImage() async {
print('pickImage'); print('pickImage');
final ImageInfo data = ImageInfo(); final ImageInfo data = ImageInfo();
final FileUploadInputElement input = FileUploadInputElement(); final FileUploadInputElement input = FileUploadInputElement();
document.body.children.add(input); document.body!.children.add(input);
input..accept = 'image/*'; input..accept = 'image/*';
input.click(); input.click();
await input.onChange.first; await input.onChange.first;
if (input.files.isEmpty) return null; if (input.files!.isEmpty) return null;
final reader = FileReader(); final reader = FileReader();
reader.readAsDataUrl(input.files[0]); reader.readAsDataUrl(input.files![0]);
await reader.onLoad.first; await reader.onLoad.first;
final encoded = reader.result as String; final encoded = reader.result as String;
// remove data:image/*;base64 preambule // remove data:image/*;base64 preambule
final stripped = final stripped =
encoded.replaceFirst(RegExp(r'data:image/[^;]+;base64,'), ''); encoded.replaceFirst(RegExp(r'data:image/[^;]+;base64,'), '');
//final imageBase64 = base64.decode(stripped); //final imageBase64 = base64.decode(stripped);
final imageName = input.files?.first?.name; final imageName = input.files?.first.name;
final imagePath = input.files?.first?.relativePath; final imagePath = input.files?.first.relativePath;
data.name = imageName; data.name = imageName!;
data.data = stripped; data.data = stripped;
data.dataScheme = encoded; data.dataScheme = encoded;
data.path = imagePath; data.path = imagePath!;
return data; return data;
} }
} }

View File

@@ -8,7 +8,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_wisetronic/models/product.dart'; import 'package:flutter_wisetronic/models/product.dart';
import 'package:fluttertoast/fluttertoast.dart'; import 'package:fluttertoast/fluttertoast.dart';
import 'package:hive/hive.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:universal_io/io.dart'; import 'package:universal_io/io.dart';
@@ -28,6 +27,7 @@ import '../store/actions.dart';
import '../store/store.dart'; import '../store/store.dart';
import 'http_util.dart'; import 'http_util.dart';
import 'util_web.dart' if (dart.library.io) 'util_io.dart'; import 'util_web.dart' if (dart.library.io) 'util_io.dart';
import 'package:shared_preferences/shared_preferences.dart';
typedef void OnSuccess(Response response); typedef void OnSuccess(Response response);
typedef void OnError(dynamic error); typedef void OnError(dynamic error);
@@ -37,16 +37,25 @@ typedef void OnOk();
typedef void OnLoadImageError(); typedef void OnLoadImageError();
class Utils { class Utils {
static StreamSubscription onProductWillAddToCartSubscription; static final Utils _utils = Utils._internal();
static StreamSubscription onProductWillRemoveFromCartSubscription; static SharedPreferences? prefs;
static StreamSubscription? onProductWillAddToCartSubscription;
static StreamSubscription? onProductWillRemoveFromCartSubscription;
factory Utils() {
return _utils;
}
Utils._internal();
init() async { init() async {
prefs = await SharedPreferences.getInstance();
onProductWillAddToCartSubscription = onProductWillAddToCartSubscription =
eventBus.on<OnProductWillAddToCart>().listen((event) { eventBus.on<OnProductWillAddToCart>().listen((event) {
CartInfo cartInfo = CartInfo? cartInfo =
getCartInfoByBusiness(store.state.cartInfos, event.business); getCartInfoByBusiness(store.state.cartInfos, event.business);
if (cartInfo == null || cartInfo.productList.length == 0) { if (cartInfo == null || cartInfo.productList!.length == 0) {
cartInfo = CartInfo(); cartInfo = CartInfo();
cartInfo.id = 0; cartInfo.id = 0;
cartInfo.amountPaid = 0.0; cartInfo.amountPaid = 0.0;
@@ -57,7 +66,7 @@ class Utils {
id: 0, id: 0,
price: event.price, price: event.price,
product: event.product, product: event.product,
name: event.product.name, name: event.product.name!,
description: event.description, description: event.description,
quantity: 1.0); quantity: 1.0);
cartInfo.productList = [lineItem]; cartInfo.productList = [lineItem];
@@ -67,15 +76,15 @@ class Utils {
eventBus.fire(new OnCartInfoUpdated()); eventBus.fire(new OnCartInfoUpdated());
print('#1'); print('#1');
} else { } else {
if (event.product.productAttributes.length > 0) { if (event.product.productAttributes!.length > 0) {
CartLineItem lineItem = newCartLineItem( CartLineItem lineItem = newCartLineItem(
id: 0, id: 0,
price: event.price, price: event.price,
product: event.product, product: event.product,
name: event.product.name, name: event.product.name!,
description: event.description, description: event.description,
quantity: 1.0); quantity: 1.0);
cartInfo.productList.add(lineItem); cartInfo.productList!.add(lineItem);
addSubproductToCard(cartInfo, lineItem); addSubproductToCard(cartInfo, lineItem);
store.dispatch(new UpdateCartInfo(addCartInfoToCartInfoList( store.dispatch(new UpdateCartInfo(addCartInfoToCartInfoList(
store.state.cartInfos, cartInfo))); store.state.cartInfos, cartInfo)));
@@ -83,8 +92,8 @@ class Utils {
eventBus.fire(new OnCartInfoUpdated()); eventBus.fire(new OnCartInfoUpdated());
} else { } else {
int found = -1; int found = -1;
for (var i = 0; i < cartInfo.productList.length; i++) { for (var i = 0; i < cartInfo.productList!.length; i++) {
if (event.product.id == cartInfo.productList[i].product.id) { if (event.product.id == cartInfo.productList![i].product!.id) {
found = i; found = i;
break; break;
} }
@@ -94,18 +103,18 @@ class Utils {
id: 0, id: 0,
price: event.price, price: event.price,
product: event.product, product: event.product,
name: event.product.name, name: event.product.name!,
description: event.description, description: event.description,
quantity: 1.0); quantity: 1.0);
cartInfo.productList.add(lineItem); cartInfo.productList!.add(lineItem);
addSubproductToCard(cartInfo, lineItem); addSubproductToCard(cartInfo, lineItem);
store.dispatch(new UpdateCartInfo(addCartInfoToCartInfoList( store.dispatch(new UpdateCartInfo(addCartInfoToCartInfoList(
store.state.cartInfos, cartInfo))); store.state.cartInfos, cartInfo)));
print('#3'); print('#3');
eventBus.fire(new OnCartInfoUpdated()); eventBus.fire(new OnCartInfoUpdated());
} else { } else {
if (cartInfo.productList[found].quantity + 1.0 > if (cartInfo.productList![found].quantity! + 1.0 >
event.product.leftNum) { event.product.leftNum!) {
// Fluttertoast.showToast( // Fluttertoast.showToast(
// msg: S.of(context).product_insufficient, // msg: S.of(context).product_insufficient,
// toastLength: Toast.LENGTH_SHORT, // toastLength: Toast.LENGTH_SHORT,
@@ -113,8 +122,8 @@ class Utils {
// backgroundColor: Colors.red, // backgroundColor: Colors.red,
// textColor: Colors.white); // textColor: Colors.white);
} else { } else {
cartInfo.productList[found].quantity += 1; cartInfo.productList![found].quantity = cartInfo.productList![found].quantity! + 1;
addSubproductQty(cartInfo, cartInfo.productList[found]); addSubproductQty(cartInfo, cartInfo.productList![found]);
store.dispatch(new UpdateCartInfo( store.dispatch(new UpdateCartInfo(
addCartInfoToCartInfoList( addCartInfoToCartInfoList(
store.state.cartInfos, cartInfo))); store.state.cartInfos, cartInfo)));
@@ -127,41 +136,41 @@ class Utils {
}); });
onProductWillRemoveFromCartSubscription = onProductWillRemoveFromCartSubscription =
eventBus.on<OnProductWillRemoveFromCart>().listen((event) { eventBus.on<OnProductWillRemoveFromCart>().listen((event) {
CartInfo cartInfo = CartInfo? cartInfo =
getCartInfoByBusiness(store.state.cartInfos, event.business); getCartInfoByBusiness(store.state.cartInfos, event.business);
if (cartInfo != null) { if (cartInfo != null) {
if (cartInfo.productList.length > 0) { if (cartInfo.productList!.length > 0) {
if (event.productListIndex != -1) { if (event.productListIndex != -1) {
if (cartInfo.productList[event.productListIndex].quantity <= 1) { if (cartInfo.productList![event.productListIndex].quantity! <= 1) {
String uuid = cartInfo.productList[event.productListIndex].uuid; String uuid = cartInfo.productList![event.productListIndex].uuid!;
cartInfo.productList.removeAt(event.productListIndex); cartInfo.productList!.removeAt(event.productListIndex);
removeSubproduct(cartInfo, uuid); removeSubproduct(cartInfo, uuid);
} else { } else {
cartInfo.productList[event.productListIndex].quantity -= 1; cartInfo.productList![event.productListIndex].quantity = cartInfo.productList![event.productListIndex].quantity! - 1;
addSubproductQty(cartInfo, cartInfo.productList[event.productListIndex], remove: true); addSubproductQty(cartInfo, cartInfo.productList![event.productListIndex], remove: true);
} }
} else { } else {
int productListIndex = -1; int productListIndex = -1;
for (var i = 0; i < cartInfo.productList.length; i++) { for (var i = 0; i < cartInfo.productList!.length; i++) {
if (cartInfo.productList[i].product.id == event.product.id) { if (cartInfo.productList![i].product!.id == event.product.id) {
productListIndex = i; productListIndex = i;
break; break;
} }
} }
if (productListIndex != -1) { if (productListIndex != -1) {
if (cartInfo.productList[productListIndex].quantity <= 1) { if (cartInfo.productList![productListIndex].quantity! <= 1) {
String uuid = cartInfo.productList[productListIndex].uuid; String uuid = cartInfo.productList![productListIndex].uuid!;
cartInfo.productList.removeAt(productListIndex); cartInfo.productList!.removeAt(productListIndex);
removeSubproduct(cartInfo, uuid); removeSubproduct(cartInfo, uuid);
} else { } else {
cartInfo.productList[productListIndex].quantity -= 1; cartInfo.productList![productListIndex].quantity = cartInfo.productList![productListIndex].quantity! - 1;
addSubproductQty(cartInfo, cartInfo.productList[productListIndex], remove: true); addSubproductQty(cartInfo, cartInfo.productList![productListIndex], remove: true);
} }
} }
} }
} }
if (cartInfo.productList.length <= 0) { if (cartInfo.productList!.length <= 0) {
store.dispatch(UpdateCartInfo(removeCartInfoFromCartInfoList( store.dispatch(UpdateCartInfo(removeCartInfoFromCartInfoList(
store.state.cartInfos, cartInfo))); store.state.cartInfos, cartInfo)));
} else { } else {
@@ -211,7 +220,7 @@ class Utils {
return false; return false;
} }
static Map<String, dynamic> stringToJson(String string) { static Map<String, dynamic>? stringToJson(String? string) {
if (string == null || string.isEmpty) { if (string == null || string.isEmpty) {
return null; return null;
} }
@@ -244,10 +253,6 @@ class Utils {
return platformName; return platformName;
} }
static Future<Box> getBox() async {
return Util.getBox();
}
static Widget imageLoadingIndicator( static Widget imageLoadingIndicator(
{double width = 30.0, double height = 30.0}) { {double width = 30.0, double height = 30.0}) {
return SizedBox( return SizedBox(
@@ -365,7 +370,7 @@ class Utils {
); );
} }
static showLoadingDialog(BuildContext context, {String message}) { static showLoadingDialog(BuildContext context, {String? message}) {
showDialog( showDialog(
context: context, context: context,
barrierDismissible: false, barrierDismissible: false,
@@ -468,46 +473,45 @@ class Utils {
} }
static void getCurrentUser() { static void getCurrentUser() {
getBox().then((box) { if (store.state.user != null) {
int userId = box.get(Constants.KEY_USER_ID, defaultValue: 0); eventBus.fire(OnCurrentUserUpdated());
String accessToken = return;
box.get(Constants.KEY_ACCESS_TOKEN, defaultValue: ''); }
if (userId == 0 || accessToken.isEmpty) { int? userId = prefs?.getInt(Constants.KEY_USER_ID) ?? 0;
eventBus.fire(new OnGetCurrentUserFailed(Error())); String? accessToken = prefs?.getString(Constants.KEY_ACCESS_TOKEN) ?? '';
} else { if (userId == 0 || accessToken.isEmpty) {
HttpUtil.httpGet( eventBus.fire(new OnGetCurrentUserFailed(Error()));
'v1/users/$userId', } else {
queryParameters: {}, HttpUtil.httpGet(
businessId: Constants.BUSINESS_ID, 'v1/users/$userId',
).then((value) { queryParameters: {},
User user = User.fromJson(value); businessId: Constants.BUSINESS_ID,
store.dispatch(UpdateCurrentUser(user)); ).then((value) {
eventBus.fire(OnCurrentUserUpdated()); User user = User.fromJson(value);
}).catchError((err) { store.dispatch(UpdateCurrentUser(user));
eventBus.fire(new OnGetCurrentUserFailed(err)); eventBus.fire(OnCurrentUserUpdated());
}); }).catchError((err) {
} eventBus.fire(new OnGetCurrentUserFailed(err));
}).catchError((err) { });
eventBus.fire(new OnGetCurrentUserFailed(err)); }
});
} }
static void showMessageDialog(BuildContext context, dynamic error, static void showMessageDialog(BuildContext context, dynamic error,
{String title, List<Widget> actions, OnOk onOk}) { {String? title, List<Widget>? actions, OnOk? onOk}) {
String message = ''; String message = '';
print('error $error'); print('error $error');
if (error is DioError && error.response != null) { if (error is DioException && error.response != null) {
if (error.response.data['message'] != null) { if (error.response!.data['message'] != null) {
message = error.response.data['message']; message = error.response!.data['message'];
} else if (error.response.data['error'] != null) { } else if (error.response!.data['error'] != null) {
if (error.response.data['error'] is String) { if (error.response!.data['error'] is String) {
message = error.response.data['error']; message = error.response!.data['error'];
} else if (error.response.data['error']['errmsg'] != null) { } else if (error.response!.data['error']['errmsg'] != null) {
message = error.response.data['error']['errmsg']; message = error.response!.data['error']['errmsg'];
} else if (error.response.data['error']['message'] != null) { } else if (error.response!.data['error']['message'] != null) {
message = error.response.data['error']['message']; message = error.response!.data['error']['message'];
} else { } else {
message = error.response.data.toString(); message = error.response!.data.toString();
} }
} }
} else if (error is String) { } else if (error is String) {
@@ -540,20 +544,15 @@ class Utils {
} }
static Future<List<int>> getLastVisit() async { static Future<List<int>> getLastVisit() async {
Box box = await getBox();
List<dynamic> lastVisit = List<dynamic> lastVisit =
json.decode(box.get(Constants.KEY_LAST_VISIT, defaultValue: '[]')); json.decode(prefs?.getString(Constants.KEY_LAST_VISIT) ?? '[]');
List<int> lv = lastVisit.map((e) => e as int).toList(); List<int> lv = lastVisit.map((e) => e as int).toList();
store.dispatch(UpdateLastVisit(lv)); store.dispatch(UpdateLastVisit(lv));
return lv; return lv;
} }
static void saveLastVisit(List<int> lastVisit) { static void saveLastVisit(List<int> lastVisit) {
getBox().then((box) { prefs?.setString(Constants.KEY_LAST_VISIT, lastVisit.toString());
box.put(Constants.KEY_LAST_VISIT, lastVisit.toString());
}).catchError((error) {
print('Error occurred: $error');
});
} }
static String utcDatetimeStringToLocalDatetimeString( static String utcDatetimeStringToLocalDatetimeString(
@@ -656,26 +655,26 @@ class Utils {
} }
} }
static CartInfo getCartInfoByBusiness( static CartInfo? getCartInfoByBusiness(
List<CartInfo> cartInfos, Business business) { List<CartInfo>? cartInfos, Business business) {
if (cartInfos == null || cartInfos.length <= 0) { if (cartInfos == null || cartInfos.length <= 0) {
return null; return null;
} }
for (var i = 0; i < cartInfos.length; i++) { for (var i = 0; i < cartInfos.length; i++) {
if (cartInfos[i].businessInfo.id == business.id) { if (cartInfos[i].businessInfo!.id == business.id) {
return cartInfos[i]; return cartInfos[i];
} }
} }
return null; return null;
} }
static CartInfo getCartInfoByBusinessId( static CartInfo? getCartInfoByBusinessId(
List<CartInfo> cartInfos, int businessId) { List<CartInfo>? cartInfos, int businessId) {
if (cartInfos == null || cartInfos.length <= 0) { if (cartInfos == null || cartInfos.length <= 0) {
return null; return null;
} }
for (var i = 0; i < cartInfos.length; i++) { for (var i = 0; i < cartInfos.length; i++) {
if (cartInfos[i].businessInfo.id == businessId) { if (cartInfos[i].businessInfo!.id == businessId) {
return cartInfos[i]; return cartInfos[i];
} }
} }
@@ -683,13 +682,13 @@ class Utils {
} }
static List<CartInfo> addCartInfoToCartInfoList( static List<CartInfo> addCartInfoToCartInfoList(
List<CartInfo> cartInfos, CartInfo cartInfo) { List<CartInfo>? cartInfos, CartInfo cartInfo) {
if (cartInfos == null || cartInfos.length <= 0) { if (cartInfos == null || cartInfos.length <= 0) {
cartInfos = [cartInfo]; cartInfos = [cartInfo];
} else { } else {
bool found = false; bool found = false;
for (var i = 0; i < cartInfos.length; i++) { for (var i = 0; i < cartInfos.length; i++) {
if (cartInfos[i].businessInfo.id == cartInfo.businessInfo.id) { if (cartInfos[i].businessInfo!.id == cartInfo.businessInfo!.id) {
cartInfos[i] = cartInfo; cartInfos[i] = cartInfo;
found = true; found = true;
break; break;
@@ -699,22 +698,19 @@ class Utils {
cartInfos.add(cartInfo); cartInfos.add(cartInfo);
} }
} }
Utils.getBox().then((box) { prefs?.setString(Constants.KEY_CARTINFOS, cartInfos.toString());
box.put(Constants.KEY_CARTINFOS, cartInfos.toString());
}).catchError((error) {
print('Error occurred: $error');
});
return cartInfos; return cartInfos;
} }
static List<CartInfo> removeCartInfoFromCartInfoList( static List<CartInfo> removeCartInfoFromCartInfoList(
List<CartInfo> cartInfos, CartInfo cartInfo) { List<CartInfo>? cartInfos, CartInfo? cartInfo) {
if (cartInfos == null || cartInfos.length <= 0 || cartInfo == null) { if (cartInfos == null || cartInfos.length <= 0 || cartInfo == null) {
prefs?.setString(Constants.KEY_CARTINFOS, cartInfos.toString());
return []; return [];
} }
int removeIndex = -1; int removeIndex = -1;
for (var i = 0; i < cartInfos.length; i++) { for (var i = 0; i < cartInfos.length; i++) {
if (cartInfo.businessInfo.id == cartInfos[i].businessInfo.id) { if (cartInfo.businessInfo!.id == cartInfos[i].businessInfo!.id) {
removeIndex = i; removeIndex = i;
break; break;
} }
@@ -722,17 +718,13 @@ class Utils {
if (removeIndex != -1) { if (removeIndex != -1) {
cartInfos.removeAt(removeIndex); cartInfos.removeAt(removeIndex);
} }
getBox().then((box) { prefs?.setString(Constants.KEY_CARTINFOS, cartInfos.toString());
box.put(Constants.KEY_CARTINFOS, cartInfos.toString());
}).catchError((error) {
print('Error occurred: $error');
});
return cartInfos; return cartInfos;
} }
static void clearCart(BuildContext context, CartInfo cartInfo, static void clearCart(BuildContext context, CartInfo cartInfo,
{OnComplete onComplete}) { {OnComplete? onComplete}) {
if (cartInfo != null && cartInfo.productList.length > 0) { if (cartInfo != null && cartInfo.productList!.length > 0) {
showDialog( showDialog(
context: context, context: context,
builder: (BuildContext context) { builder: (BuildContext context) {
@@ -766,7 +758,7 @@ class Utils {
} }
static void requireLogin(BuildContext context, static void requireLogin(BuildContext context,
{String returnUrl, bool replace = true, int delayMilliseconds = 400}) { {String? returnUrl, bool replace = true, int delayMilliseconds = 400}) {
Future.delayed(Duration(milliseconds: delayMilliseconds), () { Future.delayed(Duration(milliseconds: delayMilliseconds), () {
if (returnUrl != null) { if (returnUrl != null) {
store.dispatch(UpdateRedirectRoute(returnUrl)); store.dispatch(UpdateRedirectRoute(returnUrl));
@@ -775,9 +767,9 @@ class Utils {
}); });
} }
static String getFirstNumberFromString(String numString) { static String? getFirstNumberFromString(String numString) {
final intInStr = RegExp(r'\d+'); final intInStr = RegExp(r'\d+');
return intInStr.firstMatch(numString).group(0); return intInStr.firstMatch(numString)?.group(0);
} }
static void loadProducts(int businessId, int categoryId, int page, bool more, static void loadProducts(int businessId, int categoryId, int page, bool more,
@@ -845,7 +837,7 @@ class Utils {
} }
} }
static String getWeekDayName(BuildContext context, int timestamp, bool shortName) { static String? getWeekDayName(BuildContext context, int timestamp, bool shortName) {
DateTime date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000); DateTime date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
switch(date.weekday) { switch(date.weekday) {
case 1: case 1:
@@ -854,61 +846,54 @@ class Utils {
} else { } else {
return S.of(context).monday; return S.of(context).monday;
} }
break;
case 2: case 2:
if (shortName) { if (shortName) {
return S.of(context).tue; return S.of(context).tue;
} else { } else {
return S.of(context).tuesday; return S.of(context).tuesday;
} }
break;
case 3: case 3:
if (shortName) { if (shortName) {
return S.of(context).wed; return S.of(context).wed;
} else { } else {
return S.of(context).wednesday; return S.of(context).wednesday;
} }
break;
case 4: case 4:
if (shortName) { if (shortName) {
return S.of(context).thu; return S.of(context).thu;
} else { } else {
return S.of(context).thursday; return S.of(context).thursday;
} }
break;
case 5: case 5:
if (shortName) { if (shortName) {
return S.of(context).fri; return S.of(context).fri;
} else { } else {
return S.of(context).friday; return S.of(context).friday;
} }
break;
case 6: case 6:
if (shortName) { if (shortName) {
return S.of(context).sat; return S.of(context).sat;
} else { } else {
return S.of(context).saturday; return S.of(context).saturday;
} }
break;
case 7: case 7:
if (shortName) { if (shortName) {
return S.of(context).sun; return S.of(context).sun;
} else { } else {
return S.of(context).sunday; return S.of(context).sunday;
} }
break;
} }
} }
static void stripePaymentIntent(Order order, String customerId, String paymentMethodId, String cardType, static void stripePaymentIntent(Order order, String? customerId, String paymentMethodId, String cardType,
OnSuccess onSuccess, OnError onError, OnSuccess onSuccess, OnError onError,
{ {
String cardBrand, String? cardBrand,
String cardCountry, String? cardCountry,
int cardExpMonth, int? cardExpMonth,
int cardExpYear, int? cardExpYear,
String cardFunding, String? cardFunding,
String cardLast4, String? cardLast4,
}) { }) {
HttpUtil.httpPost('v1/stripe-payment-intent', HttpUtil.httpPost('v1/stripe-payment-intent',
@@ -919,12 +904,12 @@ class Utils {
'customer_id': customerId == null ? '' : customerId, 'customer_id': customerId == null ? '' : customerId,
'payment_method_id': paymentMethodId, 'payment_method_id': paymentMethodId,
'payment_method_type': cardType, 'payment_method_type': cardType,
'card_brand': cardBrand, 'card_brand': cardBrand ?? '',
'card_country': cardCountry, 'card_country': cardCountry ?? '',
'card_exp_month': cardExpMonth, 'card_exp_month': cardExpMonth ?? 0,
'card_exp_year': cardExpYear, 'card_exp_year': cardExpYear ?? 0,
'card_funding': cardFunding, 'card_funding': cardFunding ?? '',
'card_last4': cardLast4, 'card_last4': cardLast4 ?? '',
}, },
isFormData: true, isFormData: true,
).catchError(onError); ).catchError(onError);
@@ -945,8 +930,8 @@ class Utils {
static int getProductLineInOrder(CartInfo cartInfo) { static int getProductLineInOrder(CartInfo cartInfo) {
int qty = 0; int qty = 0;
for (CartLineItem lineItem in cartInfo.productList) { for (CartLineItem lineItem in cartInfo.productList!) {
if (lineItem.product.id != null) { if (lineItem.product?.id != null) {
qty += 1; qty += 1;
} }
} }
@@ -954,10 +939,10 @@ class Utils {
} }
static void orderAgain(BuildContext context, CartInfo cartInfo) { static void orderAgain(BuildContext context, CartInfo cartInfo) {
cartInfo.productList.removeWhere((element) => element.product == null || element.product.id == null); cartInfo.productList!.removeWhere((element) => element.product == null || element.product!.id == null);
store.dispatch(UpdateCartInfo(Utils.addCartInfoToCartInfoList(store.state.cartInfos, cartInfo))); store.dispatch(UpdateCartInfo(Utils.addCartInfoToCartInfoList(store.state.cartInfos, cartInfo)));
eventBus.fire(new OnCartInfoUpdated()); eventBus.fire(new OnCartInfoUpdated());
Routes.router.navigateTo(context, '/checkout/${cartInfo.businessInfo.id}'); Routes.router.navigateTo(context, '/checkout/${cartInfo.businessInfo!.id}');
} }
static String getOrderStatus(BuildContext context, int statusCode) { static String getOrderStatus(BuildContext context, int statusCode) {
@@ -978,42 +963,42 @@ class Utils {
} }
static CartLineItem newCartLineItem( static CartLineItem newCartLineItem(
{int id, {int? id,
double price, double? price,
Product product, Product? product,
String name, String? name,
String description, String? description,
double quantity, double? quantity,
String parentUuid, String? parentUuid,
}) { }) {
CartLineItem lineItem = CartLineItem(); CartLineItem lineItem = CartLineItem();
lineItem.unitPrice = price; lineItem.unitPrice = price;
lineItem.product = product; lineItem.product = product;
lineItem.name = product.name; lineItem.name = product?.name ?? '';
lineItem.description = description; lineItem.description = description;
lineItem.quantity = quantity; lineItem.quantity = quantity;
lineItem.parentUuid = parentUuid; lineItem.parentUuid = parentUuid ?? '';
return lineItem; return lineItem;
} }
static void addSubproductToCard(CartInfo cartInfo, CartLineItem lineItem) { static void addSubproductToCard(CartInfo cartInfo, CartLineItem lineItem) {
if (lineItem.product.subproducts.length > 0) { if (lineItem.product!.subproducts!.length > 0) {
for (int j = 0; j < lineItem.product.subproducts.length; j++) { for (int j = 0; j < lineItem.product!.subproducts!.length; j++) {
cartInfo.productList.add( cartInfo.productList!.add(
newCartLineItem( newCartLineItem(
id: 0, id: 0,
price: 0.0, price: 0.0,
product: Product( product: Product(
lineItem.product.subproducts[j].product.id, lineItem.product!.subproducts![j].product.id,
lineItem.product.businessId, lineItem.product!.businessId!,
lineItem.product.subproducts[j].product.name, lineItem.product!.subproducts![j].product.name,
lineItem.product.subproducts[j].product.price, lineItem.product!.subproducts![j].product.price,
lineItem.product.subproducts[j].product.description, lineItem.product!.subproducts![j].product.description,
lineItem.product.subproducts[j].product.image, lineItem.product!.subproducts![j].product.image,
lineItem.product.subproducts[j].product.productAttributes lineItem.product!.subproducts![j].product.productAttributes
), ),
name: lineItem.product.subproducts[j].product.name, name: lineItem.product!.subproducts![j].product.name,
description: lineItem.product.subproducts[j].product.description, description: lineItem.product!.subproducts![j].product.description,
quantity: 1.0, quantity: 1.0,
parentUuid: lineItem.uuid parentUuid: lineItem.uuid
) )
@@ -1024,16 +1009,16 @@ class Utils {
static void addSubproductQty(CartInfo cartInfo, CartLineItem lineItem, static void addSubproductQty(CartInfo cartInfo, CartLineItem lineItem,
{bool remove = false}) { {bool remove = false}) {
if (lineItem.product.subproducts.length > 0) { if (lineItem.product!.subproducts!.length > 0) {
for (var i = 0; i < cartInfo.productList.length; i++) { for (var i = 0; i < cartInfo.productList!.length; i++) {
CartLineItem lineItem1 = cartInfo.productList[i]; CartLineItem lineItem1 = cartInfo.productList![i];
if (lineItem1.parentUuid == lineItem.uuid) { if (lineItem1.parentUuid == lineItem.uuid) {
for (var j = 0; j < lineItem.product.subproducts.length; j++) { for (var j = 0; j < lineItem.product!.subproducts!.length; j++) {
if (lineItem.product.subproducts[j].product.id == lineItem1.product.id) { if (lineItem.product!.subproducts![j].product.id == lineItem1.product!.id) {
if (remove) { if (remove) {
lineItem1.quantity -= lineItem.product.subproducts[j].quantity; lineItem1.quantity = lineItem1.quantity! - lineItem.product!.subproducts![j].quantity;
} else { } else {
lineItem1.quantity += lineItem.product.subproducts[j].quantity; lineItem1.quantity = lineItem1.quantity! + lineItem.product!.subproducts![j].quantity;
} }
break; break;
} }
@@ -1044,7 +1029,7 @@ class Utils {
} }
static void removeSubproduct(CartInfo cartInfo, String uuid) { static void removeSubproduct(CartInfo cartInfo, String uuid) {
cartInfo.productList.removeWhere((element) => element.parentUuid == uuid); cartInfo.productList!.removeWhere((element) => element.parentUuid == uuid);
} }
static void openEmail(String email) async { static void openEmail(String email) async {
@@ -1069,7 +1054,7 @@ class Utils {
} }
} }
static Widget buildLine(String name, dynamic value, {double nameSize, double valueSize}) { static Widget buildLine(String name, dynamic value, {double? nameSize, double? valueSize}) {
Row row = Row( Row row = Row(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -1119,7 +1104,7 @@ class Utils {
} }
class RuntimeError extends Error { class RuntimeError extends Error {
final int code; final int? code;
final String message; final String message;
RuntimeError(this.message, {this.code}); RuntimeError(this.message, {this.code});
String toString() => "Runtime Error: $message"; String toString() => "Runtime Error: $message";

View File

@@ -13,9 +13,9 @@ import '../../widgets/general/breadcrumbs.dart';
import '../../widgets/general/navigationbar.dart'; import '../../widgets/general/navigationbar.dart';
class DesktopBuyService extends StatefulWidget { class DesktopBuyService extends StatefulWidget {
final Map<String, dynamic> data; final Map<String, dynamic>? data;
const DesktopBuyService(this.data, {Key key}) const DesktopBuyService(this.data, {Key? key})
: super(key: key); : super(key: key);
@override @override

View File

@@ -5,7 +5,8 @@ import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_wisetronic/widgets/general/breadcrumbs.dart'; import 'package:flutter_wisetronic/widgets/general/breadcrumbs.dart';
import 'package:fluttertoast/fluttertoast.dart'; import 'package:fluttertoast/fluttertoast.dart';
import 'package:gender_selection/gender_selection.dart'; import 'package:gender_picker/gender_picker.dart';
import 'package:gender_picker/source/enums.dart';
import '../../constants.dart'; import '../../constants.dart';
import '../../events/eventbus.dart'; import '../../events/eventbus.dart';
@@ -20,10 +21,9 @@ import '../../utils/utils.dart';
import '../../widgets/general/navigationbar.dart'; import '../../widgets/general/navigationbar.dart';
class DesktopEditAddress extends StatefulWidget { class DesktopEditAddress extends StatefulWidget {
final Key key; final Address? address;
final Address address;
final int businessId; final int businessId;
const DesktopEditAddress(this.address, {this.key, int businessId}) : const DesktopEditAddress(this.address, {Key? key, int? businessId}) :
businessId = businessId ?? Constants.BUSINESS_ID; businessId = businessId ?? Constants.BUSINESS_ID;
@override @override
@@ -45,12 +45,12 @@ class DesktopEditAddressState extends State<DesktopEditAddress> {
final emailController = TextEditingController(); final emailController = TextEditingController();
final faxController = TextEditingController(); final faxController = TextEditingController();
String country; String? country;
Gender _selectedGender; Gender? _selectedGender;
String _selectedProvince; String? _selectedProvince;
bool showLoading; bool showLoading = false;
double sideSpace = 0; double sideSpace = 0;
double mainSpace = 1200; double mainSpace = 1200;
@@ -105,8 +105,8 @@ class DesktopEditAddressState extends State<DesktopEditAddress> {
.of(context) .of(context)
.contact_name, .contact_name,
), ),
validator: (String value) { validator: (String? value) {
if (value if (value == null || value
.trim() .trim()
.isEmpty) { .isEmpty) {
return S return S
@@ -117,27 +117,25 @@ class DesktopEditAddressState extends State<DesktopEditAddress> {
}, },
), ),
), ),
GenderSelection( GenderPickerWithImage(
maleText: S onChanged: (Gender? gender) {
.of(context)
.mr,
femaleText: S
.of(context)
.ms,
selectedGenderIconBackgroundColor: Colors.indigo,
checkIconAlignment: Alignment.bottomRight,
selectedGenderCheckIcon: Icons.check,
onChanged: (Gender gender) {
_selectedGender = gender; _selectedGender = gender;
}, },
equallyAligned: true, maleText: S.of(context).mr,
animationDuration: Duration(milliseconds: 400), femaleText: S.of(context).ms,
isCircular: true,
isSelectedGenderIconCircular: true,
opacityOfGradient: 0.6,
padding: const EdgeInsets.all(3.0),
size: 50,
selectedGender: _selectedGender, selectedGender: _selectedGender,
showOtherGender: false,
verticalAlignedText: false,
selectedGenderTextStyle: TextStyle(
color: Color(0xFF8b32a8), fontWeight: FontWeight.bold),
unSelectedGenderTextStyle: TextStyle(
color: Colors.white, fontWeight: FontWeight.normal),
equallyAligned: true,
animationDuration: Duration(milliseconds: 200),
isCircular: true,
opacityOfGradient: 0.5,
padding: const EdgeInsets.all(3),
size: 50,
), ),
Container( Container(
padding: EdgeInsets.only( padding: EdgeInsets.only(
@@ -160,8 +158,8 @@ class DesktopEditAddressState extends State<DesktopEditAddress> {
.of(context) .of(context)
.mobile_phone_number, .mobile_phone_number,
), ),
validator: (String value) { validator: (String? value) {
if (value if (value == null || value
.trim() .trim()
.isEmpty) { .isEmpty) {
return S return S
@@ -192,8 +190,8 @@ class DesktopEditAddressState extends State<DesktopEditAddress> {
.of(context) .of(context)
.street_line_1, .street_line_1,
), ),
validator: (String value) { validator: (String? value) {
if (value if (value == null || value
.trim() .trim()
.isEmpty) { .isEmpty) {
return S return S
@@ -246,8 +244,8 @@ class DesktopEditAddressState extends State<DesktopEditAddress> {
.of(context) .of(context)
.city, .city,
), ),
validator: (String value) { validator: (String? value) {
if (value if (value == null || value
.trim() .trim()
.isEmpty) { .isEmpty) {
return S return S
@@ -316,8 +314,8 @@ class DesktopEditAddressState extends State<DesktopEditAddress> {
.of(context) .of(context)
.postal_code, .postal_code,
), ),
validator: (String value) { validator: (String? value) {
if (value if (value == null || value
.trim() .trim()
.isEmpty) { .isEmpty) {
return S return S
@@ -361,8 +359,8 @@ class DesktopEditAddressState extends State<DesktopEditAddress> {
.of(context) .of(context)
.email, .email,
), ),
validator: (String value) { validator: (String? value) {
if (value.isNotEmpty && !EmailValidator.validate(value)) { if (value != null && value.isNotEmpty && !EmailValidator.validate(value)) {
return S return S
.of(context) .of(context)
.email_is_not_valid; .email_is_not_valid;
@@ -496,29 +494,29 @@ class DesktopEditAddressState extends State<DesktopEditAddress> {
super.initState(); super.initState();
setState(() { setState(() {
showLoading = false; showLoading = false;
_selectedProvince = widget.address.state; _selectedProvince = widget.address?.state;
cityController.text = widget.address.city; cityController.text = widget.address?.city ?? '';
postalCodeController.text = widget.address.zip; postalCodeController.text = widget.address?.zip ?? '';
streetLine1Controller.text = widget.address.addressLine1; streetLine1Controller.text = widget.address?.addressLine1 ?? '';
streetLine2Controller.text = widget.address.addressLine2; streetLine2Controller.text = widget.address?.addressLine2 ?? '';
_selectedGender = widget.address.gender == 1 ? Gender.Male : Gender.Female; _selectedGender = widget.address?.gender == 1 ? Gender.Male : Gender.Female;
country = widget.address.country; country = widget.address?.country;
contactNameController.text = widget.address.contactName; contactNameController.text = widget.address?.contactName ?? '';
phoneController.text = widget.address.phone; phoneController.text = widget.address?.phone ?? '';
emailController.text = widget.address.email; emailController.text = widget.address?.email ?? '';
faxController.text = widget.address.fax; faxController.text = widget.address?.fax ?? '';
}); });
} }
void _saveEditAddress() { void _saveEditAddress() {
final FormState form = _formKey.currentState; final FormState? form = _formKey.currentState;
if (form.validate()) { if (form != null && form.validate()) {
if (mounted) { if (mounted) {
setState(() { setState(() {
showLoading = true; showLoading = true;
}); });
} }
HttpUtil.httpPatch('v1/addresses/${widget.address.id}', (response) { HttpUtil.httpPatch('v1/addresses/${widget.address?.id}', (response) {
if (mounted) { if (mounted) {
setState(() { setState(() {
showLoading = false; showLoading = false;
@@ -532,7 +530,7 @@ class DesktopEditAddressState extends State<DesktopEditAddress> {
} }
}, },
body: { body: {
'id': widget.address.id, 'id': widget.address?.id,
'name': contactNameController.text.trim(), 'name': contactNameController.text.trim(),
'address_line1': streetLine1Controller.text.trim(), 'address_line1': streetLine1Controller.text.trim(),
'address_line2': streetLine2Controller.text.trim(), 'address_line2': streetLine2Controller.text.trim(),
@@ -562,7 +560,7 @@ class DesktopEditAddressState extends State<DesktopEditAddress> {
showLoading = true; showLoading = true;
}); });
} }
HttpUtil.httpDelete('v1/addresses/${widget.address.id}', (response) { HttpUtil.httpDelete('v1/addresses/${widget.address?.id}', (response) {
if (mounted) { if (mounted) {
setState(() { setState(() {
showLoading = false; showLoading = false;

View File

@@ -1,10 +1,9 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_wisetronic/generated/l10n.dart';
class DesktopIndexMainContent1 extends StatefulWidget { class DesktopIndexMainContent1 extends StatefulWidget {
final String message; final String? message;
const DesktopIndexMainContent1(this.message, {Key key}) : super(key: key); const DesktopIndexMainContent1(this.message, {Key? key}) : super(key: key);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
@@ -37,7 +36,7 @@ class DesktopIndexMainContent1State extends State<DesktopIndexMainContent1> {
padding: EdgeInsets.symmetric(vertical: 30.0, horizontal: 30.0), padding: EdgeInsets.symmetric(vertical: 30.0, horizontal: 30.0),
child: Container( child: Container(
child: Text( child: Text(
widget.message, widget.message ?? '',
style: TextStyle( style: TextStyle(
fontSize: 20, fontSize: 20,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,

View File

@@ -5,8 +5,8 @@ import '../../widgets/general/text_link.dart';
import '../../utils/util_web.dart' if (dart.library.io) '../../utils/util_io.dart'; import '../../utils/util_web.dart' if (dart.library.io) '../../utils/util_io.dart';
class DesktopIndexMainContent2 extends StatefulWidget { class DesktopIndexMainContent2 extends StatefulWidget {
final Map<String, dynamic> content; final Map<String, dynamic>? content;
const DesktopIndexMainContent2(this.content, {Key key}) : super(key: key); const DesktopIndexMainContent2(this.content, {Key? key}) : super(key: key);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
@@ -54,7 +54,7 @@ class DesktopIndexMainContent2State extends State<DesktopIndexMainContent2> {
Container( Container(
padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0), padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0),
child: Text( child: Text(
'${widget.content['minipos']}', '${widget.content?['minipos']}',
style: TextStyle( style: TextStyle(
fontSize: 20.0, fontSize: 20.0,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@@ -66,7 +66,7 @@ class DesktopIndexMainContent2State extends State<DesktopIndexMainContent2> {
width: mainSpace / 2 - 100.0, width: mainSpace / 2 - 100.0,
padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0), padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0),
child: Text( child: Text(
'${widget.content['point_of_sale_system_solution']}', '${widget.content?['point_of_sale_system_solution']}',
style: TextStyle( style: TextStyle(
fontSize: 15.0, fontSize: 15.0,
color: Colors.grey, color: Colors.grey,
@@ -80,7 +80,7 @@ class DesktopIndexMainContent2State extends State<DesktopIndexMainContent2> {
Container( Container(
padding: EdgeInsets.symmetric(horizontal: 10.0), padding: EdgeInsets.symmetric(horizontal: 10.0),
child: Util.showImage( child: Util.showImage(
'https:${widget.content['minipos_image']['image']}', 'https:${widget.content?['minipos_image']['image']}',
fit: BoxFit.fitWidth fit: BoxFit.fitWidth
), ),
), ),
@@ -101,7 +101,7 @@ class DesktopIndexMainContent2State extends State<DesktopIndexMainContent2> {
Container( Container(
padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0), padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0),
child: Text( child: Text(
'${widget.content['igoshow']}', '${widget.content?['igoshow']}',
style: TextStyle( style: TextStyle(
fontSize: 20.0, fontSize: 20.0,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@@ -113,7 +113,7 @@ class DesktopIndexMainContent2State extends State<DesktopIndexMainContent2> {
width: mainSpace / 2 - 100.0, width: mainSpace / 2 - 100.0,
padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0), padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0),
child: Text( child: Text(
'${widget.content['igoshow_solution']}', '${widget.content?['igoshow_solution']}',
style: TextStyle( style: TextStyle(
fontSize: 15.0, fontSize: 15.0,
color: Colors.grey, color: Colors.grey,
@@ -127,7 +127,7 @@ class DesktopIndexMainContent2State extends State<DesktopIndexMainContent2> {
Container( Container(
padding: EdgeInsets.symmetric(horizontal: 10.0), padding: EdgeInsets.symmetric(horizontal: 10.0),
child: Util.showImage( child: Util.showImage(
'https:${widget.content['igoshow_image']['image']}', 'https:${widget.content?['igoshow_image']['image']}',
fit: BoxFit.fitWidth fit: BoxFit.fitWidth
), ),
), ),
@@ -149,7 +149,7 @@ class DesktopIndexMainContent2State extends State<DesktopIndexMainContent2> {
Column col = Column( Column col = Column(
children: [], children: [],
); );
for (int i = 0; i < (widget.content['minipos_features'] as List).length; i++) { for (int i = 0; i < (widget.content?['minipos_features'] as List).length; i++) {
col.children.add(Row( col.children.add(Row(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -166,7 +166,7 @@ class DesktopIndexMainContent2State extends State<DesktopIndexMainContent2> {
width: width - 40.0, width: width - 40.0,
padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0), padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0),
child: Text( child: Text(
'${(widget.content['minipos_features'] as List)[i]}', '${(widget.content?['minipos_features'] as List)[i]}',
style: TextStyle( style: TextStyle(
color: Colors.black54, color: Colors.black54,
), ),
@@ -195,7 +195,7 @@ class DesktopIndexMainContent2State extends State<DesktopIndexMainContent2> {
Column col = Column( Column col = Column(
children: [], children: [],
); );
for (int i = 0; i < (widget.content['igoshow_features'] as List).length; i++) { for (int i = 0; i < (widget.content?['igoshow_features'] as List).length; i++) {
col.children.add(Row( col.children.add(Row(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -212,7 +212,7 @@ class DesktopIndexMainContent2State extends State<DesktopIndexMainContent2> {
width: width - 40.0, width: width - 40.0,
padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0), padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0),
child: Text( child: Text(
'${(widget.content['igoshow_features'] as List)[i]}', '${(widget.content?['igoshow_features'] as List)[i]}',
style: TextStyle( style: TextStyle(
color: Colors.black54, color: Colors.black54,
), ),

View File

@@ -6,8 +6,8 @@ import 'package:flutter_wisetronic/widgets/general/text_link.dart';
import '../../constants.dart'; import '../../constants.dart';
class DesktopIndexMainContent3 extends StatefulWidget { class DesktopIndexMainContent3 extends StatefulWidget {
final Map<String, dynamic> content; final Map<String, dynamic>? content;
const DesktopIndexMainContent3(this.content, {Key key}) : super(key: key); const DesktopIndexMainContent3(this.content, {Key? key}) : super(key: key);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {

View File

@@ -14,12 +14,12 @@ import '../../widgets/general/breadcrumbs.dart';
import '../../widgets/general/navigationbar.dart'; import '../../widgets/general/navigationbar.dart';
class DesktopNavigationBar extends StatefulWidget { class DesktopNavigationBar extends StatefulWidget {
final bool hasBack; final bool? hasBack;
final List<BreadCrumb> breadCrumbs; final List<BreadCrumb>? breadCrumbs;
final Widget shoppingCart; final Widget? shoppingCart;
final OnBackPress onBackPress; final OnBackPress? onBackPress;
const DesktopNavigationBar({Key key, this.hasBack, this.breadCrumbs, const DesktopNavigationBar({Key? key, this.hasBack, this.breadCrumbs,
this.shoppingCart, this.onBackPress}) : super(key: key); this.shoppingCart, this.onBackPress}) : super(key: key);
@override @override
@@ -30,13 +30,13 @@ class DesktopNavigationBar extends StatefulWidget {
} }
class DesktopNavigationBarState extends State<DesktopNavigationBar> { class DesktopNavigationBarState extends State<DesktopNavigationBar> {
User _user; User? _user;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
Widget sc = SizedBox.shrink(); Widget sc = SizedBox.shrink();
if (widget.shoppingCart != null) { if (widget.shoppingCart != null) {
sc = widget.shoppingCart; sc = widget.shoppingCart!;
} }
Widget breadCrumbBar = SizedBox.shrink(); Widget breadCrumbBar = SizedBox.shrink();
if (widget.breadCrumbs != null && widget.breadCrumbs.length > 0) { if (widget.breadCrumbs != null && widget.breadCrumbs.length > 0) {
@@ -51,8 +51,8 @@ class DesktopNavigationBarState extends State<DesktopNavigationBar> {
Expanded( Expanded(
child: BreadCrumbs( child: BreadCrumbs(
widget.hasBack ?? false, widget.hasBack ?? false,
onBackPress: widget.onBackPress, onBackPress: widget.onBackPress!,
breadCrumbs: widget.breadCrumbs, breadCrumbs: widget.breadCrumbs!,
), ),
), ),
sc, sc,

View File

@@ -2,7 +2,8 @@
import 'package:email_validator/email_validator.dart'; import 'package:email_validator/email_validator.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_wisetronic/widgets/general/breadcrumbs.dart'; import 'package:flutter_wisetronic/widgets/general/breadcrumbs.dart';
import 'package:gender_selection/gender_selection.dart'; import 'package:gender_picker/gender_picker.dart';
import 'package:gender_picker/source/enums.dart';
import '../../constants.dart'; import '../../constants.dart';
import '../../generated/l10n.dart'; import '../../generated/l10n.dart';
@@ -14,10 +15,9 @@ import '../../utils/http_util.dart';
import '../../widgets/general/navigationbar.dart'; import '../../widgets/general/navigationbar.dart';
class DesktopNewAddress extends StatefulWidget { class DesktopNewAddress extends StatefulWidget {
final Key key; final LocatedAddress? locatedAddress;
final LocatedAddress locatedAddress; final int? businessId;
final int businessId; const DesktopNewAddress({Key? key, this.locatedAddress, this.businessId}) : super(key: key);
const DesktopNewAddress({this.key, this.locatedAddress, this.businessId}) : super(key: key);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
@@ -39,9 +39,9 @@ class DesktopNewAddressState extends State<DesktopNewAddress> {
final faxController = TextEditingController(); final faxController = TextEditingController();
String country = 'CA'; String country = 'CA';
Gender _selectedGender; Gender? _selectedGender;
String _selectedProvince; String? _selectedProvince;
double sideSpace = 0; double sideSpace = 0;
double mainSpace = 1200; double mainSpace = 1200;
@@ -97,31 +97,33 @@ class DesktopNewAddressState extends State<DesktopNewAddress> {
), ),
labelText: S.of(context).contact_name, labelText: S.of(context).contact_name,
), ),
validator: (String value) { validator: (String? value) {
if (value.trim().isEmpty) { if (value == null || value.trim().isEmpty) {
return S.of(context).contact_name_is_required; return S.of(context).contact_name_is_required;
} }
return null; return null;
}, },
), ),
), ),
GenderSelection( GenderPickerWithImage(
maleText: S.of(context).mr, onChanged: (Gender? gender) {
femaleText: S.of(context).ms,
selectedGenderIconBackgroundColor: Colors.indigo,
checkIconAlignment: Alignment.bottomRight,
selectedGenderCheckIcon: Icons.check,
onChanged: (Gender gender) {
_selectedGender = gender; _selectedGender = gender;
}, },
equallyAligned: true, maleText: S.of(context).mr,
animationDuration: Duration(milliseconds: 400), femaleText: S.of(context).ms,
isCircular: true,
isSelectedGenderIconCircular: true,
opacityOfGradient: 0.6,
padding: const EdgeInsets.all(3.0),
size: 50,
selectedGender: _selectedGender, selectedGender: _selectedGender,
showOtherGender: false,
verticalAlignedText: false,
selectedGenderTextStyle: TextStyle(
color: Color(0xFF8b32a8), fontWeight: FontWeight.bold),
unSelectedGenderTextStyle: TextStyle(
color: Colors.white, fontWeight: FontWeight.normal),
equallyAligned: true,
animationDuration: Duration(milliseconds: 200),
isCircular: true,
opacityOfGradient: 0.5,
padding: const EdgeInsets.all(3),
size: 50,
), ),
Container( Container(
padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0, bottom: 0.0), padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0, bottom: 0.0),
@@ -141,8 +143,8 @@ class DesktopNewAddressState extends State<DesktopNewAddress> {
), ),
labelText: S.of(context).mobile_phone_number, labelText: S.of(context).mobile_phone_number,
), ),
validator: (String value) { validator: (String? value) {
if (value.trim().isEmpty) { if (value == null || value.trim().isEmpty) {
return S.of(context).mobile_phone_number_is_required; return S.of(context).mobile_phone_number_is_required;
} }
return null; return null;
@@ -166,8 +168,8 @@ class DesktopNewAddressState extends State<DesktopNewAddress> {
), ),
labelText: S.of(context).street_line_1, labelText: S.of(context).street_line_1,
), ),
validator: (String value) { validator: (String? value) {
if (value.trim().isEmpty) { if (value == null || value.trim().isEmpty) {
return S.of(context).street_line_1_is_required; return S.of(context).street_line_1_is_required;
} }
return null; return null;
@@ -210,8 +212,8 @@ class DesktopNewAddressState extends State<DesktopNewAddress> {
), ),
labelText: S.of(context).city, labelText: S.of(context).city,
), ),
validator: (String value) { validator: (String? value) {
if (value.trim().isEmpty) { if (value == null || value.trim().isEmpty) {
return S.of(context).city_is_required; return S.of(context).city_is_required;
} }
return null; return null;
@@ -256,8 +258,8 @@ class DesktopNewAddressState extends State<DesktopNewAddress> {
), ),
labelText: S.of(context).postal_code, labelText: S.of(context).postal_code,
), ),
validator: (String value) { validator: (String? value) {
if (value.trim().isEmpty) { if (value == null || value.trim().isEmpty) {
return S.of(context).postal_code_is_required; return S.of(context).postal_code_is_required;
} }
return null; return null;
@@ -291,8 +293,8 @@ class DesktopNewAddressState extends State<DesktopNewAddress> {
), ),
labelText: S.of(context).email, labelText: S.of(context).email,
), ),
validator: (String value) { validator: (String? value) {
if (value.isNotEmpty && !EmailValidator.validate(value)) { if (value == null || value.isNotEmpty && !EmailValidator.validate(value)) {
return S.of(context).email_is_not_valid; return S.of(context).email_is_not_valid;
} }
return null; return null;
@@ -377,15 +379,15 @@ class DesktopNewAddressState extends State<DesktopNewAddress> {
super.initState(); super.initState();
setState(() { setState(() {
if (widget.locatedAddress != null) { if (widget.locatedAddress != null) {
if (provinces.contains(widget.locatedAddress.province)) { if (provinces.contains(widget.locatedAddress?.province)) {
_selectedProvince = widget.locatedAddress.province; _selectedProvince = widget.locatedAddress?.province;
} }
cityController.text = widget.locatedAddress.city; cityController.text = widget.locatedAddress?.city ?? '';
postalCodeController.text = widget.locatedAddress.postalCode; postalCodeController.text = widget.locatedAddress?.postalCode ?? '';
streetLine1Controller.text = (widget.locatedAddress.streetNumber != null streetLine1Controller.text = (widget.locatedAddress?.streetNumber != null
&& widget.locatedAddress.streetNumber.isNotEmpty && widget.locatedAddress!.streetNumber.isNotEmpty
? widget.locatedAddress.streetNumber + ' ' : '') ? widget.locatedAddress!.streetNumber + ' ' : '')
+ widget.locatedAddress.streetName; + widget.locatedAddress!.streetName;
} else { } else {
_selectedProvince = 'Ontario'; _selectedProvince = 'Ontario';
} }
@@ -395,11 +397,11 @@ class DesktopNewAddressState extends State<DesktopNewAddress> {
} }
void _saveNewAddress() { void _saveNewAddress() {
final FormState form = _formKey.currentState; final FormState? form = _formKey.currentState;
if (form.validate()) { if (form != null && form.validate()) {
HttpUtil.httpPost('v1/addresses', (response) { HttpUtil.httpPost('v1/addresses', (response) {
if (widget.businessId > 0) { if (widget.businessId != null && widget.businessId! > 0) {
Routes.router.navigateTo(context, '/checkout/${widget.businessId}', replace: true); Routes.router.navigateTo(context, '/checkout/${widget.businessId}', replace: true);
} else { } else {
Routes.router.navigateTo(context, '/my-addresses/${widget.businessId}', replace: true); Routes.router.navigateTo(context, '/my-addresses/${widget.businessId}', replace: true);

View File

@@ -1,8 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:stripe_sdk/stripe_sdk.dart'; import '../../vendor/stripe_sdk/lib/stripe_sdk_ui.dart';
import 'package:stripe_sdk/stripe_sdk_ui.dart'; import '../../utils/mini_stripe_api.dart';
import '../../constants.dart'; import '../../constants.dart';
import '../../events/eventbus.dart'; import '../../events/eventbus.dart';
@@ -20,11 +20,10 @@ import '../../widgets/general/navigationbar.dart';
class DesktopStripePayWeb extends StatefulWidget { class DesktopStripePayWeb extends StatefulWidget {
final Key key;
final Order order; final Order order;
final PaymentPlatform paymentPlatform; final PaymentPlatform paymentPlatform;
final StripePaymentMethod stripePaymentMethod; final StripePaymentMethod? stripePaymentMethod;
const DesktopStripePayWeb(this.order, this.paymentPlatform, {this.key, this.stripePaymentMethod}); const DesktopStripePayWeb(this.order, this.paymentPlatform, {Key? key, this.stripePaymentMethod});
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
@@ -39,9 +38,9 @@ class DesktopStripePayWebState extends State<DesktopStripePayWeb> {
final formKey = GlobalKey<FormState>(); final formKey = GlobalKey<FormState>();
final card = StripeCard(); final card = StripeCard();
CardForm form; CardForm? form;
bool isSubmitting; bool isSubmitting = false;
double sideSpace = 0; double sideSpace = 0;
double mainSpace = 1200; double mainSpace = 1200;
@@ -69,23 +68,37 @@ class DesktopStripePayWebState extends State<DesktopStripePayWeb> {
form = CardForm(card: card, formKey: formKey, displayPostalCode: false,); form = CardForm(card: card, formKey: formKey, displayPostalCode: false,);
body = ListView( body = ListView(
children: <Widget>[ children: <Widget>[
form, form!,
Container( Container(
padding: EdgeInsets.only(top: 20.0, bottom: 20.0, right: 16.0), padding: EdgeInsets.only(top: 20.0, bottom: 20.0, right: 16.0),
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
child: ElevatedButton( child: ElevatedButton.icon(
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
primary: Theme.of(context).primaryColor, backgroundColor: Colors.green,
foregroundColor: Colors.white,
padding:
EdgeInsets.only(left: 32, right: 32, top: 20, bottom: 20),
elevation: 2.0,
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
),
), ),
child: Text( icon: Icon(
S.of(context).submit, Icons.check,
size: 32.0,
color: Colors.yellow,
),
label: Text(
S.of(context).pay,
style: TextStyle( style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white, color: Colors.white,
), ),
), ),
onPressed: () { onPressed: () {
if (formKey.currentState.validate()) { if (formKey.currentState != null && formKey.currentState!.validate()) {
formKey.currentState.save(); formKey.currentState!.save();
_paymentRequestWithCard(context); _paymentRequestWithCard(context);
} else { } else {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@@ -131,7 +144,7 @@ class DesktopStripePayWebState extends State<DesktopStripePayWeb> {
void initState() { void initState() {
super.initState(); super.initState();
isSubmitting = false; isSubmitting = false;
StripeApi.init(widget.paymentPlatform.publishableKey); MiniStripeApi.init(widget.paymentPlatform.publishableKey!);
} }
SnackBar messageSnackBar(BuildContext context, String message) { SnackBar messageSnackBar(BuildContext context, String message) {
@@ -160,12 +173,12 @@ class DesktopStripePayWebState extends State<DesktopStripePayWeb> {
} }
_paymentWithPaymentMethod(BuildContext context) async { _paymentWithPaymentMethod(BuildContext context) async {
Utils.stripePaymentIntent(widget.order, widget.stripePaymentMethod.customerId, Utils.stripePaymentIntent(widget.order, widget.stripePaymentMethod?.customerId,
widget.stripePaymentMethod.paymentMethodId, widget.stripePaymentMethod!.paymentMethodId,
widget.stripePaymentMethod.paymentMethodType, (response) async { widget.stripePaymentMethod!.paymentMethodType, (response) async {
if (response.data['status'] == Constants.STRIPE_STATUS_REQUIRES_CONFIRMATION) { if (response.data['status'] == Constants.STRIPE_STATUS_REQUIRES_CONFIRMATION) {
await StripeApi.instance.confirmPaymentIntent( await MiniStripeApi.instance.confirmPaymentIntent(
response.data[Constants.STRIPE_CLIENT_SECRET], response.data[Constants.STRIPE_CLIENT_SECRET],
data: { data: {
'payment_method': response.data['payment_method'], 'payment_method': response.data['payment_method'],
@@ -173,7 +186,7 @@ class DesktopStripePayWebState extends State<DesktopStripePayWeb> {
).then((result2) { ).then((result2) {
if (result2['status'] == Constants.STRIPE_STATUS_SUCCEDED) { if (result2['status'] == Constants.STRIPE_STATUS_SUCCEDED) {
Utils.stripeChargedSuccess(widget.order, Utils.stripeChargedSuccess(widget.order,
widget.stripePaymentMethod.paymentMethodId, widget.stripePaymentMethod!.paymentMethodId,
result2['id'], (response) { result2['id'], (response) {
if (isSubmitting) { if (isSubmitting) {
Navigator.of(context).pop(); Navigator.of(context).pop();
@@ -198,11 +211,11 @@ class DesktopStripePayWebState extends State<DesktopStripePayWeb> {
_paymentRequestWithCard(BuildContext context) async { _paymentRequestWithCard(BuildContext context) async {
isSubmitting = true; isSubmitting = true;
Utils.showSubmitDialog(context); Utils.showSubmitDialog(context);
await StripeApi.instance.createPaymentMethodFromCard(card) await MiniStripeApi.instance.createPaymentMethodFromCard(card)
.then((result) { .then((result) {
Utils.stripePaymentIntent(widget.order, null, result['id'], result['type'], (response) async { Utils.stripePaymentIntent(widget.order, null, result['id'], result['type'], (response) async {
if (response.data['status'] == Constants.STRIPE_STATUS_REQUIRES_CONFIRMATION) { if (response.data['status'] == Constants.STRIPE_STATUS_REQUIRES_CONFIRMATION) {
await StripeApi.instance.confirmPaymentIntent( await MiniStripeApi.instance.confirmPaymentIntent(
response.data[Constants.STRIPE_CLIENT_SECRET], response.data[Constants.STRIPE_CLIENT_SECRET],
data: { data: {
'payment_method': response.data['payment_method'], 'payment_method': response.data['payment_method'],

View File

@@ -1,6 +1,6 @@
import 'package:badges/badges.dart'; import 'package:badges/badges.dart' as badges;
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart'; import 'package:fluttertoast/fluttertoast.dart';
@@ -17,16 +17,16 @@ import '../../store/store.dart';
import '../../utils/utils.dart'; import '../../utils/utils.dart';
class AddRemoveButton extends StatefulWidget { class AddRemoveButton extends StatefulWidget {
final Product product; final Product? product;
final Business business; final Business business;
final bool addOnly; final bool? addOnly;
final int cartLineItemIndex; final int? cartLineItemIndex;
final bool addToBasket; final bool? addToBasket;
final bool onHovor; final bool? onHovor;
AddRemoveButton({ AddRemoveButton({
this.product, this.product,
this.business, required this.business,
this.addOnly = false, this.addOnly = false,
this.cartLineItemIndex = -1, this.cartLineItemIndex = -1,
this.addToBasket = false, this.addToBasket = false,
@@ -40,7 +40,7 @@ class AddRemoveButton extends StatefulWidget {
} }
class AddRemoveButtonState extends State<AddRemoveButton> { class AddRemoveButtonState extends State<AddRemoveButton> {
int _qty; int? _qty;
var zeroColor = const Color(0xFFEFEFEF); var zeroColor = const Color(0xFFEFEFEF);
var qtyColor = const Color(0xFFFF6666); var qtyColor = const Color(0xFFFF6666);
var zeroFontColor = const Color(0xFF888888); var zeroFontColor = const Color(0xFF888888);
@@ -48,7 +48,7 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
var d = 1; var d = 1;
CartInfo cartInfo; CartInfo? cartInfo;
GlobalKey startKey = GlobalKey(); GlobalKey startKey = GlobalKey();
@@ -59,14 +59,14 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (widget.product.leftNum == null) { if (widget.product?.leftNum == null) {
_qty = 0; _qty = 0;
cartInfo = Utils.getCartInfoByBusiness(store.state.cartInfos, widget.business); cartInfo = Utils.getCartInfoByBusiness(store.state.cartInfos, widget.business);
if (cartInfo != null) { if (cartInfo != null) {
for (var i = 0; i < cartInfo.productList.length; i++) { for (var i = 0; i < cartInfo!.productList!.length; i++) {
if (cartInfo.productList[i].product.id == widget.product.id if (cartInfo!.productList?[i].product?.id == widget.product?.id
&& cartInfo.productList[i].unitPrice == 0.0) { && cartInfo!.productList?[i].unitPrice == 0.0) {
_qty = cartInfo.productList[i].quantity.round(); _qty = cartInfo!.productList?[i].quantity?.round();
break; break;
} }
} }
@@ -78,7 +78,7 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
), ),
); );
} }
if (widget.product.leftNum <= 0) { if (widget.product!.leftNum! <= 0) {
return Container( return Container(
padding: EdgeInsets.only(top: 0.0, bottom: 10.0, left: 8.0, right: 8.0), padding: EdgeInsets.only(top: 0.0, bottom: 10.0, left: 8.0, right: 8.0),
child: Text( child: Text(
@@ -100,19 +100,19 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
), ),
); );
} }
if (widget.addToBasket) { if (widget.addToBasket!) {
_qty = 0; _qty = 0;
cartInfo = Utils.getCartInfoByBusiness(store.state.cartInfos, widget.business); cartInfo = Utils.getCartInfoByBusiness(store.state.cartInfos, widget.business);
if (cartInfo != null) { if (cartInfo != null) {
for (var i = 0; i < cartInfo.productList.length; i++) { for (var i = 0; i < cartInfo!.productList!.length; i++) {
if (cartInfo.productList[i].product.id == widget.product.id) { if (cartInfo!.productList?[i].product?.id == widget.product?.id) {
_qty = cartInfo.productList[i].quantity.round(); _qty = cartInfo!.productList?[i].quantity?.round();
break; break;
} }
} }
} }
if (_qty > 0) { if (_qty! > 0) {
return Badge( return badges.Badge(
badgeContent: Text( badgeContent: Text(
'$_qty', '$_qty',
style: TextStyle( style: TextStyle(
@@ -120,14 +120,17 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
fontSize: 17.0, fontSize: 17.0,
), ),
), ),
padding: EdgeInsets.all(10), badgeStyle: badges.BadgeStyle(
position: BadgePosition.topEnd(top: -15, end: -10), padding: EdgeInsets.all(10),
badgeColor: Colors.lightBlueAccent, badgeColor: Colors.lightBlueAccent,
),
position: badges.BadgePosition.topEnd(top: -15, end: -10),
child: ElevatedButton.icon( child: ElevatedButton.icon(
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
primary: Colors.redAccent, backgroundColor: Colors.redAccent,
onPrimary: Colors.white, foregroundColor: Colors.white,
padding: EdgeInsets.only(left: 32, right: 32, top: 20, bottom: 20), padding:
EdgeInsets.only(left: 32, right: 32, top: 20, bottom: 20),
elevation: 2.0, elevation: 2.0,
shape: new RoundedRectangleBorder( shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0), borderRadius: new BorderRadius.circular(10.0),
@@ -154,7 +157,7 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
} else { } else {
return ElevatedButton.icon( return ElevatedButton.icon(
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
primary: Colors.redAccent, backgroundColor: Colors.redAccent,
padding: EdgeInsets.only(left: 32, right: 32, top: 20, bottom: 20), padding: EdgeInsets.only(left: 32, right: 32, top: 20, bottom: 20),
elevation: 2.0, elevation: 2.0,
shape: new RoundedRectangleBorder( shape: new RoundedRectangleBorder(
@@ -179,7 +182,7 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
}, },
); );
} }
} else if (widget.addOnly) { } else if (widget.addOnly!) {
return Container( return Container(
key: startKey, key: startKey,
padding: EdgeInsets.all(0.0), padding: EdgeInsets.all(0.0),
@@ -197,15 +200,15 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
_qty = 0; _qty = 0;
cartInfo = Utils.getCartInfoByBusiness(store.state.cartInfos, widget.business); cartInfo = Utils.getCartInfoByBusiness(store.state.cartInfos, widget.business);
if (cartInfo != null) { if (cartInfo != null) {
for (var i = 0; i < cartInfo.productList.length; i++) { for (var i = 0; i < cartInfo!.productList!.length; i++) {
if (cartInfo.productList[i].product.id == widget.product.id) { if (cartInfo!.productList?[i].product?.id == widget.product?.id) {
_qty = cartInfo.productList[i].quantity.round(); _qty = cartInfo!.productList?[i].quantity?.round();
break; break;
} }
} }
} }
if (widget.product.productAttributes != null && if (widget.product!.productAttributes != null &&
widget.product.productAttributes.length > 0 && widget.cartLineItemIndex == -1) { widget.product!.productAttributes!.length > 0 && widget.cartLineItemIndex == -1) {
return new Row( return new Row(
key: startKey, key: startKey,
crossAxisAlignment: CrossAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end,
@@ -219,13 +222,13 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
style: new TextStyle( style: new TextStyle(
fontSize: 13.0, fontSize: 13.0,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: _qty > 0 ? qtyFontColor : zeroFontColor color: _qty! > 0 ? qtyFontColor : zeroFontColor
), ),
), ),
), ),
padding: EdgeInsets.all(5.0).copyWith(left: 10.0, right: 10.0), padding: EdgeInsets.all(5.0).copyWith(left: 10.0, right: 10.0),
decoration: BoxDecoration( decoration: BoxDecoration(
color: _qty > 0 ? qtyColor : zeroColor, color: _qty! > 0 ? qtyColor : zeroColor,
shape: BoxShape.rectangle, shape: BoxShape.rectangle,
borderRadius: BorderRadius.only( borderRadius: BorderRadius.only(
topLeft: Radius.circular(10.0), topLeft: Radius.circular(10.0),
@@ -242,7 +245,7 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
], ],
); );
} else { } else {
if (!widget.onHovor && _qty == 0) { if (!widget.onHovor! && _qty == 0) {
return SizedBox.shrink(); return SizedBox.shrink();
} }
return new Row( return new Row(
@@ -258,13 +261,13 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
style: new TextStyle( style: new TextStyle(
fontSize: 13.0, fontSize: 13.0,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: _qty > 0 ? qtyFontColor : zeroFontColor color: _qty! > 0 ? qtyFontColor : zeroFontColor
), ),
), ),
), ),
padding: EdgeInsets.all(5.0).copyWith(left: 10.0, right: 10.0), padding: EdgeInsets.all(5.0).copyWith(left: 10.0, right: 10.0),
decoration: BoxDecoration( decoration: BoxDecoration(
color: _qty > 0 ? qtyColor : zeroColor, color: _qty! > 0 ? qtyColor : zeroColor,
shape: BoxShape.rectangle, shape: BoxShape.rectangle,
borderRadius: BorderRadius.only( borderRadius: BorderRadius.only(
topLeft: Radius.circular(10.0), topLeft: Radius.circular(10.0),
@@ -299,7 +302,7 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
), ),
), ),
onTap: () { onTap: () {
if (_qty > 0) { if (_qty! > 0) {
_removeFromCart(context); _removeFromCart(context);
} }
}, },
@@ -312,7 +315,7 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
void _addToCart(BuildContext context) { void _addToCart(BuildContext context) {
if (widget.cartLineItemIndex != -1) { if (widget.cartLineItemIndex != -1) {
if (cartInfo.productList[widget.cartLineItemIndex].quantity + 1.0 > widget.product.leftNum) { if (cartInfo!.productList![widget.cartLineItemIndex!].quantity! + 1.0 > widget.product!.leftNum!) {
Fluttertoast.showToast( Fluttertoast.showToast(
msg: S.of(context).product_insufficient, msg: S.of(context).product_insufficient,
toastLength: Toast.LENGTH_SHORT, toastLength: Toast.LENGTH_SHORT,
@@ -321,23 +324,23 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
textColor: Colors.white textColor: Colors.white
); );
} else { } else {
cartInfo.productList[widget.cartLineItemIndex].quantity += 1.0; cartInfo!.productList![widget.cartLineItemIndex!].quantity = cartInfo!.productList![widget.cartLineItemIndex!].quantity! + 1.0;
Utils.addSubproductQty(cartInfo, cartInfo.productList[widget.cartLineItemIndex]); Utils.addSubproductQty(cartInfo!, cartInfo!.productList![widget.cartLineItemIndex!]);
store.dispatch(UpdateCartInfo( store.dispatch(UpdateCartInfo(
Utils.addCartInfoToCartInfoList(store.state.cartInfos, cartInfo))); Utils.addCartInfoToCartInfoList(store.state.cartInfos, cartInfo!)));
eventBus.fire(new OnCartInfoUpdated()); eventBus.fire(new OnCartInfoUpdated());
} }
} else { } else {
if (widget.product.productAttributes.length > 0) { if (widget.product!.productAttributes!.length > 0) {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute(builder: (context) => MaterialPageRoute(builder: (context) =>
new AttributeSelection( new AttributeSelection(
product: widget.product, business: widget.business, startKey: startKey,)), product: widget.product!, business: widget.business, startKey: startKey,)),
); );
} else { } else {
eventBus.fire(new OnProductWillAddToCart(widget.product, {}, eventBus.fire(new OnProductWillAddToCart(widget.product!, {},
widget.product.price, widget.product.description, widget.product!.price!, widget.product!.description!,
widget.business, buttonKey: startKey)); widget.business, buttonKey: startKey));
} }
} }
@@ -345,7 +348,7 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
void _removeFromCart(BuildContext context) { void _removeFromCart(BuildContext context) {
if (widget.cartLineItemIndex != -1) { if (widget.cartLineItemIndex != -1) {
if (cartInfo.productList[widget.cartLineItemIndex].quantity <= 1) { if (cartInfo!.productList![widget.cartLineItemIndex!].quantity! <= 1) {
showDialog( showDialog(
context: context, context: context,
builder: (BuildContext context) { builder: (BuildContext context) {
@@ -375,23 +378,23 @@ class AddRemoveButtonState extends State<AddRemoveButton> {
} }
} else { } else {
eventBus.fire(new OnProductWillRemoveFromCart( eventBus.fire(new OnProductWillRemoveFromCart(
widget.product, -1, widget.business)); widget.product!, -1, widget.business));
} }
} }
void _removeCartLineItem() { void _removeCartLineItem() {
if (cartInfo.productList[widget.cartLineItemIndex].quantity <= 1) { if (cartInfo!.productList![widget.cartLineItemIndex!].quantity! <= 1) {
String uuid = cartInfo.productList[widget.cartLineItemIndex].uuid; String uuid = cartInfo!.productList![widget.cartLineItemIndex!].uuid!;
cartInfo.productList.removeAt(widget.cartLineItemIndex); cartInfo!.productList?.removeAt(widget.cartLineItemIndex!);
Utils.removeSubproduct(cartInfo, uuid); Utils.removeSubproduct(cartInfo!, uuid);
} else { } else {
cartInfo.productList[widget.cartLineItemIndex].quantity -= 1; cartInfo!.productList![widget.cartLineItemIndex!].quantity = cartInfo!.productList![widget.cartLineItemIndex!].quantity! - 1;
Utils.addSubproductQty(cartInfo, cartInfo.productList[widget.cartLineItemIndex], remove: true); Utils.addSubproductQty(cartInfo!, cartInfo!.productList![widget.cartLineItemIndex!], remove: true);
} }
if (cartInfo.productList.length <= 0) { if (cartInfo!.productList!.length <= 0) {
store.dispatch(new UpdateCartInfo(Utils.removeCartInfoFromCartInfoList(store.state.cartInfos, cartInfo))); store.dispatch(new UpdateCartInfo(Utils.removeCartInfoFromCartInfoList(store.state.cartInfos, cartInfo)));
} else { } else {
store.dispatch(new UpdateCartInfo(Utils.addCartInfoToCartInfoList(store.state.cartInfos, cartInfo))); store.dispatch(new UpdateCartInfo(Utils.addCartInfoToCartInfoList(store.state.cartInfos, cartInfo!)));
} }
eventBus.fire(new OnCartInfoUpdated()); eventBus.fire(new OnCartInfoUpdated());
} }

View File

@@ -5,23 +5,23 @@ import 'popup_animation_widget.dart';
class AnimationPointManager { class AnimationPointManager {
List<AnimatedWidget> list = []; List<AnimatedWidget> list = [];
static AnimationController controller1; static AnimationController? controller1;
static AnimationController controller2; static AnimationController? controller2;
Future<void> addParabolicAniamtion({ Future<void> addParabolicAniamtion({
@required TickerProvider vsync, required TickerProvider vsync,
@required GlobalKey stackKey, required GlobalKey stackKey,
@required GlobalKey startKey, required GlobalKey startKey,
@required GlobalKey endKey, required GlobalKey endKey,
@required Duration duration, required Duration duration,
@required AnimationStatusListener statusListener, required AnimationStatusListener statusListener,
Color color = Colors.red, Color color = Colors.red,
double size = 20, double size = 20,
Offset startAdjustOffset = Offset.zero, Offset startAdjustOffset = Offset.zero,
Offset endAdjustOffset = Offset.zero, Offset endAdjustOffset = Offset.zero,
}) async { }) async {
controller1 = createController(vsync, duration); controller1 = createController(vsync, duration);
Animation animation = createAnimation(controller1); Animation<double> animation = createAnimation(controller1);
AnimatedWidget animatedWidget = ParabolicAnimationWidget( AnimatedWidget animatedWidget = ParabolicAnimationWidget(
animation: animation, animation: animation,
@@ -37,9 +37,9 @@ class AnimationPointManager {
statusListener(AnimationStatus.dismissed); statusListener(AnimationStatus.dismissed);
try { try {
await controller1.forward().orCancel; await controller1?.forward().orCancel;
list.remove(animatedWidget); list.remove(animatedWidget);
controller1.dispose(); controller1?.dispose();
print('Controller1 disposed'); print('Controller1 disposed');
} on TickerCanceled { } on TickerCanceled {
print("Ticker Canceled"); print("Ticker Canceled");
@@ -51,31 +51,31 @@ class AnimationPointManager {
} }
Future<void> addPopupAniamtion({ Future<void> addPopupAniamtion({
@required TickerProvider vsync, required TickerProvider vsync,
@required GlobalKey stackKey, required GlobalKey stackKey,
@required GlobalKey startKey, required GlobalKey startKey,
@required Widget child, required Widget child,
Duration duration, required Duration duration,
Offset popupOffset = Offset.zero, Offset popupOffset = Offset.zero,
AnimationStatusListener statusListener, AnimationStatusListener? statusListener,
}) async { }) async {
controller2 = createController(vsync, duration); controller2 = createController(vsync, duration);
AnimatedWidget animatedWidget = PopupAnimationWidget( AnimatedWidget animatedWidget = PopupAnimationWidget(
animation: controller2.view, animation: controller2!.view,
stackKey: stackKey, stackKey: stackKey,
startKey: startKey, startKey: startKey,
child: child, child: child,
popupOffset: popupOffset, popupOffset: popupOffset,
); );
list.add(animatedWidget); list.add(animatedWidget);
statusListener(AnimationStatus.dismissed); if (statusListener != null) statusListener(AnimationStatus.dismissed);
try { try {
await controller2.forward().orCancel; await controller2?.forward().orCancel;
await controller2.reverse().orCancel; await controller2?.reverse().orCancel;
list.remove(animatedWidget); list.remove(animatedWidget);
controller2.dispose(); controller2?.dispose();
print('Controller2 disposed'); print('Controller2 disposed');
} on TickerCanceled { } on TickerCanceled {
print("Ticker Canceled"); print("Ticker Canceled");
@@ -83,7 +83,7 @@ class AnimationPointManager {
print('Error: $error'); print('Error: $error');
} }
statusListener(AnimationStatus.completed); if (statusListener != null) statusListener(AnimationStatus.completed);
} }
static AnimationController createController( static AnimationController createController(

View File

@@ -14,7 +14,7 @@ import 'rules.dart';
import 'options_base.dart'; import 'options_base.dart';
class CheckOptions extends OptionsBase { class CheckOptions extends OptionsBase {
CheckOptions({@required Product product, @required int index, @required Map<String, dynamic> selections}) CheckOptions({required Product product, required int index, required Map<String, dynamic> selections})
: super(product: product, index: index, selections: selections); : super(product: product, index: index, selections: selections);
@override @override
@@ -50,14 +50,14 @@ class CheckOptionsState extends OptionsBaseState<CheckOptions> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[ children: <Widget>[
new Text( new Text(
S.of(context).check_option_select_token(product.productAttributes[this.index].name), S.of(context).check_option_select_token(product!.productAttributes![this.index!].name),
style: new TextStyle( style: new TextStyle(
fontSize: 12.5, fontSize: 12.5,
), ),
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
new Text( new Text(
product.productAttributes[this.index].required ? S.of(context).check_option_is_required : S.of(context).check_option_is_optional, product!.productAttributes![this.index!].required ? S.of(context).check_option_is_required : S.of(context).check_option_is_optional,
style: new TextStyle( style: new TextStyle(
fontSize: 10.0, fontSize: 10.0,
color: new Color(0xFF999999) color: new Color(0xFF999999)
@@ -95,25 +95,25 @@ class CheckOptionsState extends OptionsBaseState<CheckOptions> {
'adjust_amount': adjustAmount 'adjust_amount': adjustAmount
}; };
var cloneSelections = json.decode(json.encode(selections)); var cloneSelections = json.decode(json.encode(selections));
int idx = Utils.selectionsContains(cloneSelections, product.productAttributes[index].name, name); int idx = Utils.selectionsContains(cloneSelections, product!.productAttributes![index!].name, name);
if (idx != -1) { if (idx != -1) {
(cloneSelections[product.productAttributes[index].name.toUpperCase()] as List).removeAt(idx); (cloneSelections[product!.productAttributes![index!].name.toUpperCase()] as List).removeAt(idx);
} else if (cloneSelections.containsKey(product.productAttributes[index].name.toUpperCase())) { } else if (cloneSelections.containsKey(product!.productAttributes![index!].name.toUpperCase())) {
(cloneSelections[product.productAttributes[index].name.toUpperCase()] as List).add(opt); (cloneSelections[product!.productAttributes![index!].name.toUpperCase()] as List).add(opt);
} else { } else {
cloneSelections[product.productAttributes[index].name.toUpperCase()] = [opt]; cloneSelections[product!.productAttributes![index!].name.toUpperCase()] = [opt];
} }
if (idx != -1 && (cloneSelections[product.productAttributes[index].name.toUpperCase()] as List).length == 0) { if (idx != -1 && (cloneSelections[product!.productAttributes![index!].name.toUpperCase()] as List).length == 0) {
cloneSelections.remove(product.productAttributes[index].name.toUpperCase()); cloneSelections.remove(product!.productAttributes![index!].name.toUpperCase());
} }
setOptionsStateDisabled(product.productAttributes[index].name, false); setOptionsStateDisabled(product!.productAttributes![index!].name, false);
setState(() { setState(() {
selections = cloneSelections; selections = cloneSelections;
}); });
eventBus.fire(new OnAttributeSelectionsChanged(selections)); eventBus.fire(new OnAttributeSelectionsChanged(selections!));
} }
Widget _getOptionWidget() { Widget _getOptionWidget() {
@@ -121,20 +121,20 @@ class CheckOptionsState extends OptionsBaseState<CheckOptions> {
children: <Widget>[], children: <Widget>[],
); );
List<ProductOption> productOptions = product.productAttributes[index].productOptions; List<ProductOption> productOptions = product!.productAttributes![index!].productOptions;
if (!optionsState.containsKey(product.productAttributes[index].name)) { if (!optionsState.containsKey(product!.productAttributes![index!].name)) {
List<Map<String, dynamic>> optionState = []; List<Map<String, dynamic>> optionState = [];
for (var i = 0; i < productOptions.length; i++) { for (var i = 0; i < productOptions.length; i++) {
optionState.add({'name': product.productAttributes[index].productOptions[i].name, 'disabled': false, 'check': false}); optionState.add({'name': product!.productAttributes![index!].productOptions[i].name, 'disabled': false, 'check': false});
} }
optionsState[product.productAttributes[index].name] = optionState; optionsState[product!.productAttributes![index!].name] = optionState;
} }
if (selections.containsKey(product.productAttributes[index].name.toUpperCase())) { if (selections!.containsKey(product!.productAttributes![index!].name.toUpperCase())) {
Map<String, dynamic> attrExtraJson = Utils.stringToJson( Map<String, dynamic>? attrExtraJson = Utils.stringToJson(
product.productAttributes[index].extra); product!.productAttributes![index!].extra);
if (attrExtraJson != null) { if (attrExtraJson != null) {
var selectLimitIfFieldEqualsTo = Rule.getRule( var selectLimitIfFieldEqualsTo = Rule.getRule(
attrExtraJson, Rule.RULE_SELECT_LIMIT_IF_FIELD_EQUALS_TO); attrExtraJson, Rule.RULE_SELECT_LIMIT_IF_FIELD_EQUALS_TO);
@@ -147,15 +147,15 @@ class CheckOptionsState extends OptionsBaseState<CheckOptions> {
int limitQty = selectLimitIfFieldEqualsTo1[Rule int limitQty = selectLimitIfFieldEqualsTo1[Rule
.RULE_KEY_FORCE_LIMITED]; .RULE_KEY_FORCE_LIMITED];
thisLimitQty = limitQty; thisLimitQty = limitQty;
if ((selections[product.productAttributes[index].name if ((selections![product!.productAttributes![index!].name
.toUpperCase()] as List).length >= limitQty) { .toUpperCase()] as List).length >= limitQty) {
disableOptionIfNotSelected(); disableOptionIfNotSelected();
} }
} else if (Utils.getSelectedAttributeValue(selections, selectLimitIfFieldEqualsTo1[Rule.RULE_KEY_FIELD_KEY]).length > 0) { } else if (Utils.getSelectedAttributeValue(selections!, selectLimitIfFieldEqualsTo1[Rule.RULE_KEY_FIELD_KEY]).length > 0) {
if (selectLimitIfFieldEqualsTo1.containsKey(Utils.getSelectedAttributeValue(selections, selectLimitIfFieldEqualsTo1[Rule.RULE_KEY_FIELD_KEY])[0])) { if (selectLimitIfFieldEqualsTo1.containsKey(Utils.getSelectedAttributeValue(selections!, selectLimitIfFieldEqualsTo1[Rule.RULE_KEY_FIELD_KEY])[0])) {
int limitQty = selectLimitIfFieldEqualsTo1[Utils.getSelectedAttributeValue(selections, selectLimitIfFieldEqualsTo1[Rule.RULE_KEY_FIELD_KEY])[0]]; int limitQty = selectLimitIfFieldEqualsTo1[Utils.getSelectedAttributeValue(selections!, selectLimitIfFieldEqualsTo1[Rule.RULE_KEY_FIELD_KEY])[0]];
thisLimitQty = limitQty; thisLimitQty = limitQty;
if ((selections[product.productAttributes[index].name if ((selections![product!.productAttributes![index!].name
.toUpperCase()] as List).length >= limitQty) { .toUpperCase()] as List).length >= limitQty) {
disableOptionIfNotSelected(); disableOptionIfNotSelected();
} }
@@ -168,15 +168,15 @@ class CheckOptionsState extends OptionsBaseState<CheckOptions> {
int limitQty = selectLimitIfFieldEqualsTo[Rule int limitQty = selectLimitIfFieldEqualsTo[Rule
.RULE_KEY_FORCE_LIMITED]; .RULE_KEY_FORCE_LIMITED];
thisLimitQty = limitQty; thisLimitQty = limitQty;
if ((selections[product.productAttributes[index].name if ((selections![product!.productAttributes![index!].name
.toUpperCase()] as List).length >= limitQty) { .toUpperCase()] as List).length >= limitQty) {
disableOptionIfNotSelected(); disableOptionIfNotSelected();
} }
} else if (Utils.getSelectedAttributeValue(selections, selectLimitIfFieldEqualsTo[Rule.RULE_KEY_FIELD_KEY]).length > 0) { } else if (Utils.getSelectedAttributeValue(selections!, selectLimitIfFieldEqualsTo[Rule.RULE_KEY_FIELD_KEY]).length > 0) {
if (selectLimitIfFieldEqualsTo.containsKey(Utils.getSelectedAttributeValue(selections, selectLimitIfFieldEqualsTo[Rule.RULE_KEY_FIELD_KEY])[0])) { if (selectLimitIfFieldEqualsTo.containsKey(Utils.getSelectedAttributeValue(selections!, selectLimitIfFieldEqualsTo[Rule.RULE_KEY_FIELD_KEY])[0])) {
int limitQty = selectLimitIfFieldEqualsTo[Utils.getSelectedAttributeValue(selections, selectLimitIfFieldEqualsTo[Rule.RULE_KEY_FIELD_KEY])[0]]; int limitQty = selectLimitIfFieldEqualsTo[Utils.getSelectedAttributeValue(selections!, selectLimitIfFieldEqualsTo[Rule.RULE_KEY_FIELD_KEY])[0]];
thisLimitQty = limitQty; thisLimitQty = limitQty;
if ((selections[product.productAttributes[index].name if ((selections![product!.productAttributes![index!].name
.toUpperCase()] as List).length >= limitQty) { .toUpperCase()] as List).length >= limitQty) {
disableOptionIfNotSelected(); disableOptionIfNotSelected();
} }
@@ -187,7 +187,7 @@ class CheckOptionsState extends OptionsBaseState<CheckOptions> {
} }
for (var i = 0; i < productOptions.length; i++) { for (var i = 0; i < productOptions.length; i++) {
Map<String, dynamic> extraJson = Utils.stringToJson( Map<String, dynamic>? extraJson = Utils.stringToJson(
productOptions[i].extra); productOptions[i].extra);
if (extraJson != null) { if (extraJson != null) {
Map<String, dynamic> exclusiveRule = Rule.getRule( Map<String, dynamic> exclusiveRule = Rule.getRule(
@@ -195,12 +195,12 @@ class CheckOptionsState extends OptionsBaseState<CheckOptions> {
Map<String, dynamic> multiItemRule = Rule.getRule(extraJson, Rule.RULE_ACTUAL_QTY_IS); Map<String, dynamic> multiItemRule = Rule.getRule(extraJson, Rule.RULE_ACTUAL_QTY_IS);
if (exclusiveRule != null) { if (exclusiveRule != null) {
if (thisLimitQty > 0 && !_checkOptionIsCheck(productOptions[i].name)) { if (thisLimitQty > 0 && !_checkOptionIsCheck(productOptions[i].name)) {
optionsState[product.productAttributes[index].name][i]['disabled'] = true; optionsState[product!.productAttributes![index!].name][i]['disabled'] = true;
} else { } else {
if (_checkOptionIsCheck(productOptions[i].name)) { if (_checkOptionIsCheck(productOptions[i].name)) {
setOptionsStateDisabled( setOptionsStateDisabled(
product.productAttributes[index].name, true); product!.productAttributes![index!].name, true);
optionsState[product.productAttributes[index] optionsState[product!.productAttributes![index!]
.name][i]['disabled'] = false; .name][i]['disabled'] = false;
break; break;
} }
@@ -208,12 +208,12 @@ class CheckOptionsState extends OptionsBaseState<CheckOptions> {
} }
if (multiItemRule != null) { if (multiItemRule != null) {
if (_checkOptionIsCheck(productOptions[i].name)) { if (_checkOptionIsCheck(productOptions[i].name)) {
if (multiItemRule[Rule.RULE_ACTUAL_QTY_IS] > thisLimitQty - (selections[product.productAttributes[index].name.toUpperCase()] as List).length) { if (multiItemRule[Rule.RULE_ACTUAL_QTY_IS] > thisLimitQty - (selections![product!.productAttributes![index!].name.toUpperCase()] as List).length) {
disableOptionIfNotSelected(); disableOptionIfNotSelected();
} }
} else { } else {
if (multiItemRule[Rule.RULE_ACTUAL_QTY_IS] > thisLimitQty - (selections[product.productAttributes[index].name.toUpperCase()] as List).length) { if (multiItemRule[Rule.RULE_ACTUAL_QTY_IS] > thisLimitQty - (selections![product!.productAttributes![index!].name.toUpperCase()] as List).length) {
optionsState[product.productAttributes[index] optionsState[product!.productAttributes![index!]
.name][i]['disabled'] = true; .name][i]['disabled'] = true;
} }
} }
@@ -222,26 +222,26 @@ class CheckOptionsState extends OptionsBaseState<CheckOptions> {
} }
} }
List<Map<String, dynamic>> optionState = optionsState[product.productAttributes[index].name]; List<Map<String, dynamic>> optionState = optionsState[product!.productAttributes![index!].name];
for (var i = 0; i < optionState.length; i++) { for (var i = 0; i < optionState.length; i++) {
Widget optionWidget = _getOptionCheck( Widget optionWidget = _getOptionCheck(
product.productAttributes[index].productOptions[i], optionState[i]['disabled'], i); product!.productAttributes![index!].productOptions[i], optionState[i]['disabled'], i);
row.children.add(optionWidget); row.children.add(optionWidget);
} }
return row; return row;
} }
void disableOptionIfNotSelected() { void disableOptionIfNotSelected() {
setOptionsStateDisabled(product.productAttributes[index].name, true); setOptionsStateDisabled(product!.productAttributes![index!].name, true);
for (var i = 0; i < optionsState[product.productAttributes[index].name].length; i++) { for (var i = 0; i < optionsState[product!.productAttributes![index!].name].length; i++) {
if (Utils.selectionsContains(selections, product.productAttributes[index].name, optionsState[product.productAttributes[index].name][i]['name']) != -1) { if (Utils.selectionsContains(selections!, product!.productAttributes![index!].name, optionsState[product!.productAttributes![index!].name][i]['name']) != -1) {
optionsState[product.productAttributes[index].name][i]['disabled'] = false; optionsState[product!.productAttributes![index!].name][i]['disabled'] = false;
} }
} }
} }
bool _checkOptionIsCheck(String name) { bool _checkOptionIsCheck(String name) {
if (Utils.selectionsContains(selections, product.productAttributes[index].name, name) != -1) { if (Utils.selectionsContains(selections!, product!.productAttributes![index!].name, name) != -1) {
return true; return true;
} }
return false; return false;
@@ -251,7 +251,7 @@ class CheckOptionsState extends OptionsBaseState<CheckOptions> {
bool disabled = optDisabled; bool disabled = optDisabled;
bool check = _checkOptionIsCheck(productOption.name); bool check = _checkOptionIsCheck(productOption.name);
Map<String, dynamic> extraJson = Utils.stringToJson(productOption.extra); Map<String, dynamic>? extraJson = Utils.stringToJson(productOption.extra);
// Utils.jsonPrettyPrint(extraJson); // Utils.jsonPrettyPrint(extraJson);
double extraAdjustAmount = 0.0; double extraAdjustAmount = 0.0;
@@ -262,13 +262,13 @@ class CheckOptionsState extends OptionsBaseState<CheckOptions> {
if (sizeBaseAdjustment is List) { if (sizeBaseAdjustment is List) {
for (var i = 0; i < (sizeBaseAdjustment as List).length; i++) { for (var i = 0; i < (sizeBaseAdjustment as List).length; i++) {
Map<String, dynamic> sizeBaseAdjustment1 = sizeBaseAdjustment[i]; Map<String, dynamic> sizeBaseAdjustment1 = sizeBaseAdjustment[i];
List<String> attValues = Utils.getSelectedAttributeValue(selections, sizeBaseAdjustment1[Rule.RULE_KEY_FIELD_KEY]); List<String> attValues = Utils.getSelectedAttributeValue(selections!, sizeBaseAdjustment1[Rule.RULE_KEY_FIELD_KEY]);
if (attValues.length > 0 && sizeBaseAdjustment1.containsKey(attValues[0])) { if (attValues.length > 0 && sizeBaseAdjustment1.containsKey(attValues[0])) {
extraAdjustAmount += sizeBaseAdjustment1[attValues[0]]; extraAdjustAmount += sizeBaseAdjustment1[attValues[0]];
} }
} }
} else { } else {
List<String> attValues = Utils.getSelectedAttributeValue(selections, sizeBaseAdjustment[Rule.RULE_KEY_FIELD_KEY]); List<String> attValues = Utils.getSelectedAttributeValue(selections!, sizeBaseAdjustment[Rule.RULE_KEY_FIELD_KEY]);
if (attValues.length > 0 && sizeBaseAdjustment.containsKey(attValues[0])) { if (attValues.length > 0 && sizeBaseAdjustment.containsKey(attValues[0])) {
extraAdjustAmount += sizeBaseAdjustment[attValues[0]]; extraAdjustAmount += sizeBaseAdjustment[attValues[0]];
} }
@@ -282,7 +282,7 @@ class CheckOptionsState extends OptionsBaseState<CheckOptions> {
for (var i = 0; i < (disabledRule as List).length; i++) { for (var i = 0; i < (disabledRule as List).length; i++) {
Map<String, dynamic> disabledRule1 = disabledRule[i]; Map<String, dynamic> disabledRule1 = disabledRule[i];
List<String> attValues = Utils.getSelectedAttributeValue( List<String> attValues = Utils.getSelectedAttributeValue(
selections, disabledRule1[Rule.RULE_KEY_FIELD_KEY]); selections!, disabledRule1[Rule.RULE_KEY_FIELD_KEY]);
if (attValues.length > 0 && if (attValues.length > 0 &&
disabledRule1.containsKey(attValues[0])) { disabledRule1.containsKey(attValues[0])) {
disabled = true; disabled = true;
@@ -301,7 +301,7 @@ class CheckOptionsState extends OptionsBaseState<CheckOptions> {
} }
} else { } else {
List<String> attValues = Utils.getSelectedAttributeValue( List<String> attValues = Utils.getSelectedAttributeValue(
selections, disabledRule[Rule.RULE_KEY_FIELD_KEY]); selections!, disabledRule[Rule.RULE_KEY_FIELD_KEY]);
if (attValues.length > 0) { if (attValues.length > 0) {
for (String s in attValues) { for (String s in attValues) {
if (disabledRule.containsKey(s) && disabledRule[s]) { if (disabledRule.containsKey(s) && disabledRule[s]) {

View File

@@ -1,7 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_wisetronic/models/product.dart'; import '../../../models/product.dart';
typedef void OnOptionTapped(String name, int quantity, double adjustAmount); typedef void OnOptionTapped(String name, int quantity, double adjustAmount);
@@ -9,16 +9,16 @@ abstract class OptionsBase extends StatefulWidget {
final Product product; final Product product;
final int index; final int index;
final Map<String, dynamic> selections; final Map<String, dynamic> selections;
OptionsBase({@required Product product, @required int index, @required Map<String, dynamic> selections}) OptionsBase({required Product product, required int index, required Map<String, dynamic> selections})
: product = product, : product = product,
index = index, index = index,
selections = selections; selections = selections;
} }
abstract class OptionsBaseState<Base extends OptionsBase> extends State<Base> { abstract class OptionsBaseState<Base extends OptionsBase> extends State<Base> {
Product product; Product? product;
Map<String, dynamic> selections; Map<String, dynamic>? selections;
int index; int? index;
final Color disabledBackgroundColor = new Color(0xFFBCBCBC); final Color disabledBackgroundColor = new Color(0xFFBCBCBC);

View File

@@ -14,7 +14,7 @@ import 'options_base.dart';
import 'rules.dart'; import 'rules.dart';
class QtyOptions extends OptionsBase { class QtyOptions extends OptionsBase {
QtyOptions({@required Product product, @required int index, @required Map<String, dynamic> selections}) QtyOptions({required Product product, required int index, required Map<String, dynamic> selections})
: super(product: product, index: index, selections: selections); : super(product: product, index: index, selections: selections);
@override @override
@@ -41,14 +41,14 @@ class QtyOptionsState extends OptionsBaseState<QtyOptions> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[ children: <Widget>[
new Text( new Text(
S.of(context).check_option_select_token(product.productAttributes[this.index].name), S.of(context).check_option_select_token(product!.productAttributes![this.index!].name),
style: new TextStyle( style: new TextStyle(
fontSize: 12.5, fontSize: 12.5,
), ),
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
new Text( new Text(
product.productAttributes[this.index].required ? S.of(context).check_option_is_required : S.of(context).check_option_is_optional, product!.productAttributes![this.index!].required ? S.of(context).check_option_is_required : S.of(context).check_option_is_optional,
style: new TextStyle( style: new TextStyle(
fontSize: 10.0, fontSize: 10.0,
color: new Color(0xFF999999) color: new Color(0xFF999999)
@@ -86,38 +86,38 @@ class QtyOptionsState extends OptionsBaseState<QtyOptions> {
'adjust_amount': adjustAmount 'adjust_amount': adjustAmount
}; };
var cloneSelections = json.decode(json.encode(selections)); var cloneSelections = json.decode(json.encode(selections));
int idx = Utils.selectionsContains(cloneSelections, product.productAttributes[index].name, name); int idx = Utils.selectionsContains(cloneSelections, product!.productAttributes![index!].name, name);
if (idx != -1) { if (idx != -1) {
if (quantity == 1) { if (quantity == 1) {
cloneSelections[product.productAttributes[index].name.toUpperCase()][idx]['quantity'] += 1; cloneSelections[product!.productAttributes![index!].name.toUpperCase()][idx]['quantity'] += 1;
optionsState[product.productAttributes[index].name][optIndex]['quantity'] = cloneSelections[product.productAttributes[index].name.toUpperCase()][idx]['quantity']; optionsState[product!.productAttributes![index!].name][optIndex]['quantity'] = cloneSelections[product!.productAttributes![index!].name.toUpperCase()][idx]['quantity'];
} else { } else {
if (cloneSelections[product.productAttributes[index].name.toUpperCase()][idx]['quantity'] - 1 > 0) { if (cloneSelections[product!.productAttributes![index!].name.toUpperCase()][idx]['quantity'] - 1 > 0) {
cloneSelections[product.productAttributes[index].name.toUpperCase()][idx]['quantity'] -= 1; cloneSelections[product!.productAttributes![index!].name.toUpperCase()][idx]['quantity'] -= 1;
optionsState[product.productAttributes[index].name][optIndex]['quantity'] = cloneSelections[product.productAttributes[index].name.toUpperCase()][idx]['quantity']; optionsState[product!.productAttributes![index!].name][optIndex]['quantity'] = cloneSelections[product!.productAttributes![index!].name.toUpperCase()][idx]['quantity'];
} else { } else {
(cloneSelections[product.productAttributes[index].name.toUpperCase()] as List).removeAt(idx); (cloneSelections[product!.productAttributes![index!].name.toUpperCase()] as List).removeAt(idx);
optionsState[product.productAttributes[index].name][optIndex]['quantity'] = 0; optionsState[product!.productAttributes![index!].name][optIndex]['quantity'] = 0;
} }
} }
} else if (cloneSelections.containsKey(product.productAttributes[index].name.toUpperCase())) { } else if (cloneSelections.containsKey(product!.productAttributes![index!].name.toUpperCase())) {
(cloneSelections[product.productAttributes[index].name.toUpperCase()] as List).add(opt); (cloneSelections[product!.productAttributes![index!].name.toUpperCase()] as List).add(opt);
optionsState[product.productAttributes[index].name][optIndex]['quantity'] = 1; optionsState[product!.productAttributes![index!].name][optIndex]['quantity'] = 1;
} else { } else {
cloneSelections[product.productAttributes[index].name.toUpperCase()] = [opt]; cloneSelections[product!.productAttributes![index!].name.toUpperCase()] = [opt];
optionsState[product.productAttributes[index].name][optIndex]['quantity'] = 1; optionsState[product!.productAttributes![index!].name][optIndex]['quantity'] = 1;
} }
if (idx != -1 && (cloneSelections[product.productAttributes[index].name.toUpperCase()] as List).length == 0) { if (idx != -1 && (cloneSelections[product!.productAttributes![index!].name.toUpperCase()] as List).length == 0) {
cloneSelections.remove(product.productAttributes[index].name.toUpperCase()); cloneSelections.remove(product!.productAttributes![index!].name.toUpperCase());
} }
setOptionsStateDisabled(product.productAttributes[index].name, false); setOptionsStateDisabled(product!.productAttributes![index!].name, false);
setState(() { setState(() {
selections = cloneSelections; selections = cloneSelections;
}); });
eventBus.fire(new OnAttributeSelectionsChanged(selections)); eventBus.fire(new OnAttributeSelectionsChanged(selections!));
} }
Widget _getOptionWidget() { Widget _getOptionWidget() {
@@ -125,24 +125,24 @@ class QtyOptionsState extends OptionsBaseState<QtyOptions> {
children: <Widget>[], children: <Widget>[],
); );
List<ProductOption> productOptions = product.productAttributes[index].productOptions; List<ProductOption> productOptions = product!.productAttributes![index!].productOptions;
if (!optionsState.containsKey(product.productAttributes[index].name)) { if (!optionsState.containsKey(product!.productAttributes![index!].name)) {
List<Map<String, dynamic>> optionState = []; List<Map<String, dynamic>> optionState = [];
for (var i = 0; i < productOptions.length; i++) { for (var i = 0; i < productOptions.length; i++) {
int qty = 0; int qty = 0;
int idx = Utils.selectionsContains(selections, product.productAttributes[index].name, productOptions[i].name); int idx = Utils.selectionsContains(selections!, product!.productAttributes![index!].name, productOptions[i].name);
if (idx != -1) { if (idx != -1) {
qty = selections[product.productAttributes[index].name.toUpperCase()][idx]['quantity']; qty = selections![product!.productAttributes![index!].name.toUpperCase()][idx]['quantity'];
} }
optionState.add({'name': product.productAttributes[index].productOptions[i].name, 'disabled': false, 'quantity': qty, 'check': false}); optionState.add({'name': product!.productAttributes![index!].productOptions[i].name, 'disabled': false, 'quantity': qty, 'check': false});
} }
optionsState[product.productAttributes[index].name] = optionState; optionsState[product!.productAttributes![index!].name] = optionState;
} }
if (selections.containsKey(product.productAttributes[index].name.toUpperCase())) { if (selections!.containsKey(product!.productAttributes![index!].name.toUpperCase())) {
Map<String, dynamic> attrExtraJson = Utils.stringToJson( Map<String, dynamic>? attrExtraJson = Utils.stringToJson(
product.productAttributes[index].extra); product!.productAttributes![index!].extra);
if (attrExtraJson != null) { if (attrExtraJson != null) {
var selectLimitIfFieldEqualsTo = Rule.getRule( var selectLimitIfFieldEqualsTo = Rule.getRule(
attrExtraJson, Rule.RULE_SELECT_LIMIT_IF_FIELD_EQUALS_TO); attrExtraJson, Rule.RULE_SELECT_LIMIT_IF_FIELD_EQUALS_TO);
@@ -155,15 +155,15 @@ class QtyOptionsState extends OptionsBaseState<QtyOptions> {
int limitQty = selectLimitIfFieldEqualsTo1[Rule int limitQty = selectLimitIfFieldEqualsTo1[Rule
.RULE_KEY_FORCE_LIMITED]; .RULE_KEY_FORCE_LIMITED];
thisLimitQty = limitQty; thisLimitQty = limitQty;
if ((selections[product.productAttributes[index].name if ((selections![product!.productAttributes![index!].name
.toUpperCase()] as List).length >= limitQty) { .toUpperCase()] as List).length >= limitQty) {
disableOptionIfNotSelected(); disableOptionIfNotSelected();
} }
} else if (Utils.getSelectedAttributeValue(selections, selectLimitIfFieldEqualsTo1[Rule.RULE_KEY_FIELD_KEY]).length > 0) { } else if (Utils.getSelectedAttributeValue(selections!, selectLimitIfFieldEqualsTo1[Rule.RULE_KEY_FIELD_KEY]).length > 0) {
if (selectLimitIfFieldEqualsTo1.containsKey(Utils.getSelectedAttributeValue(selections, selectLimitIfFieldEqualsTo1[Rule.RULE_KEY_FIELD_KEY])[0])) { if (selectLimitIfFieldEqualsTo1.containsKey(Utils.getSelectedAttributeValue(selections!, selectLimitIfFieldEqualsTo1[Rule.RULE_KEY_FIELD_KEY])[0])) {
int limitQty = selectLimitIfFieldEqualsTo1[Utils.getSelectedAttributeValue(selections, selectLimitIfFieldEqualsTo1[Rule.RULE_KEY_FIELD_KEY])[0]]; int limitQty = selectLimitIfFieldEqualsTo1[Utils.getSelectedAttributeValue(selections!, selectLimitIfFieldEqualsTo1[Rule.RULE_KEY_FIELD_KEY])[0]];
thisLimitQty = limitQty; thisLimitQty = limitQty;
if ((selections[product.productAttributes[index].name if ((selections![product!.productAttributes![index!].name
.toUpperCase()] as List).length >= limitQty) { .toUpperCase()] as List).length >= limitQty) {
disableOptionIfNotSelected(); disableOptionIfNotSelected();
} }
@@ -176,15 +176,15 @@ class QtyOptionsState extends OptionsBaseState<QtyOptions> {
int limitQty = selectLimitIfFieldEqualsTo[Rule int limitQty = selectLimitIfFieldEqualsTo[Rule
.RULE_KEY_FORCE_LIMITED]; .RULE_KEY_FORCE_LIMITED];
thisLimitQty = limitQty; thisLimitQty = limitQty;
if ((selections[product.productAttributes[index].name if ((selections![product!.productAttributes![index!].name
.toUpperCase()] as List).length >= limitQty) { .toUpperCase()] as List).length >= limitQty) {
disableOptionIfNotSelected(); disableOptionIfNotSelected();
} }
} else if (Utils.getSelectedAttributeValue(selections, selectLimitIfFieldEqualsTo[Rule.RULE_KEY_FIELD_KEY]).length > 0) { } else if (Utils.getSelectedAttributeValue(selections!, selectLimitIfFieldEqualsTo[Rule.RULE_KEY_FIELD_KEY]).length > 0) {
if (selectLimitIfFieldEqualsTo.containsKey(Utils.getSelectedAttributeValue(selections, selectLimitIfFieldEqualsTo[Rule.RULE_KEY_FIELD_KEY])[0])) { if (selectLimitIfFieldEqualsTo.containsKey(Utils.getSelectedAttributeValue(selections!, selectLimitIfFieldEqualsTo[Rule.RULE_KEY_FIELD_KEY])[0])) {
int limitQty = selectLimitIfFieldEqualsTo[Utils.getSelectedAttributeValue(selections, selectLimitIfFieldEqualsTo[Rule.RULE_KEY_FIELD_KEY])[0]]; int limitQty = selectLimitIfFieldEqualsTo[Utils.getSelectedAttributeValue(selections!, selectLimitIfFieldEqualsTo[Rule.RULE_KEY_FIELD_KEY])[0]];
thisLimitQty = limitQty; thisLimitQty = limitQty;
if ((selections[product.productAttributes[index].name if ((selections![product!.productAttributes![index!].name
.toUpperCase()] as List).length >= limitQty) { .toUpperCase()] as List).length >= limitQty) {
disableOptionIfNotSelected(); disableOptionIfNotSelected();
} }
@@ -195,7 +195,7 @@ class QtyOptionsState extends OptionsBaseState<QtyOptions> {
} }
for (var i = 0; i < productOptions.length; i++) { for (var i = 0; i < productOptions.length; i++) {
Map<String, dynamic> extraJson = Utils.stringToJson( Map<String, dynamic>? extraJson = Utils.stringToJson(
productOptions[i].extra); productOptions[i].extra);
if (extraJson != null) { if (extraJson != null) {
Map<String, dynamic> exclusiveRule = Rule.getRule( Map<String, dynamic> exclusiveRule = Rule.getRule(
@@ -203,12 +203,12 @@ class QtyOptionsState extends OptionsBaseState<QtyOptions> {
Map<String, dynamic> multiItemRule = Rule.getRule(extraJson, Rule.RULE_ACTUAL_QTY_IS); Map<String, dynamic> multiItemRule = Rule.getRule(extraJson, Rule.RULE_ACTUAL_QTY_IS);
if (exclusiveRule != null) { if (exclusiveRule != null) {
if (thisLimitQty > 0 && !_checkOptionIsCheck(productOptions[i].name)) { if (thisLimitQty > 0 && !_checkOptionIsCheck(productOptions[i].name)) {
optionsState[product.productAttributes[index].name][i]['disabled'] = true; optionsState[product!.productAttributes![index!].name][i]['disabled'] = true;
} else { } else {
if (_checkOptionIsCheck(productOptions[i].name)) { if (_checkOptionIsCheck(productOptions[i].name)) {
setOptionsStateDisabled( setOptionsStateDisabled(
product.productAttributes[index].name, true); product!.productAttributes![index!].name, true);
optionsState[product.productAttributes[index] optionsState[product!.productAttributes![index!]
.name][i]['disabled'] = false; .name][i]['disabled'] = false;
break; break;
} }
@@ -216,12 +216,12 @@ class QtyOptionsState extends OptionsBaseState<QtyOptions> {
} }
if (multiItemRule != null) { if (multiItemRule != null) {
if (_checkOptionIsCheck(productOptions[i].name)) { if (_checkOptionIsCheck(productOptions[i].name)) {
if (multiItemRule[Rule.RULE_ACTUAL_QTY_IS] > thisLimitQty - (selections[product.productAttributes[index].name.toUpperCase()] as List).length) { if (multiItemRule[Rule.RULE_ACTUAL_QTY_IS] > thisLimitQty - (selections![product!.productAttributes![index!].name.toUpperCase()] as List).length) {
disableOptionIfNotSelected(); disableOptionIfNotSelected();
} }
} else { } else {
if (multiItemRule[Rule.RULE_ACTUAL_QTY_IS] > thisLimitQty - (selections[product.productAttributes[index].name.toUpperCase()] as List).length) { if (multiItemRule[Rule.RULE_ACTUAL_QTY_IS] > thisLimitQty - (selections![product!.productAttributes![index!].name.toUpperCase()] as List).length) {
optionsState[product.productAttributes[index] optionsState[product!.productAttributes![index!]
.name][i]['disabled'] = true; .name][i]['disabled'] = true;
} }
} }
@@ -230,26 +230,26 @@ class QtyOptionsState extends OptionsBaseState<QtyOptions> {
} }
} }
List<Map<String, dynamic>> optionState = optionsState[product.productAttributes[index].name]; List<Map<String, dynamic>> optionState = optionsState[product!.productAttributes![index!].name];
for (var i = 0; i < optionState.length; i++) { for (var i = 0; i < optionState.length; i++) {
Widget optionWidget = _getOptionQty( Widget optionWidget = _getOptionQty(
product.productAttributes[index].productOptions[i], optionState[i]['disabled'], optionState[i]['quantity'], i); product!.productAttributes![index!].productOptions[i], optionState[i]['disabled'], optionState[i]['quantity'], i);
row.children.add(optionWidget); row.children.add(optionWidget);
} }
return row; return row;
} }
void disableOptionIfNotSelected() { void disableOptionIfNotSelected() {
setOptionsStateDisabled(product.productAttributes[index].name, true); setOptionsStateDisabled(product!.productAttributes![index!].name, true);
for (var i = 0; i < optionsState[product.productAttributes[index].name].length; i++) { for (var i = 0; i < optionsState[product!.productAttributes![index!].name].length; i++) {
if (Utils.selectionsContains(selections, product.productAttributes[index].name, optionsState[product.productAttributes[index].name][i]['name']) != -1) { if (Utils.selectionsContains(selections!, product!.productAttributes![index!].name, optionsState[product!.productAttributes![index!].name][i]['name']) != -1) {
optionsState[product.productAttributes[index].name][i]['disabled'] = false; optionsState[product!.productAttributes![index!].name][i]['disabled'] = false;
} }
} }
} }
bool _checkOptionIsCheck(String name) { bool _checkOptionIsCheck(String name) {
if (Utils.selectionsContains(selections, product.productAttributes[index].name, name) != -1) { if (Utils.selectionsContains(selections!, product!.productAttributes![index!].name, name) != -1) {
return true; return true;
} }
return false; return false;
@@ -259,7 +259,7 @@ class QtyOptionsState extends OptionsBaseState<QtyOptions> {
bool disabled = optDisabled; bool disabled = optDisabled;
bool check = _checkOptionIsCheck(productOption.name); bool check = _checkOptionIsCheck(productOption.name);
Map<String, dynamic> extraJson = Utils.stringToJson(productOption.extra); Map<String, dynamic>? extraJson = Utils.stringToJson(productOption.extra);
// Utils.jsonPrettyPrint(extraJson); // Utils.jsonPrettyPrint(extraJson);
double extraAdjustAmount = 0.0; double extraAdjustAmount = 0.0;
@@ -270,13 +270,13 @@ class QtyOptionsState extends OptionsBaseState<QtyOptions> {
if (sizeBaseAdjustment is List) { if (sizeBaseAdjustment is List) {
for (var i = 0; i < (sizeBaseAdjustment as List).length; i++) { for (var i = 0; i < (sizeBaseAdjustment as List).length; i++) {
Map<String, dynamic> sizeBaseAdjustment1 = sizeBaseAdjustment[i]; Map<String, dynamic> sizeBaseAdjustment1 = sizeBaseAdjustment[i];
List<String> attValues = Utils.getSelectedAttributeValue(selections, sizeBaseAdjustment1[Rule.RULE_KEY_FIELD_KEY]); List<String> attValues = Utils.getSelectedAttributeValue(selections!, sizeBaseAdjustment1[Rule.RULE_KEY_FIELD_KEY]);
if (attValues.length > 0 && sizeBaseAdjustment1.containsKey(attValues[0])) { if (attValues.length > 0 && sizeBaseAdjustment1.containsKey(attValues[0])) {
extraAdjustAmount += sizeBaseAdjustment1[attValues[0]]; extraAdjustAmount += sizeBaseAdjustment1[attValues[0]];
} }
} }
} else { } else {
List<String> attValues = Utils.getSelectedAttributeValue(selections, sizeBaseAdjustment[Rule.RULE_KEY_FIELD_KEY]); List<String> attValues = Utils.getSelectedAttributeValue(selections!, sizeBaseAdjustment[Rule.RULE_KEY_FIELD_KEY]);
if (attValues.length > 0 && sizeBaseAdjustment.containsKey(attValues[0])) { if (attValues.length > 0 && sizeBaseAdjustment.containsKey(attValues[0])) {
extraAdjustAmount += sizeBaseAdjustment[attValues[0]]; extraAdjustAmount += sizeBaseAdjustment[attValues[0]];
} }
@@ -290,7 +290,7 @@ class QtyOptionsState extends OptionsBaseState<QtyOptions> {
for (var i = 0; i < (disabledRule as List).length; i++) { for (var i = 0; i < (disabledRule as List).length; i++) {
Map<String, dynamic> disabledRule1 = disabledRule[i]; Map<String, dynamic> disabledRule1 = disabledRule[i];
List<String> attValues = Utils.getSelectedAttributeValue( List<String> attValues = Utils.getSelectedAttributeValue(
selections, disabledRule1[Rule.RULE_KEY_FIELD_KEY]); selections!, disabledRule1[Rule.RULE_KEY_FIELD_KEY]);
if (attValues.length > 0 && if (attValues.length > 0 &&
disabledRule1.containsKey(attValues[0])) { disabledRule1.containsKey(attValues[0])) {
disabled = true; disabled = true;
@@ -309,7 +309,7 @@ class QtyOptionsState extends OptionsBaseState<QtyOptions> {
} }
} else { } else {
List<String> attValues = Utils.getSelectedAttributeValue( List<String> attValues = Utils.getSelectedAttributeValue(
selections, disabledRule[Rule.RULE_KEY_FIELD_KEY]); selections!, disabledRule[Rule.RULE_KEY_FIELD_KEY]);
if (attValues.length > 0) { if (attValues.length > 0) {
for (String s in attValues) { for (String s in attValues) {
if (disabledRule.containsKey(s) && disabledRule[s]) { if (disabledRule.containsKey(s) && disabledRule[s]) {

View File

@@ -14,7 +14,7 @@ import 'options_base.dart';
import 'rules.dart'; import 'rules.dart';
class RadioOptions extends OptionsBase { class RadioOptions extends OptionsBase {
RadioOptions({@required Product product, @required int index, @required Map<String, dynamic> selections}) RadioOptions({required Product product, required int index, required Map<String, dynamic> selections})
: super(product: product, index: index, selections: selections); : super(product: product, index: index, selections: selections);
@override @override
@@ -40,14 +40,14 @@ class RadioOptionsState extends OptionsBaseState<RadioOptions> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[ children: <Widget>[
new Text( new Text(
S.of(context).radio_option_select_token(product.productAttributes[this.index].name), S.of(context).radio_option_select_token(product!.productAttributes![this.index!].name),
style: new TextStyle( style: new TextStyle(
fontSize: 12.5, fontSize: 12.5,
), ),
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
new Text( new Text(
product.productAttributes[this.index].required ? S.of(context).radio_option_is_required : S.of(context).radio_option_is_optional, product!.productAttributes![this.index!].required ? S.of(context).radio_option_is_required : S.of(context).radio_option_is_optional,
style: new TextStyle( style: new TextStyle(
fontSize: 10.0, fontSize: 10.0,
color: new Color(0xFF999999) color: new Color(0xFF999999)
@@ -85,24 +85,24 @@ class RadioOptionsState extends OptionsBaseState<RadioOptions> {
'adjust_amount': adjustAmount 'adjust_amount': adjustAmount
}; };
var cloneSelections = json.decode(json.encode(selections)); var cloneSelections = json.decode(json.encode(selections));
if (product.productAttributes[index].required) { if (product!.productAttributes![index!].required) {
cloneSelections[product.productAttributes[index].name.toUpperCase()] = [opt]; cloneSelections[product!.productAttributes![index!].name.toUpperCase()] = [opt];
} else { } else {
if (cloneSelections.containsKey(product.productAttributes[index].name.toUpperCase()) if (cloneSelections.containsKey(product!.productAttributes![index!].name.toUpperCase())
&& Utils.equalsIgnoreCase(cloneSelections[product.productAttributes[index].name.toUpperCase()][0]['name'], name)) { && Utils.equalsIgnoreCase(cloneSelections[product!.productAttributes![index!].name.toUpperCase()][0]['name'], name)) {
cloneSelections.remove(product.productAttributes[index].name.toUpperCase()); cloneSelections.remove(product!.productAttributes![index!].name.toUpperCase());
} else { } else {
cloneSelections[product.productAttributes[index].name.toUpperCase()] = [opt]; cloneSelections[product!.productAttributes![index!].name.toUpperCase()] = [opt];
} }
} }
Map<String, dynamic> extraJson = Utils.stringToJson(productOption.extra); Map<String, dynamic>? extraJson = Utils.stringToJson(productOption.extra);
if (extraJson != null) { if (extraJson != null) {
Map<String, dynamic> exclusiveRule = Rule.getRule( Map<String, dynamic> exclusiveRule = Rule.getRule(
extraJson, Rule.RULE_EXCLUSIVE_SELECTION); extraJson, Rule.RULE_EXCLUSIVE_SELECTION);
if (exclusiveRule != null) { if (exclusiveRule != null) {
if (_checkOptionIsCheck(productOption.name)) { if (_checkOptionIsCheck(productOption.name)) {
setOptionsStateDisabled(product.productAttributes[index].name, false); setOptionsStateDisabled(product!.productAttributes![index!].name, false);
} }
} }
} }
@@ -110,7 +110,7 @@ class RadioOptionsState extends OptionsBaseState<RadioOptions> {
setState(() { setState(() {
selections = cloneSelections; selections = cloneSelections;
}); });
eventBus.fire(new OnAttributeSelectionsChanged(selections)); eventBus.fire(new OnAttributeSelectionsChanged(selections!));
} }
Widget _getOptionWidget() { Widget _getOptionWidget() {
@@ -118,42 +118,42 @@ class RadioOptionsState extends OptionsBaseState<RadioOptions> {
children: <Widget>[], children: <Widget>[],
); );
List<ProductOption> productOptions = product.productAttributes[index].productOptions; List<ProductOption> productOptions = product!.productAttributes![index!].productOptions;
if (!optionsState.containsKey(product.productAttributes[index].name)) { if (!optionsState.containsKey(product!.productAttributes![index!].name)) {
List<Map<String, dynamic>> optionState = []; List<Map<String, dynamic>> optionState = [];
for (var i = 0; i < productOptions.length; i++) { for (var i = 0; i < productOptions.length; i++) {
optionState.add({'name': product.productAttributes[index].productOptions[i].name, 'disabled': false, 'check': false}); optionState.add({'name': product!.productAttributes![index!].productOptions[i].name, 'disabled': false, 'check': false});
} }
optionsState[product.productAttributes[index].name] = optionState; optionsState[product!.productAttributes![index!].name] = optionState;
} }
for (var i = 0; i < productOptions.length; i++) { for (var i = 0; i < productOptions.length; i++) {
Map<String, dynamic> extraJson = Utils.stringToJson(productOptions[i].extra); Map<String, dynamic>? extraJson = Utils.stringToJson(productOptions[i].extra);
if (extraJson != null) { if (extraJson != null) {
Map<String, dynamic> exclusiveRule = Rule.getRule( Map<String, dynamic> exclusiveRule = Rule.getRule(
extraJson, Rule.RULE_EXCLUSIVE_SELECTION); extraJson, Rule.RULE_EXCLUSIVE_SELECTION);
if (exclusiveRule != null) { if (exclusiveRule != null) {
if (_checkOptionIsCheck(productOptions[i].name)) { if (_checkOptionIsCheck(productOptions[i].name)) {
setOptionsStateDisabled(product.productAttributes[index].name, true); setOptionsStateDisabled(product!.productAttributes![index!].name, true);
optionsState[product.productAttributes[index].name][i]['disabled'] = false; optionsState[product!.productAttributes![index!].name][i]['disabled'] = false;
break; break;
} }
} }
} }
} }
List<Map<String, dynamic>> optionState = optionsState[product.productAttributes[index].name]; List<Map<String, dynamic>> optionState = optionsState[product!.productAttributes![index!].name];
for (var i = 0; i < optionState.length; i++) { for (var i = 0; i < optionState.length; i++) {
Widget optionWidget = _getOptionRadio( Widget optionWidget = _getOptionRadio(
product.productAttributes[index].productOptions[i], optionState[i]['disabled'], i); product!.productAttributes![index!].productOptions[i], optionState[i]['disabled'], i);
row.children.add(optionWidget); row.children.add(optionWidget);
} }
return row; return row;
} }
bool _checkOptionIsCheck(String name) { bool _checkOptionIsCheck(String name) {
if (Utils.selectionsContains(selections, product.productAttributes[index].name, name) != -1) { if (Utils.selectionsContains(selections!, product!.productAttributes![index!].name, name) != -1) {
return true; return true;
} }
return false; return false;
@@ -163,7 +163,7 @@ class RadioOptionsState extends OptionsBaseState<RadioOptions> {
bool disabled = optDisabled; bool disabled = optDisabled;
bool check = _checkOptionIsCheck(productOption.name); bool check = _checkOptionIsCheck(productOption.name);
Map<String, dynamic> extraJson = Utils.stringToJson(productOption.extra); Map<String, dynamic>? extraJson = Utils.stringToJson(productOption.extra);
// Utils.jsonPrettyPrint(extraJson); // Utils.jsonPrettyPrint(extraJson);
double extraAdjustAmount = 0.0; double extraAdjustAmount = 0.0;
@@ -174,13 +174,13 @@ class RadioOptionsState extends OptionsBaseState<RadioOptions> {
if (sizeBaseAdjustment is List) { if (sizeBaseAdjustment is List) {
for (var i = 0; i < (sizeBaseAdjustment as List).length; i++) { for (var i = 0; i < (sizeBaseAdjustment as List).length; i++) {
Map<String, dynamic> sizeBaseAdjustment1 = sizeBaseAdjustment[i]; Map<String, dynamic> sizeBaseAdjustment1 = sizeBaseAdjustment[i];
List<String> attValues = Utils.getSelectedAttributeValue(selections, sizeBaseAdjustment1[Rule.RULE_KEY_FIELD_KEY]); List<String> attValues = Utils.getSelectedAttributeValue(selections!, sizeBaseAdjustment1[Rule.RULE_KEY_FIELD_KEY]);
if (attValues.length > 0 && sizeBaseAdjustment1.containsKey(attValues[0])) { if (attValues.length > 0 && sizeBaseAdjustment1.containsKey(attValues[0])) {
extraAdjustAmount += sizeBaseAdjustment1[attValues[0]]; extraAdjustAmount += sizeBaseAdjustment1[attValues[0]];
} }
} }
} else { } else {
List<String> attValues = Utils.getSelectedAttributeValue(selections, sizeBaseAdjustment[Rule.RULE_KEY_FIELD_KEY]); List<String> attValues = Utils.getSelectedAttributeValue(selections!, sizeBaseAdjustment[Rule.RULE_KEY_FIELD_KEY]);
if (attValues.length > 0 && sizeBaseAdjustment.containsKey(attValues[0])) { if (attValues.length > 0 && sizeBaseAdjustment.containsKey(attValues[0])) {
extraAdjustAmount += sizeBaseAdjustment[attValues[0]]; extraAdjustAmount += sizeBaseAdjustment[attValues[0]];
} }
@@ -194,7 +194,7 @@ class RadioOptionsState extends OptionsBaseState<RadioOptions> {
for (var i = 0; i < (disabledRule as List).length; i++) { for (var i = 0; i < (disabledRule as List).length; i++) {
Map<String, dynamic> disabledRule1 = disabledRule[i]; Map<String, dynamic> disabledRule1 = disabledRule[i];
List<String> attValues = Utils.getSelectedAttributeValue( List<String> attValues = Utils.getSelectedAttributeValue(
selections, disabledRule1[Rule.RULE_KEY_FIELD_KEY]); selections!, disabledRule1[Rule.RULE_KEY_FIELD_KEY]);
if (attValues.length > 0 && if (attValues.length > 0 &&
disabledRule1.containsKey(attValues[0])) { disabledRule1.containsKey(attValues[0])) {
disabled = true; disabled = true;
@@ -213,7 +213,7 @@ class RadioOptionsState extends OptionsBaseState<RadioOptions> {
} }
} else { } else {
List<String> attValues = Utils.getSelectedAttributeValue( List<String> attValues = Utils.getSelectedAttributeValue(
selections, disabledRule[Rule.RULE_KEY_FIELD_KEY]); selections!, disabledRule[Rule.RULE_KEY_FIELD_KEY]);
if (attValues.length > 0) { if (attValues.length > 0) {
for (String s in attValues) { for (String s in attValues) {
if (disabledRule.containsKey(s) && disabledRule[s]) { if (disabledRule.containsKey(s) && disabledRule[s]) {

View File

@@ -2,7 +2,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
class BottomNav extends StatefulWidget { class BottomNav extends StatefulWidget {
const BottomNav({Key key}) : super(key: key); const BottomNav({Key? key}) : super(key: key);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {

View File

@@ -7,10 +7,10 @@ import '../../routes.dart';
import 'navigationbar.dart'; import 'navigationbar.dart';
class BreadCrumbs extends StatelessWidget { class BreadCrumbs extends StatelessWidget {
final List<BreadCrumb> breadCrumbs; final List<BreadCrumb>? breadCrumbs;
final bool hasBack; final bool hasBack;
final OnBackPress onBackPress; final OnBackPress? onBackPress;
const BreadCrumbs(this.hasBack, {this.breadCrumbs, Key key, this.onBackPress}) : super(key: key); const BreadCrumbs(this.hasBack, {this.breadCrumbs, Key? key, this.onBackPress}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -49,17 +49,17 @@ class BreadCrumbs extends StatelessWidget {
)); ));
} }
if (breadCrumbs != null) { if (breadCrumbs != null) {
for (int i = 0; i < breadCrumbs.length; i++) { for (int i = 0; i < breadCrumbs!.length; i++) {
BreadCrumb breadCrumb = breadCrumbs[i]; BreadCrumb breadCrumb = breadCrumbs![i];
if (breadCrumb.text == null && breadCrumb.item != null) { if (breadCrumb.text == null && breadCrumb.item != null) {
if (breadCrumb.onTap == null) { if (breadCrumb.onTap == null) {
widgets.add(breadCrumb.item); widgets.add(breadCrumb.item!);
} else { } else {
widgets.add(MouseRegion( widgets.add(MouseRegion(
cursor: SystemMouseCursors.click, cursor: SystemMouseCursors.click,
child: GestureDetector( child: GestureDetector(
child: breadCrumb.item, child: breadCrumb.item!,
onTap: breadCrumb.onTap, onTap: breadCrumb.onTap as GestureTapCallback?,
), ),
)); ));
} }
@@ -94,7 +94,7 @@ class BreadCrumbs extends StatelessWidget {
color: Colors.blueAccent, color: Colors.blueAccent,
), ),
Text( Text(
breadCrumb.text, breadCrumb.text ?? '',
style: TextStyle( style: TextStyle(
color: Colors.blueAccent, color: Colors.blueAccent,
fontSize: 14.0, fontSize: 14.0,
@@ -103,7 +103,7 @@ class BreadCrumbs extends StatelessWidget {
], ],
) : ) :
Text( Text(
breadCrumb.text, breadCrumb.text ?? '',
style: TextStyle( style: TextStyle(
color: Colors.blueAccent, color: Colors.blueAccent,
fontSize: 14.0, fontSize: 14.0,
@@ -113,7 +113,7 @@ class BreadCrumbs extends StatelessWidget {
], ],
), ),
onTap: () { onTap: () {
Routes.router.navigateTo(context, breadCrumb.route); Routes.router.navigateTo(context, breadCrumb.route ?? '');
}, },
), ),
), ),
@@ -145,7 +145,7 @@ class BreadCrumbs extends StatelessWidget {
color: Colors.lightBlueAccent, color: Colors.lightBlueAccent,
), ),
Text( Text(
breadCrumb.text, breadCrumb.text ?? '',
style: TextStyle( style: TextStyle(
color: Colors.black54, color: Colors.black54,
fontSize: 14.0, fontSize: 14.0,
@@ -155,7 +155,7 @@ class BreadCrumbs extends StatelessWidget {
], ],
) : ) :
Text( Text(
breadCrumb.text, breadCrumb.text ?? '',
style: TextStyle( style: TextStyle(
color: Colors.black54, color: Colors.black54,
fontSize: 14.0, fontSize: 14.0,
@@ -184,11 +184,11 @@ class BreadCrumbs extends StatelessWidget {
} }
class BreadCrumb { class BreadCrumb {
final String text; final String? text;
final String route; final String? route;
final IconData icon; final IconData? icon;
final Widget item; final Widget? item;
final Function onTap; final Function? onTap;
BreadCrumb(this.text, this.route, {this.icon, this.item, this.onTap}); BreadCrumb(this.text, this.route, {this.icon, this.item, this.onTap});
} }

View File

@@ -6,8 +6,8 @@ import 'style.dart';
class Carousel extends StatefulWidget { class Carousel extends StatefulWidget {
Carousel({ Carousel({
double height = 200.0, double height = 200.0,
List<Widget> pages, List<Widget>? pages,
bool autoPlay, bool autoPlay = false,
Duration duration = const Duration(seconds: 2), Duration duration = const Duration(seconds: 2),
Duration animationDuration = const Duration(milliseconds: 1000), Duration animationDuration = const Duration(milliseconds: 1000),
}) })
@@ -17,11 +17,11 @@ class Carousel extends StatefulWidget {
duration = duration, duration = duration,
animationDuration = animationDuration; animationDuration = animationDuration;
final double height; final double? height;
final List<Widget> pages; final List<Widget>? pages;
final bool autoPlay; final bool? autoPlay;
final Duration duration; final Duration? duration;
final Duration animationDuration; final Duration? animationDuration;
@override @override
createState() => new CarouselState(); createState() => new CarouselState();
@@ -30,7 +30,7 @@ class Carousel extends StatefulWidget {
class CarouselState extends State<Carousel> { class CarouselState extends State<Carousel> {
final _pageController = new PageController(); final _pageController = new PageController();
Timer _timer; Timer? _timer;
int _currentPage = 0; int _currentPage = 0;
bool reverse = false; bool reverse = false;
GlobalKey<IndicatorState> _indicatorStateKey = new GlobalKey(); GlobalKey<IndicatorState> _indicatorStateKey = new GlobalKey();
@@ -38,13 +38,13 @@ class CarouselState extends State<Carousel> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
if (widget.autoPlay) { if (widget.autoPlay!) {
_timer = new Timer.periodic(widget.duration, (timer) { _timer = new Timer.periodic(widget.duration!, (timer) {
_pageController.animateToPage(_currentPage, _pageController.animateToPage(_currentPage,
duration: widget.animationDuration, curve: Curves.linear); duration: widget.animationDuration!, curve: Curves.linear);
if (!reverse) { if (!reverse) {
_currentPage += 1; _currentPage += 1;
if (_currentPage == widget.pages.length) { if (_currentPage == widget.pages?.length) {
_currentPage -= 1; _currentPage -= 1;
reverse = true; reverse = true;
} }
@@ -61,9 +61,9 @@ class CarouselState extends State<Carousel> {
@override @override
void dispose() { void dispose() {
_pageController?.dispose(); _pageController.dispose();
if (_timer != null) { if (_timer != null) {
_timer.cancel(); _timer!.cancel();
} }
super.dispose(); super.dispose();
} }
@@ -77,10 +77,10 @@ class CarouselState extends State<Carousel> {
color: Style.backgroundColor, color: Style.backgroundColor,
child: new PageView( child: new PageView(
controller: _pageController, controller: _pageController,
children: widget.pages, children: widget.pages!,
onPageChanged: (index) { onPageChanged: (index) {
_currentPage = index; _currentPage = index;
_indicatorStateKey.currentState.changeIndex(index); _indicatorStateKey.currentState?.changeIndex(index);
}, },
), ),
), ),
@@ -91,7 +91,7 @@ class CarouselState extends State<Carousel> {
child: new Align( child: new Align(
child: new Indicator( child: new Indicator(
key: _indicatorStateKey, key: _indicatorStateKey,
count: widget.pages.length, count: widget.pages!.length,
), ),
alignment: Alignment.center, alignment: Alignment.center,
), ),
@@ -102,11 +102,11 @@ class CarouselState extends State<Carousel> {
} }
class Indicator extends StatefulWidget { class Indicator extends StatefulWidget {
Indicator({Key key, int count}) Indicator({Key? key, int? count})
: count = count, : count = count,
super(key: key); super(key: key);
final int count; final int? count;
@override @override
createState() => new IndicatorState(); createState() => new IndicatorState();
@@ -124,7 +124,7 @@ class IndicatorState extends State<Indicator> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
var indicators = <Widget>[]; var indicators = <Widget>[];
for (var i = 0; i < widget.count; ++i) { for (var i = 0; i < widget.count!; ++i) {
indicators.add(new Container( indicators.add(new Container(
width: 5.0, width: 5.0,
height: 5.0, height: 5.0,
@@ -135,7 +135,7 @@ class IndicatorState extends State<Indicator> {
)); ));
} }
return new SizedBox( return new SizedBox(
width: widget.count * 15.0, width: widget.count! * 15.0,
height: 30.0, height: 30.0,
child: new Row( child: new Row(
children: indicators, children: indicators,

View File

@@ -4,9 +4,9 @@ import '../../generated/l10n.dart';
import '../../utils/double_back_to_close_app.dart'; import '../../utils/double_back_to_close_app.dart';
class DoubleBackToCloseAppWrapper extends StatelessWidget { class DoubleBackToCloseAppWrapper extends StatelessWidget {
final Widget child; final Widget? child;
const DoubleBackToCloseAppWrapper({Key key, this.child}) : super(key: key); const DoubleBackToCloseAppWrapper({Key? key, this.child}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -20,7 +20,7 @@ class DoubleBackToCloseAppWrapper extends StatelessWidget {
), ),
), ),
), ),
child: child, child: child!,
); );
} }
} }

View File

@@ -12,8 +12,8 @@ import '../../utils/utils.dart';
class DownloadItem extends StatefulWidget { class DownloadItem extends StatefulWidget {
final dynamic desc; final dynamic desc;
final double width; final double? width;
const DownloadItem(this.desc, {Key key, this.width}) : super(key: key); const DownloadItem(this.desc, {Key? key, this.width}) : super(key: key);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
@@ -52,7 +52,7 @@ class DownloadItemState extends State<DownloadItem> {
margin: EdgeInsets.only(right: 16.0), margin: EdgeInsets.only(right: 16.0),
), ),
Container( Container(
width: widget.width != null ? widget.width - iconWidth - buttonWidth - 60 : MediaQuery.of(context).size.width - iconWidth - buttonWidth - 60, width: widget.width != null ? widget.width! - iconWidth - buttonWidth - 60 : MediaQuery.of(context).size.width - iconWidth - buttonWidth - 60,
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -186,9 +186,9 @@ class DownloadItemState extends State<DownloadItem> {
} }
Widget getDownloadButton() { Widget getDownloadButton() {
String downloadUrl; String? downloadUrl;
String os = Utils.getOs(); String? os = Utils.getOs();
String selectedOs; String? selectedOs;
List<String> supportedOss = []; List<String> supportedOss = [];
for (int i = 0; i < (widget.desc['urls'] as List).length; i++) { for (int i = 0; i < (widget.desc['urls'] as List).length; i++) {
supportedOss.add((widget.desc['urls'] as List)[i]['os']); supportedOss.add((widget.desc['urls'] as List)[i]['os']);
@@ -244,7 +244,7 @@ class DownloadItemState extends State<DownloadItem> {
} else if (downloadUrl != null && downloadUrl.isNotEmpty) { } else if (downloadUrl != null && downloadUrl.isNotEmpty) {
return ElevatedButton( return ElevatedButton(
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
primary: Theme.of(context).primaryColor, backgroundColor: Theme.of(context).primaryColor,
padding: EdgeInsets.all(8) padding: EdgeInsets.all(8)
), ),
child: Row( child: Row(
@@ -255,7 +255,7 @@ class DownloadItemState extends State<DownloadItem> {
padding: EdgeInsets.only(right: 0.0, left: 6.0, top: 6.0, bottom: 6.0), padding: EdgeInsets.only(right: 0.0, left: 6.0, top: 6.0, bottom: 6.0),
child: Icon( child: Icon(
IconData( IconData(
Utils.getOsFontHex(selectedOs), Utils.getOsFontHex(selectedOs!),
fontFamily: 'wisetronic', fontFamily: 'wisetronic',
fontPackage: null fontPackage: null
), ),

View File

@@ -7,14 +7,14 @@ import 'package:responsive_builder/responsive_builder.dart';
class IndexCarousel extends StatelessWidget { class IndexCarousel extends StatelessWidget {
final List<Gallery> galleries; final List<Gallery> galleries;
const IndexCarousel(this.galleries, {Key key}) : super(key: key); const IndexCarousel(this.galleries, {Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ScreenTypeLayout( return ScreenTypeLayout.builder(
mobile: MobileIndexCarousel(galleries), mobile: (context) => MobileIndexCarousel(galleries),
tablet: DesktopIndexCarousel(galleries), tablet: (context) => DesktopIndexCarousel(galleries),
desktop: DesktopIndexCarousel(galleries), desktop: (context) => DesktopIndexCarousel(galleries),
); );
} }

View File

@@ -6,14 +6,14 @@ import 'package:responsive_builder/responsive_builder.dart';
class IndexMainContent1 extends StatelessWidget { class IndexMainContent1 extends StatelessWidget {
final String message; final String message;
const IndexMainContent1(this.message, {Key key}) : super(key: key); const IndexMainContent1(this.message, {Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ScreenTypeLayout( return ScreenTypeLayout.builder(
mobile: MobileIndexMainContent1(message), mobile: (context) => MobileIndexMainContent1(message),
tablet: DesktopIndexMainContent1(message), tablet: (context) => DesktopIndexMainContent1(message),
desktop: DesktopIndexMainContent1(message), desktop: (context) => DesktopIndexMainContent1(message),
); );
} }

View File

@@ -6,14 +6,14 @@ import 'package:responsive_builder/responsive_builder.dart';
class IndexMainContent2 extends StatelessWidget { class IndexMainContent2 extends StatelessWidget {
final Map<String, dynamic> content; final Map<String, dynamic> content;
const IndexMainContent2(this.content, {Key key}) : super(key: key); const IndexMainContent2(this.content, {Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ScreenTypeLayout( return ScreenTypeLayout.builder(
mobile: MobileIndexMainContent2(content), mobile: (context) => MobileIndexMainContent2(content),
tablet: DesktopIndexMainContent2(content), tablet: (context) => DesktopIndexMainContent2(content),
desktop: DesktopIndexMainContent2(content), desktop: (context) => DesktopIndexMainContent2(content),
); );
} }

Some files were not shown because too many files have changed in this diff Show More