repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/Chi_Food/lib | mirrored_repositories/Chi_Food/lib/model/locationLocation.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'locationLocation.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<LocationLocation> _$locationLocationSerializer =
new _$LocationLocationSerializer();
class _$LocationLocationSerializer
implements StructuredSerializer<LocationLocation> {
@override
final Iterable<Type> types = const [LocationLocation, _$LocationLocation];
@override
final String wireName = 'LocationLocation';
@override
Iterable<Object> serialize(Serializers serializers, LocationLocation object,
{FullType specifiedType = FullType.unspecified}) {
final result = <Object>[
'entity_type',
serializers.serialize(object.entity_type,
specifiedType: const FullType(String)),
'entity_id',
serializers.serialize(object.entity_id,
specifiedType: const FullType(int)),
'title',
serializers.serialize(object.title,
specifiedType: const FullType(String)),
'latitude',
serializers.serialize(object.latitude,
specifiedType: const FullType(String)),
'longitude',
serializers.serialize(object.longitude,
specifiedType: const FullType(String)),
'city_id',
serializers.serialize(object.city_id, specifiedType: const FullType(int)),
'country_id',
serializers.serialize(object.country_id,
specifiedType: const FullType(int)),
'city_name',
serializers.serialize(object.city_name,
specifiedType: const FullType(String)),
'country_name',
serializers.serialize(object.country_name,
specifiedType: const FullType(String)),
];
return result;
}
@override
LocationLocation deserialize(
Serializers serializers, Iterable<Object> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = new LocationLocationBuilder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current as String;
iterator.moveNext();
final dynamic value = iterator.current;
switch (key) {
case 'entity_type':
result.entity_type = serializers.deserialize(value,
specifiedType: const FullType(String)) as String;
break;
case 'entity_id':
result.entity_id = serializers.deserialize(value,
specifiedType: const FullType(int)) as int;
break;
case 'title':
result.title = serializers.deserialize(value,
specifiedType: const FullType(String)) as String;
break;
case 'latitude':
result.latitude = serializers.deserialize(value,
specifiedType: const FullType(String)) as String;
break;
case 'longitude':
result.longitude = serializers.deserialize(value,
specifiedType: const FullType(String)) as String;
break;
case 'city_id':
result.city_id = serializers.deserialize(value,
specifiedType: const FullType(int)) as int;
break;
case 'country_id':
result.country_id = serializers.deserialize(value,
specifiedType: const FullType(int)) as int;
break;
case 'city_name':
result.city_name = serializers.deserialize(value,
specifiedType: const FullType(String)) as String;
break;
case 'country_name':
result.country_name = serializers.deserialize(value,
specifiedType: const FullType(String)) as String;
break;
}
}
return result.build();
}
}
class _$LocationLocation extends LocationLocation {
@override
final String entity_type;
@override
final int entity_id;
@override
final String title;
@override
final String latitude;
@override
final String longitude;
@override
final int city_id;
@override
final int country_id;
@override
final String city_name;
@override
final String country_name;
factory _$LocationLocation(
[void Function(LocationLocationBuilder) updates]) =>
(new LocationLocationBuilder()..update(updates)).build();
_$LocationLocation._(
{this.entity_type,
this.entity_id,
this.title,
this.latitude,
this.longitude,
this.city_id,
this.country_id,
this.city_name,
this.country_name})
: super._() {
if (entity_type == null) {
throw new BuiltValueNullFieldError('LocationLocation', 'entity_type');
}
if (entity_id == null) {
throw new BuiltValueNullFieldError('LocationLocation', 'entity_id');
}
if (title == null) {
throw new BuiltValueNullFieldError('LocationLocation', 'title');
}
if (latitude == null) {
throw new BuiltValueNullFieldError('LocationLocation', 'latitude');
}
if (longitude == null) {
throw new BuiltValueNullFieldError('LocationLocation', 'longitude');
}
if (city_id == null) {
throw new BuiltValueNullFieldError('LocationLocation', 'city_id');
}
if (country_id == null) {
throw new BuiltValueNullFieldError('LocationLocation', 'country_id');
}
if (city_name == null) {
throw new BuiltValueNullFieldError('LocationLocation', 'city_name');
}
if (country_name == null) {
throw new BuiltValueNullFieldError('LocationLocation', 'country_name');
}
}
@override
LocationLocation rebuild(void Function(LocationLocationBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
LocationLocationBuilder toBuilder() =>
new LocationLocationBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is LocationLocation &&
entity_type == other.entity_type &&
entity_id == other.entity_id &&
title == other.title &&
latitude == other.latitude &&
longitude == other.longitude &&
city_id == other.city_id &&
country_id == other.country_id &&
city_name == other.city_name &&
country_name == other.country_name;
}
@override
int get hashCode {
return $jf($jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc($jc(0, entity_type.hashCode),
entity_id.hashCode),
title.hashCode),
latitude.hashCode),
longitude.hashCode),
city_id.hashCode),
country_id.hashCode),
city_name.hashCode),
country_name.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('LocationLocation')
..add('entity_type', entity_type)
..add('entity_id', entity_id)
..add('title', title)
..add('latitude', latitude)
..add('longitude', longitude)
..add('city_id', city_id)
..add('country_id', country_id)
..add('city_name', city_name)
..add('country_name', country_name))
.toString();
}
}
class LocationLocationBuilder
implements Builder<LocationLocation, LocationLocationBuilder> {
_$LocationLocation _$v;
String _entity_type;
String get entity_type => _$this._entity_type;
set entity_type(String entity_type) => _$this._entity_type = entity_type;
int _entity_id;
int get entity_id => _$this._entity_id;
set entity_id(int entity_id) => _$this._entity_id = entity_id;
String _title;
String get title => _$this._title;
set title(String title) => _$this._title = title;
String _latitude;
String get latitude => _$this._latitude;
set latitude(String latitude) => _$this._latitude = latitude;
String _longitude;
String get longitude => _$this._longitude;
set longitude(String longitude) => _$this._longitude = longitude;
int _city_id;
int get city_id => _$this._city_id;
set city_id(int city_id) => _$this._city_id = city_id;
int _country_id;
int get country_id => _$this._country_id;
set country_id(int country_id) => _$this._country_id = country_id;
String _city_name;
String get city_name => _$this._city_name;
set city_name(String city_name) => _$this._city_name = city_name;
String _country_name;
String get country_name => _$this._country_name;
set country_name(String country_name) => _$this._country_name = country_name;
LocationLocationBuilder();
LocationLocationBuilder get _$this {
if (_$v != null) {
_entity_type = _$v.entity_type;
_entity_id = _$v.entity_id;
_title = _$v.title;
_latitude = _$v.latitude;
_longitude = _$v.longitude;
_city_id = _$v.city_id;
_country_id = _$v.country_id;
_city_name = _$v.city_name;
_country_name = _$v.country_name;
_$v = null;
}
return this;
}
@override
void replace(LocationLocation other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$LocationLocation;
}
@override
void update(void Function(LocationLocationBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$LocationLocation build() {
final _$result = _$v ??
new _$LocationLocation._(
entity_type: entity_type,
entity_id: entity_id,
title: title,
latitude: latitude,
longitude: longitude,
city_id: city_id,
country_id: country_id,
city_name: city_name,
country_name: country_name);
replace(_$result);
return _$result;
}
}
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/Chi_Food/lib | mirrored_repositories/Chi_Food/lib/model/geoLocation.dart |
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:chifood/model/location.dart';
import 'package:chifood/model/locationLocation.dart';
import 'package:chifood/model/popularity.dart';
import 'package:chifood/model/restaurants.dart';
part 'geoLocation.g.dart';
abstract class GeoLocation implements Built<GeoLocation,GeoLocationBuilder>{
static Serializer<GeoLocation> get serializer => _$geoLocationSerializer;
LocationLocation get location;
Popularity get popularity;
BuiltList<Restaurants> get nearby_restaurants;
GeoLocation._();
factory GeoLocation([void Function(GeoLocationBuilder) updates]) =_$GeoLocation;
} | 0 |
mirrored_repositories/Chi_Food/lib | mirrored_repositories/Chi_Food/lib/model/menuItem.dart | import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:chifood/model/restaurants.dart';
import 'package:chifood/model/review.dart';
import 'package:chifood/model/reviewUser.dart';
part 'menuItem.g.dart';
abstract class MenuItem implements Built<MenuItem,MenuItemBuilder>{
static Serializer<MenuItem> get serializer => _$menuItemSerializer;
String get strMeal;
String get strMealThumb;
String get idMeal;
MenuItem._();
factory MenuItem([void Function(MenuItemBuilder) updates]) =_$MenuItem;
} | 0 |
mirrored_repositories/Chi_Food/lib | mirrored_repositories/Chi_Food/lib/service/apiService.dart |
import 'dart:convert';
import 'package:built_value/serializer.dart';
import 'package:chifood/config.dart';
import 'package:chifood/model/locationLocation.dart';
import 'package:chifood/model/restaurants.dart';
import 'package:chifood/model/serializer.dart';
import 'package:chifood/model/yelpBusiness.dart';
import 'package:chifood/model/yelpReview.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
Future<LocationLocation> getGeoInfoFromZomato(Dio client,String query,double lat,double long) async{
Response res= await client.get<Response>('$url/locations',queryParameters: <String,dynamic>{'query':query,'lat':lat,'lon':long});
return standardSerializers.deserializeWith(LocationLocation.serializer,res.data['location_suggestions'][0]);
}
Future<List<Restaurants>> searchRestaurants(Dio client,String query,String entity_id,String entity_type) async {
try{
Response res=await client.get('https://developers.zomato.com/api/v2.1/search?entity_id=$entity_id&entity_type=$entity_type&q=$query');
return res.data['restaurants'].map<Restaurants>((each){
if(each['restaurant']['user_rating']['aggregate_rating']==0){
return Restaurants((a)=>a ..deeplink='');
}
return standardSerializers.deserializeWith(Restaurants.serializer, each['restaurant']);
}).toList();
}catch(e){
print(e);
}
}
Future<List<YelpBusiness>> searchYelpBusiness(Dio yelpClient,{String term, String latitude, String longitude}) async{
Response res=await yelpClient.get<Response>('https://api.yelp.com/v3/businesses/search',queryParameters: <String,dynamic>{
'term':term,'latitude':latitude,'longitude':longitude
});
return res.data['businesses'].map<YelpBusiness>((each){
return standardSerializers.deserializeWith(YelpBusiness.serializer, each);
}).toList();
}
| 0 |
mirrored_repositories/Chi_Food/lib | mirrored_repositories/Chi_Food/lib/service/orderSort.dart | import 'package:chifood/model/orderItem.dart';
List<List<OrderItem>> SortList(OrderItem content,List<List<OrderItem>> source){
for(List<OrderItem> res in source){
if(res[0].restaurant.id==content.restaurant.id){
res.add(content);
break;
}else{
source.add([content]);
break;
}
}
return source;
}
List<List<OrderItem>> removeFromList(OrderItem content,List<List<OrderItem>> source,int index){
source[index].removeWhere((OrderItem each)=>each.id==content.id);
return source;
} | 0 |
mirrored_repositories/Chi_Food/lib | mirrored_repositories/Chi_Food/lib/utils/priceDollor.dart | String getAvergePayIcon(int level){
var dollor='';
for(var i=0;i< level;i++){
dollor+='\$';
}
return dollor;
} | 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/swipeIndicator.dart | import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_page_indicator/flutter_page_indicator.dart';
class SquareSwiperPagination extends SwiperPlugin {
///color when current index,if set null , will be Theme.of(context).primaryColor
final Color activeColor;
///,if set null , will be Theme.of(context).scaffoldBackgroundColor
final Color color;
///Size of the dot when activate
final double activeSize;
///Size of the dot
final double size;
/// Space between dots
final double space;
final Key key;
const SquareSwiperPagination(
{this.activeColor,
this.color,
this.key,
this.size: 10.0,
this.activeSize: 10.0,
this.space: 3.0});
@override
Widget build(BuildContext context, SwiperPluginConfig config) {
if (config.itemCount > 20) {
print(
"The itemCount is too big, we suggest use FractionPaginationBuilder instead of DotSwiperPaginationBuilder in this sitituation");
}
Color activeColor = this.activeColor;
Color color = this.color;
if (activeColor == null || color == null) {
ThemeData themeData = Theme.of(context);
activeColor = this.activeColor ?? themeData.primaryColor;
color = this.color ?? themeData.scaffoldBackgroundColor;
}
if (config.indicatorLayout != PageIndicatorLayout.NONE &&
config.layout == SwiperLayout.DEFAULT) {
return new PageIndicator(
count: config.itemCount,
controller: config.pageController,
layout: config.indicatorLayout,
size: size,
activeColor: activeColor,
color: color,
space: space,
);
}
List<Widget> list = [];
int itemCount = config.itemCount;
int activeIndex = config.activeIndex;
for (int i = 0; i < itemCount; ++i) {
bool active = i == activeIndex;
list.add(Container(
key: Key("pagination_$i"),
margin: EdgeInsets.all(space),
child: Container(
// color: active ? activeColor : color,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(size/2),
color: active ? activeColor : color,
),
width: active ? activeSize * 2 : size,
height: active ? activeSize : size,
),
));
}
if (config.scrollDirection == Axis.vertical) {
return new Column(
key: key,
mainAxisSize: MainAxisSize.min,
children: list,
);
} else {
return new Row(
key: key,
mainAxisSize: MainAxisSize.min,
children: list,
);
}
}
} | 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/restaurantPageHeader.dart | import 'package:chifood/config.dart';
import 'package:chifood/ui/pages/restaurantScreen.dart';
import 'package:chifood/ui/widgets/restaurantInfoContainer.dart';
import 'package:chifood/utils/priceDollor.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/rendering/sliver_persistent_header.dart';
import 'package:flutter/widgets.dart';
import 'dart:math' as Math;
class RestaurantPageHeader implements SliverPersistentHeaderDelegate {
RestaurantArg index;
RestaurantPageHeader(this.index);
@override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent) {
return Hero(
tag: 'restaurant',
createRectTween: (Rect begin, Rect end) {
return RectTween(
begin: Rect.fromLTRB(
begin.left, begin.top, begin.right, begin.bottom),
end: Rect.fromLTRB(end.left, end.top, end.right, end.bottom),
);
},
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Image.asset(
bannerList[index.id],
fit: BoxFit.cover,
),
Container(height: 200,),
Positioned(
top: 50,
left: 0,
right: 0,
child: Container(
padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap:(){
Navigator.of(context).pop();
},
child: Container(
padding: EdgeInsets.all(10.0),
decoration: BoxDecoration(
color:
Colors.white.withOpacity(titleOpacity(shrinkOffset)),
shape: BoxShape.circle,
),
child: Icon(
Icons.arrow_back_ios,
size: 20.0,
),
),
),
Row(
children: <Widget>[
Container(
padding: EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: Colors.white
.withOpacity(titleOpacity(shrinkOffset)),
shape: BoxShape.circle,
),
child: Icon(
Icons.file_upload,
size: 20.0,
),
),
SizedBox(
width: 20,
),
Container(
padding: EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: Colors.white
.withOpacity(titleOpacity(shrinkOffset)),
shape: BoxShape.circle,
),
child: Icon(
Icons.favorite,
size: 20.0,
color: Colors.redAccent,
),
)
],
)
],
),
),
),
Positioned(
bottom: 10,
left: 50,
right: 50,
child: AnimatedOpacity(
duration: Duration(milliseconds: 550),
opacity: titleOpacity(shrinkOffset),
child: RestaurantInfoCard(index.restaurants),
)),
shrinkOffset > 170?Positioned(
top: 0,
left: 0,
right: 0,
child: Container(
decoration: BoxDecoration(
color: Colors.white ,
),
padding: EdgeInsets.symmetric(vertical: 60, horizontal: 25.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
GestureDetector(
onTap: ()=>Navigator.of(context).pop(),
child: Icon(
Icons.arrow_back_ios,
size: 17.0,
),
),
Padding(
padding: EdgeInsets.only(left: 20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
index.restaurants.name,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
Container(
constraints: BoxConstraints(
minWidth:
MediaQuery.of(context).size.width *
0.7),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
crossAxisAlignment:
CrossAxisAlignment.center,
children: <Widget>[
Icon(
Icons.star,
color: Colors.orange,
),
Text(index.restaurants.user_rating
.aggregate_rating)
],
),
Row(
crossAxisAlignment:
CrossAxisAlignment.center,
children: <Widget>[
Text(
'Votes:',
style: TextStyle(color: Colors.black),
),
Text(
index.restaurants.user_rating.votes)
],
),
Row(
crossAxisAlignment:
CrossAxisAlignment.center,
children: <Widget>[
Text('Average spent:'),
Text(getAvergePayIcon(
index.restaurants.price_range))
],
)
],
),
)
],
),
)
],
)
),
):SizedBox(width: 1,),
],
),
);
}
@override
// TODO: implement maxExtent
double get maxExtent => 300;
@override
// TODO: implement minExtent
double get minExtent => 130;
@override
bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
// TODO: implement shouldRebuild
return true;
}
double titleOpacity(double shrink) {
return 1 - Math.max(0.0, shrink) / maxExtent;
}
double newTitleOpacity(double shrink) {
return 1 - Math.min(0.0, shrink) / maxExtent;
}
@override
// TODO: implement snapConfiguration
FloatingHeaderSnapConfiguration get snapConfiguration => null;
@override
// TODO: implement stretchConfiguration
OverScrollHeaderStretchConfiguration get stretchConfiguration => null;
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/flipTransition.dart |
import 'package:flutter/cupertino.dart';
class FlipTransition extends PageRouteBuilder<dynamic>{
final Widget page;
FlipTransition({this.page})
: super(
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
page,
transitionDuration: Duration(seconds: 1),
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
ScaleTransition(
scale: Tween<double>(
begin: 0.0,
end: 1.0,
).animate(
CurvedAnimation(
parent: animation,
curve: Curves.fastOutSlowIn,
),
),
child: RotationTransition(
turns: Tween<double>(
begin: 0.0,
end: 1.0,
).animate(
CurvedAnimation(
parent: animation,
curve: Curves.linear,
),
),
child: child,
),
),
);
} | 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/loadingWidget.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class MyLoading extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.only(top: 30.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SpinKitFadingCircle(
itemBuilder: (BuildContext context, int index) {
return DecoratedBox(
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
),
);
},
),
Text('Loading Hard')
],
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/draggeableCart.dart | import 'package:flutter/material.dart';
class AppFloatBox extends StatefulWidget {
int item_count;
AppFloatBox(this.item_count);
@override
_AppFloatBoxState createState() => _AppFloatBoxState();
}
class _AppFloatBoxState extends State<AppFloatBox> {
Offset offset = Offset(10, kToolbarHeight + 100);
Offset _calOffset(Size size, Offset offset, Offset nextOffset) {
double dx = 0;
//水平方向偏移量不能小于0不能大于屏幕最大宽度
if ((offset.dx + nextOffset.dx <= 0)) {
dx = 0;
} else if (offset.dx + nextOffset.dx >= (size.width - 50)) {
dx = size.width - 50;
} else {
dx = offset.dx + nextOffset.dx;
}
double dy = 0;
//垂直方向偏移量不能小于0不能大于屏幕最大高度
if (offset.dy + nextOffset.dy >= (size.height - 100)) {
dy = size.height - 100;
} else if (offset.dy + nextOffset.dy <= kToolbarHeight) {
dy = kToolbarHeight+70;
} else {
dy = offset.dy + nextOffset.dy;
}
return Offset(
dx,
dy,
);
}
@override
Widget build(BuildContext context) {
return Positioned(
left: offset.dx,
top: offset.dy,
child: GestureDetector(
onTap: (){
Navigator.of(context).pushNamed('/Order');
},
onPanUpdate: (detail) {
setState(() {
offset =
_calOffset(MediaQuery.of(context).size, offset, detail.delta);
});
},
onPanEnd: (detail) {},
child: _cart()
),
);
}
Widget _cart(){
return Material(
type: MaterialType.transparency,
child: Container(
padding:EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.all(Radius.circular(45.0)),
boxShadow: [BoxShadow(color: Color(0xfff4f4f3),offset: Offset(1.0,2.0),blurRadius: 2.0,spreadRadius: 1.0)]
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
shape: BoxShape.circle
),
child: Icon(Icons.shopping_basket),
padding: EdgeInsets.all(5.0),
margin: EdgeInsets.only(right: 10.0),
),
Text('${widget.item_count} items',style: TextStyle(color: Colors.white,fontWeight: FontWeight.w600,fontSize: 14.0),)
],
),
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/errorWidget.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../config.dart';
class MyErrorWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
Image.asset(
'${asset}404-1.jpg',
fit: BoxFit.cover,
),
Container(
padding: EdgeInsets.symmetric(
horizontal: 20.0, vertical: 15.0),
decoration: BoxDecoration(
color: Colors.yellow,
borderRadius: BorderRadius.all(Radius.circular(20.0)),
),
child: Text(
'Reload Menu',
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 16.0),
),
),
SizedBox(
height: 40,
)
],
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/dropdownMenu.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dropdownController.dart';
class GZXDropdownMenuBuilder {
final Widget dropDownWidget;
final double dropDownHeight;
GZXDropdownMenuBuilder({@required this.dropDownWidget, @required this.dropDownHeight});
}
typedef DropdownMenuChange = void Function(bool isShow, int index);
class GZXDropDownMenu extends StatefulWidget {
final GZXDropdownMenuController controller;
final List<GZXDropdownMenuBuilder> menus;
final int animationMilliseconds;
final Color maskColor;
final DropdownMenuChange dropdownMenuChanging;
final DropdownMenuChange dropdownMenuChanged;
final double topHeight;
const GZXDropDownMenu(
{Key key,
@required this.controller,
@required this.menus,
this.animationMilliseconds = 500,
this.maskColor = const Color.fromRGBO(0, 0, 0, 0.5),
this.dropdownMenuChanging,
this.dropdownMenuChanged,this.topHeight})
: super(key: key);
@override
_GZXDropDownMenuState createState() => _GZXDropDownMenuState();
}
class _GZXDropDownMenuState extends State<GZXDropDownMenu> with SingleTickerProviderStateMixin {
bool _isShowDropDownItemWidget = false;
bool _isShowMask = false;
bool _isControllerDisposed = false;
Animation<double> _animation;
AnimationController _controller;
double _maskColorOpacity;
double _dropDownHeight;
int _currentMenuIndex;
@override
void initState() {
// TODO: implement initState
super.initState();
widget.controller.addListener(_onController);
_controller = new AnimationController(duration: Duration(milliseconds: widget.animationMilliseconds), vsync: this);
}
_onController() {
// print('_GZXDropDownMenuState._onController ${widget.controller.menuIndex}');
_showDropDownItemWidget();
}
@override
Widget build(BuildContext context) {
// print('_GZXDropDownMenuState.build');
_controller.duration = Duration(milliseconds: widget.animationMilliseconds);
return _buildDropDownWidget();
}
dispose() {
_animation?.removeListener(_animationListener);
_animation?.removeStatusListener(_animationStatusListener);
widget.controller?.removeListener(_onController);
_controller?.dispose();
_isControllerDisposed = true;
super.dispose();
}
_showDropDownItemWidget() {
_currentMenuIndex = widget.controller.menuIndex;
if (_currentMenuIndex >= widget.menus.length || widget.menus[_currentMenuIndex] == null) {
return;
}
_isShowDropDownItemWidget = !_isShowDropDownItemWidget;
if (widget.dropdownMenuChanging != null) {
widget.dropdownMenuChanging(_isShowDropDownItemWidget, _currentMenuIndex);
}
if (!_isShowMask) {
_isShowMask = true;
}
_dropDownHeight = widget.menus[_currentMenuIndex].dropDownHeight;
_animation?.removeListener(_animationListener);
_animation?.removeStatusListener(_animationStatusListener);
_animation = new Tween(begin: 0.0, end: _dropDownHeight).animate(_controller)
..addListener(_animationListener)
..addStatusListener(_animationStatusListener);
if (_isControllerDisposed) return;
// print('${widget.controller.isShow}');
if (widget.controller.isShow) {
_controller.forward();
} else if (widget.controller.isShowHideAnimation) {
_controller.reverse();
} else {
_controller.value = 0;
}
}
void _animationStatusListener(AnimationStatus status) {
switch (status) {
case AnimationStatus.dismissed:
// print('dismissed');
_isShowMask = false;
if (widget.dropdownMenuChanged != null) {
widget.dropdownMenuChanged(false, _currentMenuIndex);
}
break;
case AnimationStatus.forward:
// TODO: Handle this case.
break;
case AnimationStatus.reverse:
// TODO: Handle this case.
break;
case AnimationStatus.completed:
// print('completed');
if (widget.dropdownMenuChanged != null) {
widget.dropdownMenuChanged(true, _currentMenuIndex);
}
break;
}
}
void _animationListener() {
var heightScale = _animation.value / _dropDownHeight;
_maskColorOpacity = widget.maskColor.opacity * heightScale;
// print('$_maskColorOpacity');
//这行如果不写,没有动画效果
setState(() {});
}
Widget _mask() {
if (_isShowMask) {
return GestureDetector(
onTap: () {
widget.controller.hide();
},
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
color: widget.maskColor.withOpacity(_maskColorOpacity),
// color: widget.maskColor,
),
);
} else {
return Container(
height: 0,
);
}
}
Widget _buildDropDownWidget() {
int menuIndex = widget.controller.menuIndex;
if (menuIndex >= widget.menus.length) {
return Container();
}
return Positioned(
width: MediaQuery.of(context).size.width,
top: widget.topHeight,
left: 0,
child: Column(
children: <Widget>[
Container(
color: Colors.white,
width: MediaQuery.of(context).size.width,
height: _animation == null ? 0 : _animation.value,
child: widget.menus[menuIndex].dropDownWidget,
),
_mask()
],
));
}
} | 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/dropdownController.dart | import 'package:flutter/cupertino.dart';
enum DropDownType { current, another }
class GZXDropdownMenuController extends ChangeNotifier {
double dropDownHeaderHeight;
int menuIndex = 0;
bool isShow = false;
bool isShowHideAnimation = false;
DropDownType dropDownType;
void show(int index) {
isShow = true;
menuIndex = index;
notifyListeners();
}
void hide({bool isShowHideAnimation = true}) {
this.isShowHideAnimation = isShowHideAnimation;
isShow = false;
notifyListeners();
}
} | 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/myCUstom.dart |
import 'package:chifood/ui/pages/restaurantScreen.dart';
import 'package:chifood/ui/widgets/restaurantInfoContainer.dart';
import 'package:chifood/utils/priceDollor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../config.dart';
class CUS extends StatefulWidget {
RestaurantArg index;
CUS(this.index);
@override
_CUSState createState() => _CUSState();
}
class _CUSState extends State<CUS> with SingleTickerProviderStateMixin {
TabController tabController;
@override
void initState() {
// TODO: implement initState
super.initState();
tabController=TabController(length: 2,vsync: this);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
backgroundColor: Colors.white,
expandedHeight: 300,
pinned: true,
leading: SizedBox(width: 1,),
title: Text('a'),
flexibleSpace: Stack(
children: <Widget>[
Image.asset(
bannerList[widget.index.id],
fit: BoxFit.cover,
),
Positioned(
top: 50,
left: 0,
right: 0,
child: Container(
padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap:(){
Navigator.of(context).pop();
},
child: Container(
padding: EdgeInsets.all(10.0),
decoration: BoxDecoration(
color:
Colors.white,
shape: BoxShape.circle,
),
child: Icon(
Icons.arrow_back_ios,
size: 20.0,
),
),
),
Row(
children: <Widget>[
Container(
padding: EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: Colors.white
,
shape: BoxShape.circle,
),
child: Icon(
Icons.file_upload,
size: 20.0,
),
),
SizedBox(
width: 20,
),
Container(
padding: EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
child: Icon(
Icons.favorite,
size: 20.0,
color: Colors.redAccent,
),
)
],
)
],
),
),
),
Positioned(
bottom: 10,
left: 50,
right: 50,
child: RestaurantInfoCard(widget.index.restaurants)),
],
),
),
SliverPersistentHeader( // 可以吸顶的TabBar
pinned: true,
delegate: StickyTabBarDelegate(
child: TabBar(
labelColor: Colors.black,
controller:tabController,
tabs: <Widget>[
Tab(text: 'Home'),
Tab(text: 'Profile'),
],
),
),
),
SliverFillRemaining( // 剩余补充内容TabBarView
child: TabBarView(
controller: tabController,
children: <Widget>[
Center(child: Text('Content of Home')),
Center(child: Text('Content of Profile')),
],
),
),
],
)
,
);
}
}
class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
final TabBar child;
StickyTabBarDelegate({@required this.child});
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
return this.child;
}
@override
double get maxExtent => this.child.preferredSize.height;
@override
double get minExtent => this.child.preferredSize.height;
@override
bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
return true;
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/CategoryListView.dart | import 'package:chifood/config.dart';
import 'package:chifood/model/category.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class CategoryList extends StatefulWidget {
List<Category> _categoryList;
CategoryList(this._categoryList);
@override
_CategoryListState createState() => _CategoryListState();
}
class _CategoryListState extends State<CategoryList> {
List<String>a=['guide1.jpeg','guide2.jpeg','guide3.jpeg','guide4.jpeg'];
@override
Widget build(BuildContext context) {
return Container(
constraints: BoxConstraints(maxHeight: 150),
padding: EdgeInsets.only(bottom: 20.0),
margin: EdgeInsets.only(bottom: 10),
child: ListView.builder(itemBuilder: (BuildContext context,int index){
Category each= widget._categoryList[index];
return GestureDetector(
onTap: (){
},
child: Container(
//constraints: BoxConstraints(maxHeight: 80),
margin: EdgeInsets.symmetric(horizontal: 15.0),
padding: EdgeInsets.all(10),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
margin: EdgeInsets.only(bottom: 10),
// padding: EdgeInsets.all(20.0),
constraints: BoxConstraints(maxHeight: 60,maxWidth: 60),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
image: DecorationImage(image: AssetImage('$asset${a[index%a.length]}'),fit: BoxFit.fill),
boxShadow: [
BoxShadow(
color: Color(0xffd3d3d3),blurRadius: 10.0,spreadRadius: 2.0,offset: Offset(0.0,1.0)
)
]
),
),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: 70),
child: Text(each.name,overflow: TextOverflow.ellipsis,),
)
],
),
),
);
},scrollDirection: Axis.horizontal, itemCount: widget._categoryList.length,),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/paymentCard.dart | import 'package:chifood/config.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class PaymentCard extends StatefulWidget {
final void Function() turn;
PaymentCard(this.turn);
@override
_PaymentCardState createState() => _PaymentCardState();
}
class _PaymentCardState extends State<PaymentCard> {
int selected=0;
final imgList=['applypay.png','mastercard.jpg','visa.png'];
final colorList=[0xffFFE53B,0xffFF2525,0xff52ACFF,0xffFFE32C,0xff6284FF,0xffFF0000];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: GestureDetector(
onTap:()=>Navigator.of(context).pop(),
child: Icon(Icons.arrow_back_ios),
),
title: Text('Payment Method',style: TextStyle(fontSize: 16.0,fontWeight: FontWeight.w600),),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.all(30.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Select your payment method',style: TextStyle(fontSize: 16.0,fontWeight: FontWeight.w700),),
Container(
constraints: BoxConstraints(minWidth: 80),
padding: EdgeInsets.symmetric(horizontal: 10.0,vertical: 5.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(15.0)),
color: Color(0xff21bf73)
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Icon(Icons.account_balance_wallet,color: Colors.white,),
Text('\$ 30.6',style: TextStyle(fontWeight: FontWeight.bold,color: Colors.white,fontSize: 13.0),)
],
),
)
],
),
),
Container(
margin: EdgeInsets.only(left: 20.0),
padding: EdgeInsets.all(5.0),
width: double.infinity,
height: 170,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(topLeft: Radius.circular(10.0),bottomLeft: Radius.circular(10.0)),
color: Color(0xffeeedee)
),
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 3,
itemBuilder: (BuildContext context, int index){
if(index==0){
return Container(
child: Icon(Icons.arrow_back_ios),
);
}
return GestureDetector(
onTap:()=> setState(() {
selected=index;
}),
child: Container(
width: 120,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(colorList[index]),Color(colorList[index+1])]
),
borderRadius: BorderRadius.all(Radius.circular(10.0)),
),
margin: EdgeInsets.symmetric(horizontal: 10.0,vertical: 15.0),
padding: EdgeInsets.only(top: 10.0,left: 10.0,right: 10.0,bottom: 10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
child: Row(
mainAxisAlignment: selected==index?MainAxisAlignment.spaceBetween: MainAxisAlignment.start,
children: <Widget>[
Container(
width:45,
height: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
image: DecorationImage(image: AssetImage('${asset}${imgList[index]}'),fit: BoxFit.fill)
),
),
selected==index? Container(
padding:EdgeInsets.all(3.0),
child: Icon(Icons.done,color: Colors.white,size: 14.0,),
decoration: BoxDecoration(
color: Colors.redAccent,
shape: BoxShape.circle
),
):SizedBox(height: 1,)
],
),
),
Text('Balanced $index',style: TextStyle(fontWeight: FontWeight.bold,color: Colors.white),),
],
),
),
);
}),
),
SizedBox(height: 50,),
Container(
width: MediaQuery.of(context).size.width*0.85,
decoration: BoxDecoration(
color: Color(0xffeeedee),
borderRadius: BorderRadius.all(Radius.circular(15.0))
),
padding: EdgeInsets.symmetric(horizontal: 20.0,vertical: 10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.add),
Text('Add Credit Card',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16.0),)
],
),
),
SizedBox(height: 50,),
Container(
width: MediaQuery.of(context).size.width*0.85,
decoration: BoxDecoration(
color: Color(0xffeeedee),
borderRadius: BorderRadius.all(Radius.circular(15.0))
),
padding: EdgeInsets.symmetric(horizontal: 20.0,vertical: 10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Mastercard'),
SizedBox(height: 5,),
Text('**** **** **** 083',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16.0),)
],
),
),
SizedBox(height: 50,),
GestureDetector(
onTap: ()=>widget.turn(),
child: Container(
width: MediaQuery.of(context).size.width*0.85,
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.all(Radius.circular(15.0))
),
padding: EdgeInsets.symmetric(horizontal: 20.0,vertical: 15.0),
child: Text('SELECT PAYMENT',style: TextStyle(color: Colors.white,fontSize: 18.0,fontWeight: FontWeight.bold),textAlign: TextAlign.center,),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/couponSliverOrderList.dart |
import 'package:chifood/bloc/orderBloc/orderBloc.dart';
import 'package:chifood/bloc/orderBloc/orderState.dart';
import 'package:chifood/model/orderItem.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
class CouponOrderList extends StatefulWidget {
List<List<OrderItem>> itemList;
CouponOrderList(this.itemList);
@override
_CouponOrderListState createState() => _CouponOrderListState();
}
class _CouponOrderListState extends State<CouponOrderList> {
SlidableState state;
SlidableController slidableController;
@override
void initState() {
// TODO: implement initState
super.initState();
state = new SlidableState();
slidableController = SlidableController(
// onSlideAnimationChanged: handleSlideAnimationChanged,
// onSlideIsOpenChanged: handleSlideIsOpenChanged,
);
}
@override
Widget build(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height*0.7,
width: double.infinity,
color: Color(0xfff9f8f8),
padding: EdgeInsets.symmetric(horizontal: 15.0),
child: MediaQuery.removePadding(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return RestaurantContainer();
},
itemCount:2,shrinkWrap: true,
), context: context,
),
);
}
Widget RestaurantContainer({List<OrderItem> itemList}){
return Container(
padding: EdgeInsets.all(10.0),
margin: EdgeInsets.only(bottom: 20),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(15.0)),
boxShadow: [
BoxShadow(
color: Color(0xffd3d3d3).withOpacity(0.46),
spreadRadius: 1.0,
offset: Offset(1.0,3.0)
)
]
),
child:Column(
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(horizontal: 5.0,vertical: 10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
width: 20,
height: 20,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Color(0xffd3d3d3))
),
),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width*0.7),
child: Text('Sushi Tima',style: TextStyle(fontSize: 16.0,fontWeight: FontWeight.w700),),
),
Icon(Icons.arrow_forward)
],
),
),
ListView.builder(itemBuilder: (BuildContext context,int index){
return Slidable(
actionExtentRatio: 0.25,
actionPane: SlidableScrollActionPane(),
key: Key('key$index'),
dismissal: SlidableDismissal(
child: SlidableDrawerDismissal(),
closeOnCanceled: true,
),
secondaryActions: <Widget>[
BlocBuilder<OrderBloc,OrderState>(
builder: (BuildContext context,OrderState state ){
if(state is OrderListState){
return Container(
margin: EdgeInsets.only(
top: 5.0, bottom: 5.0, right: 5.0, left: 5.0),
padding: EdgeInsets.symmetric(
horizontal: 10.0, vertical: 10.0),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.all(Radius.circular(20.0)),
boxShadow: [
BoxShadow(
color: Color(0xfff0efef),
blurRadius: 5.0,
offset: Offset(3.0, 3.0))
]),
child: IconSlideAction(
caption: 'Delete',
color: Colors.red,
icon: Icons.delete,
onTap: (){
},
closeOnTap: true,
),
);
}else{
return SizedBox(height: 1,);
}
},
),
],
closeOnScroll: true,
child: GestureDetector(
child: Container(
padding: EdgeInsets.symmetric(vertical: 15.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
),
//padding: EdgeInsets.all(5.0),
margin: EdgeInsets.symmetric(horizontal: 4.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
width: 20,
height: 20,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Color(0xffd3d3d3))
),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(15.0)),
image: DecorationImage(image: AssetImage('assets/img/guide2.jpeg'),fit: BoxFit.fill)
),
width: 75.0,
height: 75.0,
),
Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
ConstrainedBox(
constraints: BoxConstraints(maxWidth: 150),
child: Text('Pumpkin Cream Soup',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 14.0),),
),
],
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('\$ 19.9',style: TextStyle(color: Colors.grey,fontWeight: FontWeight.bold,fontSize: 16.0),),
SizedBox(height: 10,),
Text('x1')
],
)
],
),
),
),
);
},itemCount: 3,shrinkWrap: true,physics:NeverScrollableScrollPhysics(),)
],
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/menuTab.dart | import 'package:chifood/model/menuItem.dart';
import 'package:chifood/model/restaurants.dart';
import 'package:chifood/ui/widgets/menuPageView.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class MenuTab extends StatefulWidget {
MenuTab({this.menuItemMap,this.tabController,this.pageController,this.curRestaurant});
TabController tabController;
Restaurants curRestaurant;
List<List<MenuItem>> menuItemMap;
PageController pageController;
// List<List<MenuItem>> menuItemMap;
//
// MenuTab({this.menuItemMap});
@override
_MenuTabState createState() => _MenuTabState();
}
class _MenuTabState extends State<MenuTab> {
var curPage=0;
var isPageChanged=true;
void onPageChange(int index,{PageController p,TabController t}) async{
if(p!=null){
isPageChanged=false;
await p.animateToPage(index, duration: Duration(microseconds: 500), curve: Curves.easeIn);
isPageChanged=true;
widget.tabController.animateTo(index);
}
}
@override
void dispose() {
super.dispose();
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return PageView.builder(
controller: widget.pageController,
itemBuilder: (BuildContext context,int index){
final List<MenuItem> curPage=widget.menuItemMap[index];
return MenuPageView(curPage,widget.curRestaurant);
},
onPageChanged: (int index){
if(isPageChanged){
onPageChange(index,p: widget.pageController);
}
},itemCount: widget.menuItemMap.length,pageSnapping: true,);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/menuPageView.dart |
import 'package:chifood/bloc/orderBloc/orderBloc.dart';
import 'package:chifood/bloc/orderBloc/orderEvent.dart';
import 'package:chifood/bloc/orderBloc/orderState.dart';
import 'package:chifood/model/menuItem.dart';
import 'package:chifood/model/orderItem.dart';
import 'package:chifood/model/restaurants.dart';
import 'package:chifood/service/orderSort.dart';
import 'package:chifood/ui/widgets/AddBar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:transparent_image/transparent_image.dart';
import 'modalScroll.dart';
class MenuPageView extends StatefulWidget {
const MenuPageView(this.itemList,this.restaurants);
final Restaurants restaurants;
final List<MenuItem> itemList;
@override
_MenuPageViewState createState() => _MenuPageViewState();
}
class _MenuPageViewState extends State<MenuPageView> with AutomaticKeepAliveClientMixin{
int count=1;
@override
void initState(){
super.initState();
}
void add(int val){
setState(() {
count=val;
});
}
Widget build(BuildContext context) {
return ListView.builder(itemBuilder: (BuildContext context,int index){
final MenuItem item=widget.itemList[index];
return GestureDetector(
onTap: (){
showModalBottomSheet(context: context,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
builder: (BuildContext context){
return new Container(
height: 350.0,
//color: Colors.transparent, //could change this to Color(0xFF737373),
//so you don't have to change MaterialApp canvasColor
child: new Container(
padding: EdgeInsets.all(20.0),
decoration: new BoxDecoration(
color: Colors.white,
borderRadius: new BorderRadius.only(
topLeft: const Radius.circular(30.0),
topRight: const Radius.circular(30.0))),
child: Stack(
children: <Widget>[
ClipRRect(
child: Image.network(item.strMealThumb,width: 150,height: 150,fit: BoxFit.fill,),
borderRadius: BorderRadius.all(Radius.circular(15.0)),
),
Positioned(
left: 180,
top: 0,
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: 150
),
child:Text(item.strMeal,style: TextStyle(
fontSize: 14.0,fontWeight: FontWeight.bold
),),
),
Container(
padding: EdgeInsets.all(10.0),
child: Icon(Icons.favorite),
),
Container(
padding: EdgeInsets.all(10.0),
child: Icon(Icons.bookmark),
)
],
),
),
Positioned(
bottom: 100,
left: 10,
right: 10,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
AddBar(add),
Text('\$ 18.0',style: TextStyle(fontSize: 17.0,fontWeight: FontWeight.bold),),
],
),
),
BlocBuilder<OrderBloc,OrderState>(
bloc: BlocProvider.of<OrderBloc>(context),
builder: (BuildContext context, OrderState state){
if(state is NoOrderState){
return Positioned(
bottom: 15,
left: 10,
right: 10,
child: CupertinoButton(
disabledColor: Theme.of(context).primaryColor,
color: Colors.yellow,
onPressed: (){
OrderItem cur=OrderItem((a)=>a ..strMeal=item.strMeal ..price=18.0 ..strMealThumb=item.strMealThumb ..idMeal=item.idMeal ..count=count ..restaurant=widget.restaurants.toBuilder());
BlocProvider.of<OrderBloc>(context).add(AddRemoveOrderEvent([[cur]]));
Navigator.pop(context);
},
child: Text('Add To Cart',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 17.0,color: Colors.black),),
),
);
}else if(state is OrderListState ){
return Positioned(
bottom: 15,
left: 10,
right: 10,
child: CupertinoButton(
disabledColor: Theme.of(context).primaryColor,
color: Colors.yellow,
onPressed: (){
OrderItem cur=OrderItem((a)=>a ..price=18.0 ..strMeal=item.strMeal ..strMealThumb=item.strMealThumb ..idMeal=item.idMeal ..count=count ..restaurant=widget.restaurants.toBuilder());
List<List<OrderItem>> a=state.orderList;
a=SortList(cur, a);
BlocProvider.of<OrderBloc>(context).add(AddRemoveOrderEvent(a));
Navigator.pop(context);
},
child: Text('Add To Cart',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 17.0,color: Colors.black),),
),
);
}
return Positioned(
bottom: 15,
left: 10,
right: 10,
child: CupertinoButton(
disabledColor: Theme.of(context).primaryColor,
color: Colors.yellow,
onPressed: (){
Navigator.pop(context);
},
child: Text('Add To Cart',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 17.0,color: Colors.black),),
),
);
},
)
],
)
),
);
},isScrollControlled: true);
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 15.0,vertical: 10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.46),
blurRadius: 10.0,
offset: Offset(1.0,5.0)
)
]
),
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: FadeInImage.memoryNetwork(placeholder: kTransparentImage, image: item.strMealThumb,width: 70,height: 70,),
),
),
SizedBox(width: 10,),
Column(
children: <Widget>[
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width*0.5
),
child: Text(item.strMeal,style: TextStyle(fontWeight: FontWeight.bold,fontSize: 14.0),),
)
],
)
],
),
Container(
padding: EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
border: Border.all(color: Theme.of(context).primaryColor),
boxShadow: [
BoxShadow(
color: Color(0xffd3d3d3).withOpacity(0.9),
offset: Offset(0,3),
blurRadius: 2.0
)
]
),
child: Icon(Icons.add,size: 17.0,color: Theme.of(context).primaryColor,),
)
],
),
),
);
},
itemCount: widget.itemList.length,
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
);
}
@override
bool get wantKeepAlive => true;
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/dropdownHeader.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dropdownController.dart';
typedef OnItemTap<T> = void Function(T value);
class GZXDropDownHeader extends StatefulWidget {
final Color color;
final double borderWidth;
final Color borderColor;
final TextStyle style;
final TextStyle dropDownStyle;
final double iconSize;
final Color iconColor;
final Color iconDropDownColor;
// final List<String> menuStrings;
final double height;
final double dividerHeight;
final Color dividerColor;
final GZXDropdownMenuController controller;
final OnItemTap onItemTap;
final List<GZXDropDownHeaderItem> items;
final GlobalKey stackKey;
GZXDropDownHeader({
Key key,
@required this.items,
@required this.controller,
@required this.stackKey,
this.style = const TextStyle(color: Color(0xFF666666), fontSize: 13),
this.dropDownStyle,
this.height = 40,
this.iconColor = const Color(0xFFafada7),
this.iconDropDownColor,
this.iconSize = 20,
this.borderWidth = 1,
this.borderColor = const Color(0xFFeeede6),
this.dividerHeight = 20,
this.dividerColor = const Color(0xFFeeede6),
this.onItemTap,
this.color = Colors.white,
}) : super(key: key);
@override
_GZXDropDownHeaderState createState() => _GZXDropDownHeaderState();
}
class _GZXDropDownHeaderState extends State<GZXDropDownHeader> with SingleTickerProviderStateMixin {
bool _isShowDropDownItemWidget = false;
double _screenWidth;
int _menuCount;
GlobalKey _keyDropDownHeader = GlobalKey();
TextStyle _dropDownStyle;
Color _iconDropDownColor;
@override
void initState() {
// TODO: implement initState
super.initState();
widget.controller.addListener(_onController);
}
_onController() {
if (mounted) {
setState(() {});
}
// print(widget.controller.menuIndex);
}
@override
Widget build(BuildContext context) {
_dropDownStyle = TextStyle(color: Colors.white, fontSize: 14,fontWeight: FontWeight.bold);
_iconDropDownColor = Colors.white;
MediaQueryData mediaQuery = MediaQuery.of(context);
_screenWidth = mediaQuery.size.width;
_menuCount = widget.items.length;
var gridView = GridView.count(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
key: _keyDropDownHeader,
crossAxisCount: _menuCount,
childAspectRatio: (_screenWidth / _menuCount) / widget.height,
children: widget.items.map<Widget>((item) {
return _menu(item);
}).toList(),
);
return gridView;
}
dispose() {
super.dispose();
}
_menu(GZXDropDownHeaderItem item) {
int index = widget.items.indexOf(item);
int menuIndex = widget.controller.menuIndex;
_isShowDropDownItemWidget = index == menuIndex && widget.controller.isShow;
return GestureDetector(
onTap: () {
final RenderBox overlay = widget.stackKey.currentContext.findRenderObject();
final RenderBox dropDownItemRenderBox = _keyDropDownHeader.currentContext.findRenderObject();
var position = dropDownItemRenderBox.localToGlobal(Offset.zero, ancestor: overlay);
// print("POSITION : $position ");
var size = dropDownItemRenderBox.size;
// print("SIZE : $size");
widget.controller.dropDownHeaderHeight = size.height + position.dy;
if (index == menuIndex) {
if (widget.controller.isShow) {
widget.controller.hide();
} else {
widget.controller.show(index);
}
} else {
if (widget.controller.isShow) {
widget.controller.hide(isShowHideAnimation: false);
}
widget.controller.show(index);
}
if (widget.onItemTap != null) {
widget.onItemTap(index);
}
setState(() {});
},
child: Container(
color:widget.color!=null?widget.color:Theme.of(context).primaryColor,
constraints: BoxConstraints(maxHeight: 40),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Flexible(
child: Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: _isShowDropDownItemWidget ? _dropDownStyle : widget.style.merge(item.style),
),
),
Icon(
!_isShowDropDownItemWidget ? item.iconData ?? Icons.arrow_drop_down : item.iconData ?? Icons.arrow_drop_up,
color: _isShowDropDownItemWidget ? _iconDropDownColor : item?.style?.color ?? widget.iconColor,
size: item.iconSize ?? widget.iconSize,
),
],
),
),
index == widget.items.length - 1
? Container()
: Container(
height: widget.dividerHeight,
decoration: BoxDecoration(
border: Border(
right: BorderSide(color: widget.dividerColor, width: 1),
),
),
)
],
),
),
);
}
}
class GZXDropDownHeaderItem {
final String title;
final IconData iconData;
final double iconSize;
final TextStyle style;
GZXDropDownHeaderItem(this.title, {this.iconData, this.iconSize, this.style});
}
class SortCondition {
String name;
bool isSelected;
String id;
SortCondition({this.name, this.isSelected,String id});
} | 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/restaurantInfoContainer.dart |
import 'package:chifood/model/restaurants.dart';
import 'package:chifood/utils/priceDollor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class RestaurantInfoCard extends StatelessWidget {
Restaurants curRes;
RestaurantInfoCard(this.curRes);
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(15.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
color: Colors.white),
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: Colors.black54))),
child: Row(
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
curRes.name,
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 17.0),
),
Text(
curRes.location.address,
style: TextStyle(
fontWeight: FontWeight.w600,
color: Colors.grey),
),
SizedBox(height: 5,),
],
),
],
),
),
SizedBox(height: 5,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Icon(
Icons.star,
color: Colors.orange,
size: 18.0,
),
Text(curRes.user_rating.aggregate_rating, style: TextStyle(color: Colors.black,fontWeight: FontWeight.bold),)
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
'Votes:',
),
Text(curRes.user_rating.votes, style: TextStyle(color: Colors.black,fontWeight: FontWeight.bold),)
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text('Average spent:'),
Text(getAvergePayIcon(curRes.price_range),style: TextStyle(fontWeight: FontWeight.bold),)
],
),
],
)
],
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/AddressCard.dart |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class CustomCard extends StatefulWidget {
final void Function() turn;
CustomCard(this.turn);
@override
_CustomCardState createState() => _CustomCardState();
}
class _CustomCardState extends State<CustomCard> {
int selected=0;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
leading: GestureDetector(
onTap: ()=>widget.turn(),
child: Icon(Icons.arrow_back_ios),
),
backgroundColor: Colors.white,
elevation: 0.0,
title: Text('Address Delivery',style: TextStyle(fontSize: 16.0,fontWeight: FontWeight.w600),),
),
body: SingleChildScrollView(
child:Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
color: Colors.white,
padding: EdgeInsets.all(20.0),
width: MediaQuery.of(context).size.width,
child: Container(
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width*0.7),
child: Text('Select an address to deliver your dishes',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 17.0))
,
),
),
SizedBox(height: 30,),
Container(
margin: EdgeInsets.only(left: 20.0),
padding: EdgeInsets.all(5.0),
width: double.infinity,
height: 330,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(topLeft: Radius.circular(10.0),bottomLeft: Radius.circular(10.0)),
color: Color(0xffeeedee)
),
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 6,
itemBuilder: (BuildContext context, int index){
if(index==0){
return Container(
child: Icon(Icons.arrow_back_ios),
);
}
return GestureDetector(
onTap:()=> setState(() {
selected=index;
}),
child: Container(
width: 120,
decoration: BoxDecoration(
color:selected==index?Theme.of(context).primaryColor: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10.0)),
),
margin: EdgeInsets.symmetric(horizontal: 10.0,vertical: 15.0),
padding: EdgeInsets.only(top: 30.0,left: 10.0,right: 10.0,bottom: 10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
height: 20,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
selected==index? Container(
padding:EdgeInsets.all(3.0),
child: Icon(Icons.done,color: Colors.white,size: 14.0,),
decoration: BoxDecoration(
color: Colors.redAccent,
shape: BoxShape.circle
),
):SizedBox(height: 1,)
],
),
),
Text('Address $index',style: TextStyle(fontWeight: FontWeight.bold),),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: 120,minHeight: 170),
child: Text('516 Albert Street, Kingston, K7K 4M4',style: TextStyle(color: selected==index?Colors.black54:Colors.blueGrey),),
),
Icon(Icons.restore_from_trash)
],
),
),
);
}),
),
SizedBox(height: 70,),
Container(
width:MediaQuery.of(context).size.width*0.9 ,
decoration: BoxDecoration(
color: Color(0xffeeedee),
borderRadius: BorderRadius.all(Radius.circular(10.0))
),
padding: EdgeInsets.symmetric(horizontal: 20.0,vertical: 10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Icon(Icons.add),
Text('Add new Address',style: TextStyle(fontWeight: FontWeight.bold),)
],
),
),
SizedBox(height: 50.0,),
GestureDetector(
onTap:()=> Navigator.of(context).pushNamed('/OrderFinish'),
child: Container(
width:MediaQuery.of(context).size.width*0.9 ,
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.all(Radius.circular(15.0)),
boxShadow: [
BoxShadow(
color: Color(0xfff0f0f0),
spreadRadius: 3.0,
blurRadius: 2.0,
offset: Offset(1.0,3.0)
)
]
),
padding: EdgeInsets.symmetric(horizontal: 20.0,vertical: 11.0),
child: Text('PLACE ORDER',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 20.0),textAlign: TextAlign.center,),
),
),
SizedBox(height: 30,)
],
),
)
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/restaurantTab.dart | import 'package:chifood/model/menuCategory.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class RestaurantTab extends StatefulWidget {
RestaurantTab({this.tabTitle,this.pageController,this.tabController});
PageController pageController;
TabController tabController;
List<MenuCategory> tabTitle;
@override
_RestaurantTabState createState() => _RestaurantTabState();
// RestaurantTab({this.tabTitle});
}
class _RestaurantTabState extends State<RestaurantTab> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return TabBar(
labelPadding: EdgeInsets.symmetric(horizontal: 15.0,vertical: 5.0),
controller: widget.tabController,
isScrollable: true,
indicatorColor: Colors.transparent,
labelStyle: TextStyle(fontSize: 17.0,fontWeight: FontWeight.bold,color: Colors.black),
unselectedLabelStyle: TextStyle(fontSize: 14.0,fontWeight: FontWeight.w600,color: Colors.grey),
tabs: widget.tabTitle.map((MenuCategory each){
return Tab(text: each.strCategory);
}).toList(),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/resSwipe.dart | import 'package:built_collection/built_collection.dart';
import 'package:chifood/bloc/mealBloc/mealBloc.dart';
import 'package:chifood/bloc/mealBloc/menuEvent.dart';
import 'package:chifood/bloc/restaurantBloc/restaurantBloc.dart';
import 'package:chifood/bloc/restaurantBloc/restaurantEvent.dart';
import 'package:chifood/model/restaurants.dart';
import 'package:chifood/ui/pages/restaurantScreen.dart';
import 'package:chifood/ui/widgets/restaurantInfoContainer.dart';
import 'package:chifood/utils/priceDollor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import '../../config.dart';
class ResSwiper extends StatefulWidget {
List<Restaurants> restaurantlist;
ResSwiper(this.restaurantlist);
@override
_ResSwiperState createState() => _ResSwiperState();
}
class _ResSwiperState extends State<ResSwiper> {
@override
Widget build(BuildContext context) {
return Swiper(
itemCount: 4,
itemBuilder: _build,
containerWidth: 200,
containerHeight: 200,
pagination: SwiperPagination(
alignment: Alignment.bottomCenter,
margin: const EdgeInsets.only(top: 120),
builder: DotSwiperPaginationBuilder(
color: Colors.grey,
activeColor: Colors.black,
space: 3.0,
activeSize: 14.0)),
controller: SwiperController(),
scrollDirection: Axis.horizontal,
);
}
Widget _build(BuildContext context, int index) {
final Restaurants curRes=widget.restaurantlist[index];
return GestureDetector(
onTap: (){
BlocProvider.of<RestaurantBloc>(context).add(LoadRestaurantAllInfoEvent(curRes));
BlocProvider.of<MenuBloc>(context).add(LoadMenuEvent());
Navigator.pushNamed(context,'/Restaurant',arguments: RestaurantArg(index,curRes));
},
child: Hero(
tag: 'restuarant',
createRectTween: (Rect begin, Rect end) {
return RectTween(
begin: Rect.fromLTRB(
begin.left, begin.top, begin.right, begin.bottom),
end: Rect.fromLTRB(end.left, end.top, end.right, end.bottom),
);
},
child: Container(
width: 200,
height: 200,
padding: EdgeInsets.all(20.0),
margin: EdgeInsets.only(left: 20, right: 20, bottom: 60, top: 20),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
image: DecorationImage(
image: AssetImage(bannerList[index]), fit: BoxFit.cover)),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
RestaurantInfoCard(curRes)
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/AddBar.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class AddBar extends StatefulWidget {
Function(int) callback;
AddBar(this.callback);
@override
_AddBarState createState() => _AddBarState();
}
class _AddBarState extends State<AddBar> {
int count=1;
@override
Widget build(BuildContext context) {
bool disable=count==1;
return Container(
constraints: BoxConstraints(minWidth: MediaQuery.of(context).size.width*0.3),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
GestureDetector(
onTap: (){
if(!disable){
count-=1;
setState(() {
});
widget.callback(count);
}
},
child: Container(
padding: EdgeInsets.all(5.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: disable?Colors.grey:Theme.of(context).primaryColor
)
),
child: Icon(Icons.remove,color:disable?Colors.grey:Theme.of(context).primaryColor ,),
),
),
Text(count.toString(),style: TextStyle(fontWeight: FontWeight.bold,fontSize: 17.0),),
GestureDetector(
onTap: (){
count+=1;
setState(() {
});
widget.callback(count);
},
child: Container(
padding: EdgeInsets.all(5.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: Theme.of(context).primaryColor
)
),
child: Icon(Icons.add,color:Theme.of(context).primaryColor ,),
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/getRating.dart | import 'package:flutter/material.dart';
class StarRating extends StatelessWidget {
final int starCount;
final double rating;
final Color color;
StarRating({this.starCount = 5, this.rating = .0, this.color});
Widget buildStar(BuildContext context, int index) {
Icon icon;
if (index >= rating) {
icon = new Icon(
Icons.star_border,
color: Colors.grey,
);
}
else if (index > rating - 1 && index < rating) {
icon = new Icon(
Icons.star_half,
color: color ?? Colors.orange,
);
} else {
icon = new Icon(
Icons.star,
color: color ?? Colors.orange,
);
}
return icon;
}
@override
Widget build(BuildContext context) {
return new Row(children: new List.generate(starCount, (index) => buildStar(context, index)));
}
} | 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/restaurantScrollView.dart | import 'dart:async';
import 'package:chifood/bloc/mealBloc/menuState.dart';
import 'package:chifood/bloc/orderBloc/orderBloc.dart';
import 'package:chifood/bloc/orderBloc/orderState.dart';
import 'package:chifood/ui/pages/restaurantScreen.dart';
import 'package:chifood/ui/widgets/draggeableCart.dart';
import 'package:chifood/ui/widgets/restaurantPageHeader.dart';
import 'package:chifood/ui/widgets/restaurantTab.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'menuTab.dart';
class RestaurantScrollView extends StatefulWidget {
ScrollController controller;
RestaurantArg arg;
LoadMenuState state;
RestaurantScrollView({this.controller, this.arg,this.state});
@override
_RestaurantScrollViewState createState() => _RestaurantScrollViewState();
}
class _RestaurantScrollViewState extends State<RestaurantScrollView> with SingleTickerProviderStateMixin{
Set<Marker> _markers = {};
Completer<GoogleMapController> _mapController = Completer();
TabController tabController;
PageController pageController=PageController(initialPage: 0);
@override
void initState() {
// TODO: implement initState
super.initState();
tabController = TabController(vsync: this, length: widget.state.menuCategory.length);
tabController.addListener((){
if(tabController.indexIsChanging){
pageController.animateToPage(tabController.index, duration: Duration(milliseconds: 550), curve: Curves.easeIn);
}
});
}
@override
Widget build(BuildContext context) {
final args=widget.arg;
return NestedScrollView(
controller: widget.controller,
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
SliverPersistentHeader(
pinned: true,
floating: false,
delegate: RestaurantPageHeader(args),
),
SliverList(
delegate: SliverChildListDelegate([
Container(
padding: EdgeInsets.all(20.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: Color(0xfff4f4f3)))),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Restaurant Location',
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 17.0),
),
SizedBox(
height: 10,
),
Container(
width: MediaQuery.of(context).size.width * 0.9,
height: 150,
decoration: BoxDecoration(border: Border.all()),
child: GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(
double.parse(args.restaurants.location.latitude),
double.parse(args.restaurants.location.longitude)),
zoom: 14.0000,
),
mapType: MapType.normal,
markers: _markers
..add(Marker(
markerId: MarkerId('restloc${args.restaurants.id}'),
position: LatLng(
double.parse(
args.restaurants.location.latitude),
double.parse(
args.restaurants.location.longitude)))),
compassEnabled: false,
myLocationButtonEnabled: false,
onMapCreated: (GoogleMapController controller) {
_mapController.complete(controller);
},
),
)
],
),
),
])),
SliverToBoxAdapter(
child:
RestaurantTab(
tabTitle: widget.state.menuCategory,
pageController: pageController,
tabController: tabController,
),
// BlocBuilder<MenuBloc, MenuState>(
// bloc: BlocProvider.of<MenuBloc>(context),
// builder: (BuildContext context, MenuState state) {
// if(state is LoadMenuState){
// return RestaurantTab(tabTitle: state.menuCategory,);
// }else{
// return MyErrorWidget();
// }
// })
)
];
},
body: MenuTab(
menuItemMap: widget.state.menuList,
tabController: tabController,
pageController: pageController,
curRestaurant: args.restaurants,
)
// BlocBuilder<MenuBloc, MenuState>(
// bloc: BlocProvider.of<MenuBloc>(context),
// builder: (BuildContext context, MenuState state) {
// if(state is LoadMenuState){
// return MenuTab(menuItemMap: state.menuList);
// }else{
// return MyErrorWidget();
// }
// }),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/FilterRestrauant.dart | import 'package:chifood/bloc/restaurantBloc/restaurantBloc.dart';
import 'package:chifood/bloc/restaurantBloc/restaurantEvent.dart';
import 'package:chifood/config.dart';
import 'package:chifood/model/restaurants.dart';
import 'package:chifood/ui/widgets/dropdownHeader.dart';
import 'package:chifood/ui/widgets/restaurantContentList.dart';
import 'package:chifood/utils/priceDollor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class RestaurantList extends StatefulWidget {
List<Restaurants> restaurantList;
List<GZXDropDownHeaderItem> filterChoice;
Widget handler;
RestaurantList({this.restaurantList,this.handler,this.filterChoice});
@override
_RestaurantListState createState() => _RestaurantListState();
}
class _RestaurantListState extends State<RestaurantList> {
@override
Widget build(BuildContext context) {
List<String> choices=turnOrder(widget.filterChoice);
return Container(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 16.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15.0), topRight: Radius.circular(15.0)),
boxShadow: [
BoxShadow(
color: Color(0xfff4f4f3),
offset: Offset(0.0, -3.0),
spreadRadius: 2.0)
]),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'All Restaurants',
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0),
),
choices.length!=0?Text('Fileter by: ${choices.join(',')}'):Text('No Filter')
],
),
GestureDetector(
onTap: ()=>Navigator.of(context).pushNamed('/FilterRestaurants'),
child: Container(
padding: EdgeInsets.all(10.0),
child: Icon(Icons.sort),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: Color(0xfff4f4f3)),
shape: BoxShape.circle,
),
),
)
],
),
widget.restaurantList==null?widget.handler:RestaurantContentList(widget.restaurantList)
],
),
);
}
List<String> turnOrder(List<GZXDropDownHeaderItem> source){
return source.where((i) =>(i.title!='Distance'&&i.title!='Category'&&i.title!='Cuisine')).map((e) => e?.title);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/loginForm.dart | import 'package:chifood/bloc/authBloc/AuthBloc.dart';
import 'package:chifood/bloc/authBloc/AuthEvent.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:form_field_validator/form_field_validator.dart';
class LoginForm extends StatefulWidget {
@override
_LoginFormState createState() => _LoginFormState();
}
class _LoginFormState extends State<LoginForm> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
void _checkAndSubmit(){
BlocProvider.of<AuthenticationBloc>(context).add(LoginEvent(_emailController.text,_passwordController.text));
}
bool get isPopulated =>
_emailController.text.isNotEmpty && _passwordController.text.isNotEmpty;
@override
Widget build(BuildContext context) {
return Form(
autovalidate: true,
child: Column(
children: <Widget>[
TextFormField(
controller: _emailController,
decoration: InputDecoration(
icon: Icon(Icons.email),
labelText: 'Email',
),
keyboardType: TextInputType.emailAddress,
autovalidate: true,
autocorrect: false,
validator: EmailValidator(errorText: "enter a vaild email"),
),
TextFormField(
controller: _passwordController,
decoration: InputDecoration(
icon: Icon(Icons.lock),
labelText: 'Password',
),
obscureText: true,
autovalidate: true,
autocorrect: false,
validator: RequiredValidator(errorText: "please enter the password"),
),
Padding(
padding: EdgeInsets.symmetric(vertical: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
onPressed: (){
if(isPopulated){
_checkAndSubmit();
}else{
}
},
child: Text('Login'),
),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
onPressed: ()=>Navigator.of(context).pushNamed('/SignUp'),
child: Text('Sign Up'),
)
],
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/modalScroll.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class ModalWithScroll extends StatelessWidget {
final ScrollController scrollController;
const ModalWithScroll({Key key, this.scrollController}) : super(key: key);
@override
Widget build(BuildContext context) {
return Material(
child: CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
leading: Container(), middle: Text('Modal Page')),
child: SafeArea(
bottom: false,
child: ListView(
shrinkWrap: true,
controller: scrollController,
children: ListTile.divideTiles(
context: context,
tiles: List.generate(
100,
(index) => ListTile(
title: Text('Item'),
)),
).toList(),
),
),
),
);
}
} | 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/customDrawer.dart |
import 'package:chifood/ui/pages/order.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class CustomDrawer extends StatefulWidget {
@override
_CustomDrawerState createState() => _CustomDrawerState();
}
class _CustomDrawerState extends State<CustomDrawer> with SingleTickerProviderStateMixin {
AnimationController _animationController;
static final double maxSlide=225;
static const double minDragStartEdge = 60;
static double maxDragStartEdge = maxSlide - 16;
bool _canBeDragged=false;
@override
void initState() {
// TODO: implement initState
super.initState();
_animationController=new AnimationController(vsync: this,duration: Duration(milliseconds: 250));
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
void close() => _animationController.reverse();
void open() => _animationController.forward();
void toggleDrawer() => _animationController.isCompleted ? close() : open();
void _onDragStart(DragStartDetails details){
bool isDragOpenFromLeft =_animationController.isDismissed&&details.globalPosition.dx<minDragStartEdge;
bool isDragOpenFromRight =_animationController.isCompleted&&details.globalPosition.dx> maxDragStartEdge;
_canBeDragged = isDragOpenFromLeft||isDragOpenFromRight;
}
void _onDragUpdate(DragUpdateDetails details){
if(_canBeDragged){
double delta=details.primaryDelta /maxSlide;
_animationController.value+=delta;
}
}
void _onDragEnd(DragEndDetails details){
if(_animationController.isDismissed||_animationController.isCompleted){
return;
}
if(details.velocity.pixelsPerSecond.dx.abs()>=365.0){
double visualelocity=details.velocity.pixelsPerSecond.dx/MediaQuery.of(context).size.width;
_animationController.fling(velocity: visualelocity);
}else if(_animationController.value<0.5){
close();
}else{
open();
}
}
@override
Widget build(BuildContext context) {
var yellow=Container(color: Colors.blue,);
var blue=Container(color: Colors.yellow,);
return GestureDetector(
onHorizontalDragStart: _onDragStart,
onHorizontalDragUpdate:_onDragUpdate ,
onHorizontalDragEnd:_onDragEnd ,
child: AnimatedBuilder(
animation: _animationController,
builder: (context,_){
double animValue = _animationController.value;
final slideAmount = maxSlide * animValue;
final contentScale = 1.0 - (0.3 * animValue);
return Stack(
children: <Widget>[
yellow,
Transform(
transform: Matrix4.identity()
..translate(slideAmount)
..scale(contentScale, contentScale),
alignment: Alignment.centerLeft,
child: GestureDetector(
onTap: _animationController.isCompleted ? close : null,
child: OrderPage(open),
),
)
],
);
},
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/filterPanel.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class FilterPanel extends StatefulWidget {
@override
_FilterPanelState createState() => _FilterPanelState();
}
class _FilterPanelState extends State<FilterPanel> with SingleTickerProviderStateMixin{
TabController _tabController;
@override
void initState() {
// TODO: implement initState
super.initState();
_tabController=TabController(length: 3, vsync: this);
}
// Animation<RelativeRect> _getPanelAnimation(BoxConstraints constraints) {
// final double height = constraints.biggest.height;
// final double top = 0;
// final double bottom = ;
//
// return new RelativeRectTween(
// begin: new RelativeRect.fromLTRB(0.0, top, 0.0, bottom),
// end: new RelativeRect.fromLTRB(0.0, 0.0, 0.0, 0.0),
// ).animate(new CurvedAnimation(parent: _controller, curve: Curves.linear));
// }
@override
Widget build(BuildContext context) {
return Container(
height: 50,
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.only(bottomLeft: Radius.circular(15.0),bottomRight: Radius.circular(15.0))
),
child: Column(
children: <Widget>[
TabBar(
controller: _tabController,
tabs: <Widget>[
],
)
],
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/backdropList.dart |
import 'package:flutter/material.dart';
import 'dropdownHeader.dart';
class ConditionListWidget extends StatelessWidget {
List<SortCondition> items;
void Function(SortCondition) itemOnTap;
SortCondition curSort;
ConditionListWidget(this.items, this.itemOnTap,this.curSort);
@override
Widget build(BuildContext context) {
return ListView.separated(
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemCount: items.length,
// item 的个数
separatorBuilder: (BuildContext context, int index) => Divider(height: 1.0),
// 添加分割线
itemBuilder: (BuildContext context, int index) {
SortCondition goodsSortCondition = items[index];
curSort??=SortCondition(name: "All");
return GestureDetector(
onTap: () {
for (var value in items) {
value.isSelected = false;
}
goodsSortCondition.isSelected = true;
itemOnTap(goodsSortCondition);
},
child: Container(
// color: Colors.blue,
height: 40,
child: Row(
children: <Widget>[
SizedBox(
width: 16,
),
Expanded(
child: Text(
goodsSortCondition.name,
style: TextStyle(
color: goodsSortCondition.name==curSort.name? Theme.of(context).primaryColor : Colors.black,
),
),
),
goodsSortCondition.name==curSort.name
? Icon(
Icons.check,
color: Theme.of(context).primaryColor,
size: 16,
)
: SizedBox(),
SizedBox(
width: 16,
),
],
),
),
);
},
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/animatedOrder.dart | import 'package:flutter/cupertino.dart';
class AnimatedOrder extends StatefulWidget {
@override
_AnimatedOrderState createState() => _AnimatedOrderState();
}
class _AnimatedOrderState extends State<AnimatedOrder> with SingleTickerProviderStateMixin {
AnimationController controller;
Animation<double> animation;
@override
void initState() {
// TODO: implement initState
super.initState();
controller = AnimationController(
vsync: this, duration: const Duration(milliseconds: 2000));
// 通过 Tween 对象 创建 Animation 对象
animation = Tween(begin: 0.0, end: 60.0).animate(controller)
..addListener(() {
// 注意:这句不能少,否则 widget 不会重绘,也就看不到动画效果
setState(() {});
})
..addStatusListener((status) {
if (status == AnimationStatus.completed) {
controller.reverse();
} else if (status == AnimationStatus.dismissed) {
controller.forward();
}});
controller.forward();
}
@override
void dispose() {
// TODO: implement dispose
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: controller,
builder: (context,_){
return Transform(
alignment: Alignment.center,
transform: Matrix4.identity() ..translate(animation.value),
child: Container(
child:Image.asset('assets/img/delivery.png',width: 100,height: 100,)
),
);
},
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/widgets/restaurantContentList.dart | import 'package:chifood/bloc/mealBloc/mealBloc.dart';
import 'package:chifood/bloc/mealBloc/menuEvent.dart';
import 'package:chifood/bloc/restaurantBloc/restaurantBloc.dart';
import 'package:chifood/bloc/restaurantBloc/restaurantEvent.dart';
import 'package:chifood/model/restaurants.dart';
import 'package:chifood/ui/pages/restaurantScreen.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../config.dart';
class RestaurantContentList extends StatefulWidget {
List<Restaurants> restaurantList;
RestaurantContentList(this.restaurantList);
@override
_RestaurantContentListState createState() => _RestaurantContentListState();
}
class _RestaurantContentListState extends State<RestaurantContentList> {
@override
Widget build(BuildContext context) {
return ListView.builder(
itemBuilder: _build,
itemCount: widget.restaurantList.length,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics());
}
Widget _build(BuildContext context, int index) {
Restaurants curRes = widget.restaurantList[index];
return GestureDetector(
onTap: () {
BlocProvider.of<RestaurantBloc>(context)
..add(LoadRestaurantAllInfoEvent(curRes));
BlocProvider.of<MenuBloc>(context).add(LoadMenuEvent());
Navigator.pushNamed(context,'/Restaurant',arguments: RestaurantArg(index%4,curRes));
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
margin: EdgeInsets.only(bottom: 20),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(15.0)),
boxShadow: [
BoxShadow(
color: Color(0xfff4f4f3),
offset: Offset(0.5, 1.5),
spreadRadius: 2.0,
blurRadius: 1.5)
]),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
padding: EdgeInsets.only(bottom: 5.0),
decoration: BoxDecoration(border: Border(bottom: BorderSide())),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
curRes.name,
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 16.0),
),
SizedBox(
height: 5,
),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width*0.7),
child: Text(
curRes.location.address,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontWeight: FontWeight.w600, color: Colors.grey),
),
)
],
),
Container(
height: 50,
width: 50,
padding: EdgeInsets.symmetric(vertical: 10.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
image: DecorationImage(
image: AssetImage('${icon}pizza.png'),
fit: BoxFit.cover)),
)
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Icon(
Icons.star,
color: Colors.orange,
),
Text(curRes.user_rating.aggregate_rating)
],
),
Row(
children: <Widget>[
Icon(Icons.people),
Text(curRes.user_rating.votes)
],
),
Row(
children: <Widget>[
Icon(Icons.attach_money),
Text(curRes.average_cost_for_two.toString())
],
),
],
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/pages/mapSearch.dart | import 'dart:async';
import 'package:chifood/configs.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:search_map_place/search_map_place.dart';
class MapSample extends StatefulWidget {
@override
State<MapSample> createState() => MapSampleState();
}
class MapSampleState extends State<MapSample> {
Completer<GoogleMapController> _mapController = Completer();
LatLng curLocation;
static const CameraPosition _initialCamera = CameraPosition(
target: LatLng(-20.3000, -40.2990),
zoom: 14.0000,
);
final Set<Marker> _markers = {};
Marker MyMarker(){
return Marker(
markerId: MarkerId('onlyId'),
draggable: true,
position: curLocation,
onDragEnd: (value){
}
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
body: Stack(
children: <Widget>[
GoogleMap(
myLocationButtonEnabled: false,
myLocationEnabled: true,
mapType: MapType.normal,
initialCameraPosition: _initialCamera,
onMapCreated: (GoogleMapController controller) {
_mapController.complete(controller);
},
markers: _markers,
),
Positioned(
top: 60,
left: MediaQuery.of(context).size.width * 0.05,
child: Column(
children: <Widget>[
SearchMapPlaceWidget(
apiKey: API_GOOGLE,
onSelected: (place) async {
final geolocation = await place.geolocation;
final GoogleMapController controller = await _mapController.future;
setState(() {
curLocation=geolocation.coordinates;
});
print(geolocation.fullJSON);
_markers.add(MyMarker());
controller.animateCamera(CameraUpdate.newLatLng(geolocation.coordinates));
controller.animateCamera(CameraUpdate.newLatLngBounds(geolocation.bounds, 0));
},
),
Container(
)
],
),
),
],
),
);
}
} | 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/pages/orderConfirmation.dart | import 'package:chifood/ui/pages/home.dart';
import 'package:chifood/ui/pages/order.dart';
import 'package:chifood/ui/widgets/AddressCard.dart';
import 'package:chifood/ui/widgets/paymentCard.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:math' as math;
class OrderConfirmation extends StatefulWidget {
@override
_OrderConfirmationState createState() => _OrderConfirmationState();
}
class _OrderConfirmationState extends State<OrderConfirmation>
with SingleTickerProviderStateMixin {
bool isFront = true;
bool hasHalf = false;
AnimationController _animationController;
Animation<double> frontAnimation;
Animation<double> backAnimation;
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
void initState() {
// TODO: implement initState
super.initState();
_animationController =
new AnimationController(vsync: this, duration: Duration(seconds: 2));
_animationController.addListener(() {
if (_animationController.value > 0.5) {
if (hasHalf == false) {
isFront = !isFront;
}
hasHalf = true;
}
setState(() {});
});
_animationController.addStatusListener((status) {
if (status == AnimationStatus.completed) {
hasHalf = false;
}
});
frontAnimation = Tween(begin: 0.0, end: 0.5).animate(CurvedAnimation(
parent: _animationController,
curve: Interval(0.0, 0.5, curve: Curves.easeIn)));
backAnimation = Tween(begin: 1.5, end: 2.0).animate(CurvedAnimation(
parent: _animationController,
curve: Interval(0.5, 1.0, curve: Curves.easeOut)));
}
void animate() {
_animationController.stop();
_animationController.value = 0;
_animationController.forward();
}
@override
Widget build(BuildContext context) {
var yellow = Container(
color: Theme.of(context).primaryColor,
);
double value = 0;
if (_animationController.status == AnimationStatus.forward) {
if (hasHalf == true) {
value = backAnimation.value;
} else {
value = frontAnimation.value;
}
}
return GestureDetector(
child: AnimatedBuilder(
animation: _animationController,
builder: (context, _) {
return Stack(
children: <Widget>[
yellow,
Transform(
alignment: Alignment.center,
transform: Matrix4.identity() ..setEntry(3, 2, 0.002) ..rotateY(value*math.pi) ,
child:IndexedStack(
index: isFront ? 0 : 1,
children: <Widget>[
PaymentCard(animate),CustomCard(animate)
],
),
)
],
);
},
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/pages/restaurantScreen.dart | import 'dart:async';
import 'package:chifood/bloc/mealBloc/mealBloc.dart';
import 'package:chifood/bloc/mealBloc/menuState.dart';
import 'package:chifood/bloc/orderBloc/orderBloc.dart';
import 'package:chifood/bloc/orderBloc/orderState.dart';
import 'package:chifood/bloc/restaurantBloc/restaurantBloc.dart';
import 'package:chifood/bloc/restaurantBloc/restaurantState.dart';
import 'package:chifood/config.dart';
import 'package:chifood/model/restaurants.dart';
import 'package:chifood/ui/widgets/draggeableCart.dart';
import 'package:chifood/ui/widgets/errorWidget.dart';
import 'package:chifood/ui/widgets/loadingWidget.dart';
import 'package:chifood/ui/widgets/restaurantScrollView.dart';
import 'package:chifood/ui/widgets/restaurantTab.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class RestaurantScreen extends StatefulWidget {
@override
_RestaurantScreenState createState() => _RestaurantScreenState();
}
class _RestaurantScreenState extends State<RestaurantScreen> {
ScrollController _controller;
bool dark = false;
static OverlayEntry entry;
@override
void initState() {
// TODO: implement initState
super.initState();
_controller = new ScrollController();
_controller.addListener(() {
if (_controller.offset > 220) {
dark = true;
setState(() {});
}
if(_controller.offset<=220){
dark = false;
setState(() {});
}
});
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
}
@override
Widget build(BuildContext context) {
RestaurantArg args = ModalRoute.of(context).settings.arguments;
return AnnotatedRegion<SystemUiOverlayStyle>(
value: dark ? SystemUiOverlayStyle.dark : SystemUiOverlayStyle.light,
child: SafeArea(
top: false,
bottom: false,
child: Scaffold(
body:BlocBuilder<MenuBloc,MenuState>(
builder: (BuildContext context,MenuState state){
if(state is LoadMenuState){
return Stack(
children: <Widget>[
RestaurantScrollView(arg: args,controller: _controller,state: state,),
BlocBuilder<OrderBloc,OrderState>(
builder: (BuildContext context,OrderState orderState){
if(orderState is OrderListState){
return AppFloatBox(orderState.orderList.length);
}else{
return SizedBox(width: 1,);
}
},
)
],
);
}else if(state is LoadingMenuState){
return MyLoading();
}
return MyErrorWidget();
},
),
),
),
);
}
}
class RestaurantArg {
final int id;
final Restaurants restaurants;
RestaurantArg(this.id, this.restaurants);
}
class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
final Widget child;
StickyTabBarDelegate({@required this.child});
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
return this.child;
}
@override
double get maxExtent => 70;
@override
double get minExtent => 70;
@override
bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
return true;
}
} | 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/pages/orderFinish.dart | import 'package:chifood/ui/widgets/animatedOrder.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class OrderFinish extends StatefulWidget {
@override
_OrderFinishState createState() => _OrderFinishState();
}
class _OrderFinishState extends State<OrderFinish> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.only(top: 100.0, left: 20, right: 20),
child: Column(
children: <Widget>[
Text(
'Thank you',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 26.0),
),
SizedBox(
height: 30.0,
),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width*0.7),
child: Text(
'Your order has been successfully added',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.grey, fontSize: 16.0),
),
),
SizedBox(height: 30,),
AnimatedOrder(),
SizedBox(
height: 30.0,
),
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.6),
child: RichText(
text: TextSpan(
text: 'Estimated Delivery in ',
style: TextStyle(color: Colors.grey),
children: [
TextSpan(
text: '20 minutes',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black)),
]),
),
),
Text(''),
SizedBox(
height: 40,
),
Column(
children: <Widget>[
Text('6 Items will be delivered to'),
Text('516 Ablert Street')
],
),
SizedBox(
height: 50.0,
),
Container(
width: MediaQuery.of(context).size.width * 0.85,
padding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0),
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.all(Radius.circular(20.0)),
boxShadow: [
BoxShadow(
color: Color(0xffeeedee),
offset: Offset(1.0, 2.7),
blurRadius: 1.0,
spreadRadius: 2.0)
]),
child: Text(
'BACK TO HOME',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16.0),
textAlign: TextAlign.center,
),
),
SizedBox(
height: 50.0,
),
Container(
width: MediaQuery.of(context).size.width * 0.85,
padding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
boxShadow: [
BoxShadow(
color: Color(0xffeeedee), offset: Offset(0.7, 1.2))
]),
child: Text(
'Order List',
textAlign: TextAlign.center,
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/pages/signUp.dart |
import 'package:chifood/bloc/authBloc/AuthBloc.dart';
import 'package:chifood/bloc/authBloc/AuthEvent.dart';
import 'package:chifood/bloc/authBloc/AuthState.dart';
import 'package:chifood/configs.dart';
import 'package:chifood/model/baseUser.dart';
import 'package:chifood/model/locationLocation.dart';
import 'package:chifood/service/apiService.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:form_field_validator/form_field_validator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_place_picker/google_maps_place_picker.dart';
import 'package:oktoast/oktoast.dart';
import '../../config.dart';
class SignUpScreen extends StatefulWidget {
SignUpScreen(this.client);
final Dio client;
@override
_SignUpScreenState createState() => _SignUpScreenState();
}
class _SignUpScreenState extends State<SignUpScreen> {
bool lightTheme = true;
Color currentColor = Colors.limeAccent;
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _usernameController = TextEditingController();
LocationLocation locationInfo;
String primary;
BaseUser user;
void _checkAndSubmit(){
if(FocusScope.of(context).hasFocus){
FocusScope.of(context).unfocus();
}
if(!isPopulated||locationInfo==null){
_showToast();
return;
}
user=BaseUser((a)=>a ..long=locationInfo.longitude ..lat=locationInfo.latitude ..username=_usernameController.text
..primaryLocation=primary
..cityId=locationInfo.city_id ..entityId=locationInfo.entity_id ..entityType=locationInfo.entity_type ..foodie_color=currentColor.value.toString()
);
print(user);
BlocProvider.of<AuthenticationBloc>(context).add(SignUpEvent(userInfo: user,email: _emailController.text,password: _passwordController.text));
}
bool get isPopulated =>
_emailController.text.isNotEmpty && _passwordController.text.isNotEmpty&&_usernameController.text.isNotEmpty;
PickResult selectedPlace;
void changeColor(Color color) {
setState(() => currentColor = color);
Navigator.pop(context);
}
void _showToast(){
showToast('missing fields',duration: const Duration(milliseconds: 1500),
position: ToastPosition.center,
backgroundColor: Colors.redAccent.withOpacity(0.8),
radius: 3.0,
textStyle: const TextStyle(fontSize: 30.0),);
}
@override
Widget build(BuildContext context) {
return BlocListener<AuthenticationBloc,AuthenticationState>(
listener: (BuildContext context,AuthenticationState state){
if(state is Authenticated){
Navigator.of(context).popAndPushNamed('/HomePage');
}else if(state is Authenticating){
showToast('loading',duration: const Duration(seconds: 2),position: ToastPosition.center);
}
},
child: Scaffold(
body: GestureDetector(
onTap: (){
FocusScope.of(context).unfocus();
},
child: SafeArea(
top: false,
bottom: false,
child: Stack(
children: <Widget>[
Image.asset(
'${asset}signin.jpeg',
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
padding: EdgeInsets.all(30.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(30.0),
topRight: Radius.circular(30.0))),
//height: MediaQuery.of(context).size.height * 0.7,
child: SingleChildScrollView(
reverse: true,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Column(
children: <Widget>[
Container(
padding:const EdgeInsets.symmetric(horizontal: 10.0,vertical: 5.0),
decoration:BoxDecoration(
borderRadius: const BorderRadius.all( Radius.circular(15.0)),
border: Border.all(color: Theme.of(context).primaryColor)
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'Set Your Favorite Color:',
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 17.0),
),
GestureDetector(
child: Container(
width: 30,
height: 30,
decoration: BoxDecoration(
color: currentColor,
shape: BoxShape.circle),
),
onTap: () {
showDialog<dynamic>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title:const Text('Select a color'),
content: SingleChildScrollView(
child: BlockPicker(
pickerColor: currentColor,
onColorChanged: changeColor,
),
),
);
},
);
},
)
],
),
),
const SizedBox(height: 20,),
GestureDetector(
onTap: () => Navigator.push<dynamic>(
context,
MaterialPageRoute<dynamic>(
builder: (BuildContext context) {
return PlacePicker(
apiKey: API_GOOGLE,
initialPosition:
selectedPlace!=null?LatLng(selectedPlace.geometry.location.lat,selectedPlace.geometry.location.lng): LatLng(-33.8567844, 151.213108),
useCurrentLocation: true,
//usePlaceDetailSearch: true,
onPlacePicked: (result) async {
selectedPlace = result;
Navigator.of(context).pop();
primary=selectedPlace.formattedAddress;
locationInfo=await getGeoInfoFromZomato(widget.client, result.formattedAddress, result.geometry.location.lat, result.geometry.location.lng);
setState(() {});
},
//forceSearchOnZoomChanged: true,
//automaticallyImplyAppBarLeading: false,
autocompleteLanguage: "en",
region: 'ca',
);
},
),
),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Theme.of(context).primaryColor),
borderRadius: BorderRadius.all(Radius.circular(15.0))
),
padding: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 5.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Icon(Icons.location_on),
SizedBox(width: 10,),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width*0.7),
child: Text(
selectedPlace == null
? "Input your deliver address"
: selectedPlace.formattedAddress ?? "",
overflow: TextOverflow.ellipsis,
softWrap: true,
)),
],
),
),
),],
),
SizedBox(
height: 50,
),
Form(
autovalidate: true,
child: Column(
children: <Widget>[
TextFormField(
controller: _usernameController,
validator: RequiredValidator(errorText: 'need username'),
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(15), //边角为30
),
borderSide: BorderSide(
color: Colors.amber, //边线颜色为黄色
width: 2, //边线宽度为2
),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.green, //边框颜色为绿色
width: 2, //宽度为5
)),
labelText: "Username",
// errorText: "errorText",
hintText: "Input your username",
prefixIcon: Icon(Icons.person_outline),
),
),
SizedBox(height: 20,),
TextFormField(
controller: _emailController,
validator: EmailValidator(errorText: 'input valid email'),
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(15), //边角为30
),
borderSide: BorderSide(
color: Colors.amber, //边线颜色为黄色
width: 2, //边线宽度为2
),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.green, //边框颜色为绿色
width: 2, //宽度为5
)),
labelText: "Email",
// errorText: "errorText",
hintText: "Input your email",
prefixIcon: Icon(Icons.email),
),
),
SizedBox(height: 20,),
TextFormField(
controller: _passwordController,
obscureText: true,
validator: RequiredValidator(errorText: 'Need password'),
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(15), //边角为30
),
borderSide: BorderSide(
color: Colors.amber, //边线颜色为黄色
width: 2, //边线宽度为2
),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.green, //边框颜色为绿色
width: 2, //宽度为5
)),
labelText: "Password",
// errorText: "errorText",
hintText: "Input your password",
prefixIcon: Icon(Icons.lock_open),
),
),
SizedBox(height: 20,),
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
GestureDetector(
onTap: ()=>Navigator.of(context).pop(),
child: Container(
decoration:BoxDecoration(
color: Theme.of(context).primaryColor,
shape: BoxShape.circle,
),
padding:EdgeInsets.all(20.0),
child: Icon(Icons.arrow_back),
),
),
GestureDetector(
onTap: _checkAndSubmit,
child: Container(
decoration:BoxDecoration(
color: Theme.of(context).primaryColor,
shape: BoxShape.circle,
),
padding:EdgeInsets.all(20.0),
child: Icon(Icons.arrow_forward),
)
),
],
)
],
),
)
),
)
],
)),
),
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/pages/order.dart | import 'package:chifood/bloc/orderBloc/orderBloc.dart';
import 'package:chifood/bloc/orderBloc/orderState.dart';
import 'package:chifood/config.dart';
import 'package:chifood/model/orderItem.dart';
import 'package:chifood/ui/widgets/couponSliverOrderList.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
class OrderPage extends StatefulWidget {
final void Function() callback;
OrderPage(this.callback);
@override
_OrderPageState createState() => _OrderPageState();
}
class _OrderPageState extends State<OrderPage> {
@override
Widget build(BuildContext context) {
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.dark ,
child:Scaffold(
backgroundColor: Color(0xfff9f8f8),
body: SafeArea(
top: false,
bottom: false,
child: Container(
height: MediaQuery
.of(context)
.size
.height,
child:BlocBuilder<OrderBloc,OrderState>(
builder:(BuildContext context,OrderState state){
if(state is OrderListState){
List<List<OrderItem>> itemList=state.orderList;
return Stack(
children: <Widget>[
Column(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height*0.13,
padding: EdgeInsets.only(
left: 30.0, right: 30, top: 50.0, bottom: 20),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(color: Color(0xffebebea),
blurRadius: 2.0,
spreadRadius: 1.0,
offset: Offset(2.0, 2.0))
],
//border: Border(bottom: BorderSide(color: Color(0xffb0b1b0)))
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(15.0),
bottomRight: Radius.circular(15.0))
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
GestureDetector(
onTap:(){
Navigator.of(context).pop();
},
child: Icon(Icons.arrow_back_ios),
),
Text('Order (${itemList.length})', style: TextStyle(fontWeight: FontWeight
.bold, fontSize: 20.0),),
GestureDetector(
onTap: () {
widget.callback();
},
child: Container(
padding: EdgeInsets.all(5.0),
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.all(
Radius.circular(5.0)),
),
child: Icon(Icons.person),
),
)
],
),
),
CouponOrderList(itemList),
],
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
height: 180,
padding: EdgeInsets.symmetric(
vertical: 30.0, horizontal: 30.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topRight: Radius.circular(15.0),
topLeft: Radius.circular(15.0)),
boxShadow: [
BoxShadow(color: Color(0xffebebea),
blurRadius: 2.0,
spreadRadius: 2.0,
offset: Offset(2.0, -2.0))
]
//border: Border(top: BorderSide(color: Color(0xffb0b1b0)))
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Discount', style: TextStyle(
fontWeight: FontWeight.w600, fontSize: 14.0),),
Text('\$ 10.0', style: TextStyle(
fontWeight: FontWeight.w600, fontSize: 14.0),)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Total', style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 27.0),),
Text('\$ 100.0', style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 27.0),)
],
),
GestureDetector(
onTap: ()=>Navigator.of(context).pushNamed('/OrderConfirm'),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
width: MediaQuery
.of(context)
.size
.width * 0.82,
padding: EdgeInsets.symmetric(
horizontal: 10.0, vertical: 15.0),
decoration: BoxDecoration(
color: Theme
.of(context)
.primaryColor,
borderRadius: BorderRadius.all(
Radius.circular(10.0)),
boxShadow: [
BoxShadow(
color: Color(0xffebebea),
blurRadius: 1.0,
spreadRadius: 2.0,
offset: Offset(1.0, 1.0)
)
]
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Confirm Order', style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17.0),),
Icon(Icons.add_shopping_cart)
],
),
)
],
),
)
],
),
),
),
],
);
}
return Stack(
children: <Widget>[
Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
padding: EdgeInsets.only(
left: 30.0, right: 30, top: 50.0, bottom: 20),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(color: Color(0xffebebea),
blurRadius: 2.0,
spreadRadius: 1.0,
offset: Offset(2.0, 2.0))
],
//border: Border(bottom: BorderSide(color: Color(0xffb0b1b0)))
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(15.0),
bottomRight: Radius.circular(15.0))
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
GestureDetector(
onTap:(){
Navigator.of(context).pop();
},
child: Icon(Icons.arrow_back_ios),
),
Text('Order ', style: TextStyle(fontWeight: FontWeight
.bold, fontSize: 20.0),),
GestureDetector(
onTap: () {
widget.callback();
},
child: Container(
padding: EdgeInsets.all(5.0),
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.all(
Radius.circular(5.0)),
),
child: Icon(Icons.person),
),
)
],
),
),
],
),
Center(
child: Image.asset('${asset}nullOrder.png'),
)
],
);
}
) ,
),
),
));
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/pages/splash.dart | import 'dart:async';
import 'package:chifood/bloc/authBloc/AuthBloc.dart';
import 'package:chifood/bloc/authBloc/AuthEvent.dart';
import 'package:chifood/bloc/authBloc/AuthState.dart';
import 'package:chifood/bloc/implementation/FireAuthRepo.dart';
import 'package:chifood/bloc/selectionBloc/selectionBloc.dart';
import 'package:chifood/bloc/selectionBloc/selectionEvent.dart';
import 'package:chifood/bloc/selectionBloc/selectionState.dart';
import 'package:chifood/ui/pages/home.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
class SplashPage extends StatefulWidget {
FireAuthRepo _firebaseAuth;
SplashPage(this._firebaseAuth);
@override
_SplashPageState createState() => _SplashPageState();
}
class _SplashPageState extends State<SplashPage> {
int _count=5;
bool jump=false;
void initState() {
// TODO: implement initState
super.initState();
_configureCountDown();
}
@override
Widget build(BuildContext context) {
return BlocListener<AuthenticationBloc,AuthenticationState>(
listener: (context,state){
if(state is Authenticated ){
BlocProvider.of<SelectionBloc>(context)
..add(LoadAllBaseChoice(city_id: state.user.cityId,lat: state.user.lat,lon: state.user.long,entity_id: state.user.entityId.toString(),entity_type: state.user.entityType));
Future.delayed(Duration(seconds: 5),()=>Navigator.of(context).popAndPushNamed('/HomePage'));
}else if(state is Unauthenticated){
Future.delayed(Duration(seconds: 5),()=>Navigator.of(context).popAndPushNamed('/setUp'));
}
},
child: Scaffold(
body: _buildDefaultLaunchImage(),
),
);
}
void _switchRootView(){
// Navigator.pushAndRemoveUntil(
//// context,
//// MaterialPageRoute(builder: (BuildContext context) => HomePage()),
//// ModalRoute.withName('/'),
//// );
}
@override
void _configureCountDown() {
Timer.periodic(Duration(seconds: 1),(tick){
if(jump){
tick.cancel();
// Navigator.pushAndRemoveUntil(
// context,
// MaterialPageRoute(builder: (BuildContext context) => HomePage()),
// ModalRoute.withName('/'),
// );
}
if (_count == 0) {
tick.cancel();
} else {
_count--;
setState(() {
});
}
});
}
Widget _buildDefaultLaunchImage() {
return Stack(
children: <Widget>[
Container(
width: double.maxFinite,
height: double.maxFinite,
child: Center(
child: Text('Chi',style: TextStyle(color: Colors.white,fontSize: 42.0,fontWeight: FontWeight.bold),),
),
decoration: BoxDecoration(
// 这里设置颜色 跟启动页一致的背景色,以免发生白屏闪烁
color: Color.fromRGBO(0, 10, 24, 1),
image: DecorationImage(
// 注意:启动页 别搞太大 以免加载慢
image: AssetImage('assets/img/launch.jpeg'),
fit: BoxFit.cover,
),
),
),
Positioned(
top: 40,
right: 10,
child: GestureDetector(
onTap: ()=>setState((){jump=true;}),
child: Container(
padding: EdgeInsets.symmetric(horizontal: 10.0,vertical: 5.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(15.0)),
border: Border.all(color: Colors.white)
),
child: Text('Skip $_count',style: TextStyle(color: Colors.white),),
),
),
)
],
);
}
Widget _buildNewFeatureWidget() {
return Swiper(
itemCount: 3,
loop: false,
itemBuilder: (_, index) {
final String name =
'assets/img/guide${index + 1}.jpeg';
Widget widget = Image.asset(
name,
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
);
if (index == 2) {
return Stack(
children: <Widget>[
widget,
Positioned(
child: InkWell(
child: Container(
padding: EdgeInsets.symmetric(vertical: 5.0,horizontal: 7.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10.0))
),
child: Text('Skip',textAlign: TextAlign.center,),
),
//onTap: _switchRootView,
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
focusColor: Colors.transparent,
),
right: 10,
bottom: 55.0,
),
],
);
} else {
return widget;
}
},
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/pages/restaurantFilterPage.dart | import 'package:chifood/bloc/authBloc/AuthBloc.dart';
import 'package:chifood/bloc/authBloc/AuthState.dart';
import 'package:chifood/bloc/restaurantListBloc/restaurantListBloc.dart';
import 'package:chifood/bloc/restaurantListBloc/restaurantListEvent.dart';
import 'package:chifood/bloc/restaurantListBloc/restaurantListState.dart';
import 'package:chifood/bloc/selectionBloc/selectionBloc.dart';
import 'package:chifood/bloc/selectionBloc/selectionEvent.dart';
import 'package:chifood/bloc/selectionBloc/selectionState.dart';
import 'package:chifood/ui/widgets/FilterRestrauant.dart';
import 'package:chifood/ui/widgets/backdropList.dart';
import 'package:chifood/ui/widgets/dropdownController.dart';
import 'package:chifood/ui/widgets/dropdownHeader.dart';
import 'package:chifood/ui/widgets/dropdownMenu.dart';
import 'package:chifood/ui/widgets/errorWidget.dart';
import 'package:chifood/ui/widgets/loadingWidget.dart';
import 'package:chifood/ui/widgets/restaurantContentList.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'home.dart';
class RestaurantFilterPage extends StatefulWidget {
@override
_RestaurantFilterPageState createState() => _RestaurantFilterPageState();
}
class _RestaurantFilterPageState extends State<RestaurantFilterPage> {
GlobalKey _stackKey = GlobalKey();
GZXDropdownMenuController _dropdownMenuController =
GZXDropdownMenuController();
List<GZXDropDownHeaderItem> selctionList = [
GZXDropDownHeaderItem('Distance'),
GZXDropDownHeaderItem('Cuisine'),
GZXDropDownHeaderItem('Category')
];
SortCondition _selectCateSortCondition;
SortCondition _selectCuisineSortCondition;
SortCondition _selectDistanceSortCondition;
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
bottom: false,
child: BlocBuilder<AuthenticationBloc,AuthenticationState>(
builder: (BuildContext context,AuthenticationState authstate){
if(authstate is Authenticated){
return BlocBuilder<SelectionBloc, SelectionState>(
builder: (BuildContext context, SelectionState selectionState) {
if (selectionState is BaseChoice) {
List<ItemClass> cateString = selectionState.categoryList
.map((each) => ItemClass(each.id.toString(), each.name))
.toList();
List<ItemClass> cusString = selectionState.cuisineList
.map((each) =>
ItemClass(each.cuisine_id.toString(), each.cuisine_name))
.toList();
List<ItemClass> disString = [
ItemClass('1', '500'),
ItemClass('2', '1000'),
ItemClass('3', '1500')
];
return Stack(
key: _stackKey,
children: <Widget>[
Positioned(
top: 0,
left: 0,
right: 0,
child: GestureDetector(
onTap: ()=>Navigator.of(context).pushNamed('/Search',arguments: SearchArg(authstate.user.entityId.toString(),
authstate.user.entityType,authstate.user.lat,authstate.user.long)),
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
height: 40,
padding: EdgeInsets.only(left: 10,right: 20),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(15.0)),
color: Colors.grey.withOpacity(0.4),
border: Border.all(color: Color(0xffe5e5e5))
),
child: Row(
children: <Widget>[
Icon(Icons.search),
Text('Search Restaurants Nearby')
],
),
),
GestureDetector(child: Text('Cancel'),onTap: ()=>Navigator.of(context).pop(),)
],
),
),
),
),
Positioned(
top: 50,
left: 0,
right: 0,
child: GZXDropDownHeader(stackKey: _stackKey,controller: _dropdownMenuController,
color: Colors.white,
items: selctionList,
),
),
Positioned(
top: 100,
left: 10,
right: 10,
bottom: 0,
child: SingleChildScrollView(
child:
BlocBuilder<RestaurantListBloc, RestaurantListState>(
builder: (BuildContext context,
RestaurantListState resstate) {
if (resstate is LoadedFilterRestaurantListState) {
return RestaurantContentList(
resstate.restaurantList,
);
} else if (resstate is LoadingRestaurantListState) {
return MyLoading();
} else if (resstate is LoadFailRestaurantListState ||
selectionState is LoadSelectionFail) {
return MyErrorWidget();
} else {
return RestaurantContentList(
selectionState.locationDetail,
);
}
},
),
),
),
BlocBuilder<AuthenticationBloc, AuthenticationState>(
builder:
(BuildContext context, AuthenticationState authstate) {
if (authstate is Authenticated) {
return GZXDropDownMenu(
topHeight: 100,
// controller用于控制menu的显示或隐藏
controller: _dropdownMenuController,
// 下拉菜单显示或隐藏动画时长
animationMilliseconds: 300,
// 下拉后遮罩颜色
// maskColor: Theme.of(context).primaryColor.withOpacity(0.5),
// maskColor: Colors.red.withOpacity(0.5),
// 下拉菜单,高度自定义,你想显示什么就显示什么,完全由你决定,你只需要在选择后调用_dropdownMenuController.hide();即可
menus: [
GZXDropdownMenuBuilder(
dropDownHeight: 40 * 4.0,
dropDownWidget: ConditionListWidget(
turnSortCondition(disString), (value) {
_selectDistanceSortCondition = value;
selctionList[0] = value.name == 'All'
? GZXDropDownHeaderItem('Distance')
: GZXDropDownHeaderItem(value.name);
setState(() {});
BlocProvider.of<RestaurantListBloc>(context)
.add(FilterRestaurantListEvent(
entity_id: authstate.user.entityId
.toString(),
entity_type:
authstate.user.entityType,
category:
_selectCateSortCondition?.id,
cuisines:
_selectCuisineSortCondition?.id,
lat: authstate.user.lat,
lon: authstate.user.long,
radius: _selectDistanceSortCondition
?.name));
_dropdownMenuController.hide();
}, _selectDistanceSortCondition)),
GZXDropdownMenuBuilder(
dropDownHeight: 320.0,
dropDownWidget: ConditionListWidget(
turnSortCondition(cusString), (value) {
_selectCuisineSortCondition = value;
selctionList[1] = value.name == 'All'
? GZXDropDownHeaderItem('Cuisine')
: GZXDropDownHeaderItem(value.name);
setState(() {});
BlocProvider.of<RestaurantListBloc>(context)
.add(FilterRestaurantListEvent(
entity_id: authstate.user.entityId
.toString(),
entity_type:
authstate.user.entityType,
category:
_selectCateSortCondition?.id,
cuisines:
_selectCuisineSortCondition?.id,
lat: authstate.user.lat,
lon: authstate.user.long,
radius: _selectDistanceSortCondition
?.name));
_dropdownMenuController.hide();
}, _selectCuisineSortCondition)),
GZXDropdownMenuBuilder(
dropDownHeight: 320.0,
dropDownWidget: ConditionListWidget(
turnSortCondition(cateString), (value) {
_selectCateSortCondition =
value.name == 'All' ? null : value;
selctionList[2] = value.name == 'All'
? GZXDropDownHeaderItem('Category')
: GZXDropDownHeaderItem(value.name);
setState(() {});
BlocProvider.of<RestaurantListBloc>(context)
.add(FilterRestaurantListEvent(
entity_id: authstate.user.entityId
.toString(),
entity_type:
authstate.user.entityType,
category:
_selectCateSortCondition?.id,
cuisines:
_selectCuisineSortCondition?.id,
lat: authstate.user.lat,
lon: authstate.user.long,
radius: _selectDistanceSortCondition
?.name));
_dropdownMenuController.hide();
}, _selectCateSortCondition))
],
);
} else {
return GZXDropDownMenu(
// controller用于控制menu的显示或隐藏
controller: _dropdownMenuController,
// 下拉菜单显示或隐藏动画时长
animationMilliseconds: 300,
// 下拉后遮罩颜色
// maskColor: Theme.of(context).primaryColor.withOpacity(0.5),
// maskColor: Colors.red.withOpacity(0.5),
// 下拉菜单,高度自定义,你想显示什么就显示什么,完全由你决定,你只需要在选择后调用_dropdownMenuController.hide();即可
menus: [
GZXDropdownMenuBuilder(
dropDownHeight: 100,
dropDownWidget: Container(
child:
Text('No location detail could be found'),
)),
GZXDropdownMenuBuilder(
dropDownHeight: 100,
dropDownWidget: Container(
child:
Text('No cuisine detail could be found'),
)),
GZXDropdownMenuBuilder(
dropDownHeight: 100,
dropDownWidget: Container(
child:
Text('No category detail could be found'),
))
],
);
}
},
),
],
);
} else {
return MyLoading();
}
},
);
}
else{
return MyErrorWidget();
}
},
),
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/pages/searchPage.dart | import 'dart:async';
import 'package:chifood/bloc/mealBloc/mealBloc.dart';
import 'package:chifood/bloc/mealBloc/menuEvent.dart';
import 'package:chifood/bloc/restaurantBloc/restaurantBloc.dart';
import 'package:chifood/bloc/restaurantBloc/restaurantEvent.dart';
import 'package:chifood/model/baseUser.dart';
import 'package:chifood/model/restaurants.dart';
import 'package:chifood/model/yelpBusiness.dart';
import 'package:chifood/model/yelpReview.dart';
import 'package:chifood/service/apiService.dart';
import 'package:chifood/ui/pages/home.dart';
import 'package:chifood/ui/pages/restaurantScreen.dart';
import 'package:chifood/ui/widgets/getRating.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class CustomSearchPage extends StatefulWidget {
Dio client;
Dio yelpClient;
CustomSearchPage(this.client,this.yelpClient);
@override
_CustomSearchPageState createState() => _CustomSearchPageState();
}
class _CustomSearchPageState extends State<CustomSearchPage> with SingleTickerProviderStateMixin {
List<String> hintList=[
'Search by restaurant name or location','Search by location to find review','Search username'
];
String entity_id;
String entity_type;
String lat;
String long;
TabController _controller;
FocusNode node;
final TextEditingController _searchQuery = TextEditingController();
bool _isSearching = false;
String _error;
List<Restaurants> resRdesult;
List<YelpBusiness> reviewResult;
List<BaseUser> userResult;
int default_int=0;
Timer debounceTimer;
ScrollController _scrollController;
@override
void initState() {
// TODO: implement initState
super.initState();
node=new FocusNode();
_controller=new TabController(length: 3, vsync: this);
_controller.addListener((){
if(_controller.indexIsChanging){
default_int=_controller.index;
setState(() {
});
}
});
_scrollController=new ScrollController();
_scrollController.addListener((){
if(_scrollController.offset>1.0&&node.hasFocus){
node.unfocus();
}
});
_searchQuery.addListener((){
if (debounceTimer != null) {
debounceTimer.cancel();
}
debounceTimer = Timer(Duration(milliseconds: 1500), () {
if (this.mounted) {
performSearch(_searchQuery.text);
}
});
});
}
void performSearch(String query) async {
if (query.isEmpty) {
setState(() {
_isSearching = false;
_error = null;
});
return;
}
setState(() {
_isSearching = true;
_error = null;
});
List<Restaurants> repos;
List<YelpBusiness> reviewrepo;
if(default_int==0){
repos = await searchRestaurants(widget.client, query,entity_id,entity_type);
}else{
reviewrepo=await searchYelpBusiness(widget.yelpClient,term: query,latitude: lat,longitude: long );
}
if (this._searchQuery.text == query && this.mounted) {
setState(() {
_isSearching = false;
if(default_int==0){
if (repos != null) {
repos.removeWhere((each)=>each.name==null);
resRdesult =repos ;
}
}else{
reviewResult=reviewrepo;
}
});
}
}
@override
Widget build(BuildContext context) {
SearchArg a=ModalRoute.of(context).settings.arguments;
setState(() {
entity_id=a.entity_id;
entity_type=a.entity_type;
});
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.dark,
child: Scaffold(
body:SafeArea(
top: true,
bottom: false,
child: Stack(
children: <Widget>[
Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(vertical: 10,horizontal: 15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width*0.75),
child: TextField(
controller: _searchQuery,
focusNode: node,
decoration: InputDecoration(
hintText: hintList[default_int],
hintStyle: TextStyle(fontSize: 14.0,color: Colors.black),
contentPadding: EdgeInsets.symmetric(vertical:0.0,horizontal: 10.0),
filled: true,
focusColor: Colors.white,
suffixIcon: _searchQuery.text.length>0?IconButton(
onPressed: ()=>WidgetsBinding.instance.addPostFrameCallback( (_) => _searchQuery.clear()),
icon: Icon(Icons.cancel,color: Theme.of(context).primaryColor,),
):SizedBox(),
fillColor:node.hasFocus?Colors.white: Color(0xffd3d3d3).withOpacity(0.4),
border: OutlineInputBorder(
gapPadding: 0.0,
borderRadius: const BorderRadius.all(
const Radius.circular(20.0),
),
)
),
),
),
GestureDetector(
onTap: ()=>Navigator.of(context).pop(),
child: Text('Cancel'),
)
],
),
),
Expanded(
child: Column(
children: <Widget>[
SizedBox(height: 10,),
TabBar(
controller: _controller,
tabs: <Widget>[
Tab(child:Row(
children: <Widget>[
Text('Restaurants'), Icon(Icons.apps)
],
) ,),
Tab(child:Row(
children: <Widget>[
Text('Reviews'), Icon(Icons.message)
],
) ,),
Tab(child:Row(
children: <Widget>[
Text('Users'), Icon(Icons.person_outline)
],
) ,),
],
indicatorColor: Colors.orange,
isScrollable: true,
labelColor: Colors.orange,
labelStyle: TextStyle(fontSize: 15.0,fontWeight: FontWeight.w600),
unselectedLabelStyle: TextStyle(fontSize: 15.0,fontWeight: FontWeight.w500),
unselectedLabelColor: Colors.black,
),
Expanded(
child: TabBarView(
controller: _controller,
children: <Widget>[
Container(
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(horizontal: 35.0,vertical: 7.0),
child: Text('Check nearby restaurants',textAlign: TextAlign.center,),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: [
BoxShadow(
color: Color(0xffd3d3d3).withOpacity(0.3),offset: Offset(1.6,1.7),spreadRadius: 2.0,blurRadius: 4.0
),BoxShadow(
color: Color(0xffd3d3d3).withOpacity(0.3),offset: Offset(-1.6,-1.7),spreadRadius: 2.0,blurRadius: 4.0
)
]
),
)
],
),
SizedBox(height: 20,),
Text('Popular Search',style: TextStyle(fontWeight: FontWeight.w700,fontSize: 16.0),textAlign: TextAlign.left,),
SizedBox(height: 10,),
Column(
children: <Widget>[
Container(
padding:EdgeInsets.symmetric(vertical: 10.0),
decoration: BoxDecoration(
border: Border(top: BorderSide(color: Colors.grey.withOpacity(0.3)),bottom: BorderSide(color: Colors.grey.withOpacity(0.3)))
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Chinese Cuisine'),
Text('Japan Cuisine')
],
),
),
Container(
padding:EdgeInsets.symmetric(vertical: 10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Breakfast'),
Text('Bakery')
],
),
),
Container(
padding:EdgeInsets.symmetric(vertical: 10.0),
decoration: BoxDecoration(
border: Border(top: BorderSide(color: Colors.grey.withOpacity(0.3)),bottom: BorderSide(color: Colors.grey.withOpacity(0.3)))
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('BBQ'),
Text('Middle East Cuisine')
],
),
)
],
)
],
),
), Container(), Container(),
],
),
)
],
),
),
],
),
!_isSearching&&_searchQuery.text.length!=0?Positioned(
top: 70,
left: 0,
right: 0,
bottom: 0,
child: default_int==0?restaurantPart():reviewList(),
):SizedBox()
],
),
),
),
);
}
Widget restaurantPart(){
return Container(
color: Colors.white,
child:resRdesult==null?Container(
child: Text('No result found'),
): ListView.builder(itemBuilder: (BuildContext context,int index){
Restaurants res=resRdesult[index];
return GestureDetector(
onTap: (){
BlocProvider.of<RestaurantBloc>(context).add(LoadRestaurantAllInfoEvent(res));
BlocProvider.of<MenuBloc>(context).add(LoadMenuEvent());
Navigator.pushNamed(context,'/Restaurant',arguments: RestaurantArg(index,res));
},
child: Container(
padding: EdgeInsets.symmetric(vertical: 10.0,horizontal: 16.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: Colors.black.withOpacity(0.2)))
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Icon(Icons.store),
SizedBox(width: 10,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(res.name),
Row(
children: <Widget>[
StarRating(rating: double.parse(res.user_rating.aggregate_rating),),
SizedBox(width: 5,),
Text(res.user_rating.votes)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(res.cuisines.split(', ')[0]),
Container(
width: 1,
height: 10,
margin: EdgeInsets.symmetric(horizontal: 5.0),
color: Colors.grey,
),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: 230),
child: Text(res.location.address,overflow: TextOverflow.ellipsis,),
),
],
)
],
)
],
),
),
);
},itemCount: resRdesult?.length,controller: _scrollController,),
);
}
Widget reviewList(){
return Container(
color: Colors.white,
child:reviewResult==null?Container(
child: Text('No result found'),
): ListView.builder(itemBuilder: (BuildContext context,int index){
YelpBusiness curBusiness=reviewResult[index];
return Container(
padding: EdgeInsets.symmetric(vertical: 10.0,horizontal: 16.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: Colors.black.withOpacity(0.2)))
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Icon(Icons.message),
SizedBox(width: 10,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(curBusiness.name),
Row(
children: <Widget>[
StarRating(rating: double.parse(curBusiness.rating.toString()),),
SizedBox(width: 5,),
Text(curBusiness.price)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(curBusiness.alias),
Container(
width: 1,
height: 10,
margin: EdgeInsets.symmetric(horizontal: 5.0),
color: Colors.grey,
),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: 230),
child: Text(curBusiness.location.address1+', '+curBusiness.location.city,overflow: TextOverflow.ellipsis,),
),
],
)
],
)
],
),
);
},itemCount: resRdesult?.length,controller: _scrollController,),
) ;
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/pages/home.dart | import 'package:chifood/bloc/authBloc/AuthBloc.dart';
import 'package:chifood/bloc/authBloc/AuthState.dart';
import 'package:chifood/bloc/orderBloc/orderBloc.dart';
import 'package:chifood/bloc/orderBloc/orderState.dart';
import 'package:chifood/bloc/restaurantListBloc/restaurantListBloc.dart';
import 'package:chifood/bloc/restaurantListBloc/restaurantListEvent.dart';
import 'package:chifood/bloc/restaurantListBloc/restaurantListState.dart';
import 'package:chifood/bloc/selectionBloc/selectionBloc.dart';
import 'package:chifood/bloc/selectionBloc/selectionEvent.dart';
import 'package:chifood/bloc/selectionBloc/selectionState.dart';
import 'package:chifood/model/category.dart';
import 'package:chifood/ui/widgets/CategoryListView.dart';
import 'package:chifood/ui/widgets/FilterRestrauant.dart';
import 'package:chifood/ui/widgets/backdropList.dart';
import 'package:chifood/ui/widgets/draggeableCart.dart';
import 'package:chifood/ui/widgets/dropdownController.dart';
import 'package:chifood/ui/widgets/dropdownHeader.dart';
import 'package:chifood/ui/widgets/dropdownMenu.dart';
import 'package:chifood/ui/widgets/errorWidget.dart';
import 'package:chifood/ui/widgets/filterPanel.dart';
import 'package:chifood/ui/widgets/loadingWidget.dart';
import 'package:chifood/ui/widgets/resSwipe.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage>
with SingleTickerProviderStateMixin {
double appBarAlpha = 0;
var _scaffoldKey = new GlobalKey<ScaffoldState>();
GlobalKey _stackKey = GlobalKey();
List<GZXDropDownHeaderItem> selctionList=[GZXDropDownHeaderItem('Distance'),GZXDropDownHeaderItem('Cuisine'),GZXDropDownHeaderItem('Category')];
ScrollController _scrollViewController;
GZXDropdownMenuController _dropdownMenuController = GZXDropdownMenuController();
SortCondition _selectCateSortCondition;
SortCondition _selectCuisineSortCondition;
SortCondition _selectDistanceSortCondition;
bool showTab=false;
@override
void initState() {
super.initState();
_scrollViewController = ScrollController(initialScrollOffset: 0.0);
_scrollViewController.addListener((){
if(_scrollViewController.offset>585.0&&showTab==false){
showTab=true;
setState(() {
});
}else if(_scrollViewController.offset<585.0&&showTab==true){
showTab=false;
setState(() {
});
}
});
}
@override
void dispose() {
_scrollViewController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocBuilder<AuthenticationBloc,AuthenticationState>(
bloc: BlocProvider.of<AuthenticationBloc>(context),
builder:(BuildContext context,authstate){
if(authstate is Authenticated){
return BlocConsumer<SelectionBloc,SelectionState>(
listener: (context,state){
},
bloc: BlocProvider.of<SelectionBloc>(context),
builder:(BuildContext context,selectionState){
if(selectionState is BaseChoice){
List<ItemClass> cateString=selectionState.categoryList.map((each)=>ItemClass(each.id.toString(),each.name)).toList();
List<ItemClass> cusString=selectionState.cuisineList.map((each)=>ItemClass(each.cuisine_id.toString(),each.cuisine_name)).toList();
List<ItemClass> disString=[ItemClass('1','500'),ItemClass('2','1000'),ItemClass('3','1500')];
return WillPopScope(
onWillPop: () async {
return false;
},
child: Scaffold(
key: _scaffoldKey,
backgroundColor: Colors.white,
body:SafeArea(
top: false,
bottom: false,
child: LayoutBuilder(
builder: (BuildContext context,BoxConstraints constraints){
return Stack(
key: _stackKey,
children: <Widget>[
Column(
children: <Widget>[
Container(
height: 200,
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(30.0),
bottomRight: Radius.circular(30.0))),
child: Container(
margin: EdgeInsets.only(top: 50.0),
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Deliver Address',
style: TextStyle(color: Color(0xff5c331d)),
),
Row(
children: <Widget>[
Text(
authstate.user.primaryLocation.split(",")[0],
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14.0),
),
Icon(
Icons.edit,
color: Colors.grey,
size: 16.0,
)
],
)
],
),
Row(
children: <Widget>[
Container(
padding: EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: Color(0xfff4f4f3),
offset: Offset(0.0, 2.0))
]),
child: GestureDetector(
onTap: ()=>Navigator.of(context).pushNamed('/Search',arguments: SearchArg(authstate.user.entityId.toString(),
authstate.user.entityType,authstate.user.lat,authstate.user.long)),
child: Icon(
Icons.search,
size: 20.0,
),
),
),
SizedBox(
width: 10,
),
GestureDetector(
onTap: ()=>Navigator.of(context).pushNamed('/MyPage'),
child: Container(
padding: EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: Color(0xfff4f4f3),
offset: Offset(0.0, 2.0))
]),
child: Icon(
Icons.person,
size: 20.0,
),
),
)
],
)
],
),
),
),
],
),
Positioned(
top: 100,
left: 0,
right: 0,
bottom: 0,
child:Container(
// margin: EdgeInsets.only(top: 100),
child: SingleChildScrollView(
controller: _scrollViewController,
child:Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Container(
height: 350,
child: ResSwiper(selectionState.geoLocation.nearby_restaurants.toList()),
),
Container(
padding: EdgeInsets.only(top: 20),
color: Colors.white,
child: Column(
children: <Widget>[CategoryList(selectionState.categoryList)],
),
),
BlocBuilder<RestaurantListBloc,RestaurantListState>(
builder: (BuildContext context,RestaurantListState resstate){
if(resstate is LoadedFilterRestaurantListState ){
return RestaurantList(restaurantList: resstate.restaurantList,filterChoice: selctionList,);
}else if(resstate is LoadingRestaurantListState){
return RestaurantList(handler:MyLoading());
}else if(resstate is LoadFailRestaurantListState || selectionState is LoadSelectionFail){
return RestaurantList(handler: MyErrorWidget(),);
}else{
return RestaurantList(restaurantList: selectionState.locationDetail,filterChoice: selctionList,);
}
},
)
],
),
),
),
),
Positioned(
top: 52,
left: 0,
right: 0,
child: showTab?GZXDropDownHeader(stackKey: _stackKey,controller: _dropdownMenuController,
items: selctionList,
):SizedBox(),
),
GZXDropDownMenu(
// controller用于控制menu的显示或隐藏
controller: _dropdownMenuController,
topHeight: 130,
// 下拉菜单显示或隐藏动画时长
animationMilliseconds: 300,
// 下拉菜单,高度自定义,你想显示什么就显示什么,完全由你决定,你只需要在选择后调用_dropdownMenuController.hide();即可
menus: [
GZXDropdownMenuBuilder(
dropDownHeight: 40*4.0,
dropDownWidget: ConditionListWidget(turnSortCondition(disString), (value){
_selectDistanceSortCondition=value;
selctionList[0]=value.name=='All'?GZXDropDownHeaderItem('Distance'):GZXDropDownHeaderItem(value.name);
setState(() {
});
BlocProvider.of<RestaurantListBloc>(context).add(FilterRestaurantListEvent(
entity_id: authstate.user.entityId.toString(),entity_type: authstate.user.entityType,
category:_selectCateSortCondition?.id,cuisines: _selectCuisineSortCondition?.id,
lat: authstate.user.lat,lon: authstate.user.long,radius: _selectDistanceSortCondition?.name
));
_dropdownMenuController.hide();
},_selectDistanceSortCondition)
),
GZXDropdownMenuBuilder(
dropDownHeight:320.0,
dropDownWidget: ConditionListWidget(turnSortCondition(cusString), (value){
_selectCuisineSortCondition=value;
selctionList[1]=value.name=='All'?GZXDropDownHeaderItem('Cuisine'):GZXDropDownHeaderItem(value.name);
setState(() {
});
BlocProvider.of<RestaurantListBloc>(context).add(FilterRestaurantListEvent(
entity_id: authstate.user.entityId.toString(),entity_type: authstate.user.entityType,
category:_selectCateSortCondition?.id,cuisines: _selectCuisineSortCondition?.id,
lat: authstate.user.lat,lon: authstate.user.long,radius: _selectDistanceSortCondition?.name
));
_dropdownMenuController.hide();
},_selectCuisineSortCondition)
),
GZXDropdownMenuBuilder(
dropDownHeight: 320.0,
dropDownWidget: ConditionListWidget(turnSortCondition(cateString), (value){
_selectCateSortCondition=value.name=='All'?null:value;
selctionList[2]=value.name=='All'?GZXDropDownHeaderItem('Category'):GZXDropDownHeaderItem(value.name);
setState(() {
});
BlocProvider.of<RestaurantListBloc>(context).add(FilterRestaurantListEvent(
entity_id: authstate.user.entityId.toString(),entity_type: authstate.user.entityType,
category:_selectCateSortCondition?.id,cuisines: _selectCuisineSortCondition?.id,
lat: authstate.user.lat,lon: authstate.user.long,radius: _selectDistanceSortCondition?.name
));
_dropdownMenuController.hide();
},_selectCateSortCondition)
)
],
),
BlocBuilder<OrderBloc,OrderState>(
builder: (BuildContext context,OrderState orderState){
if(orderState is OrderListState){
return AppFloatBox(orderState.orderList.length);
}else{
return SizedBox(width: 1,);
}
},
)
],
);
},
),
),
),
);
}else{
return Scaffold(
backgroundColor: Colors.white,
body: MyLoading(),
);
}
} ,
);
}
return Scaffold(
body: MyErrorWidget(),
);
},
);
}
}
turnSortCondition(List<ItemClass> items){
List<SortCondition> _brandSortConditions = [];
_brandSortConditions.add(SortCondition(name: 'All', isSelected: true,));
for(ItemClass each in items){
_brandSortConditions.add(SortCondition(name: each.name, isSelected: false,id: each.id));
}
return _brandSortConditions;
}
class SearchArg{
String entity_id;
String entity_type;
String lat;
String lon;
SearchArg(this.entity_id, this.entity_type,lat,lon);
}
class ItemClass {
String id;
String name;
ItemClass(this.id, this.name);
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/pages/myPage.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class MyPage extends StatefulWidget {
@override
_MyPageState createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
leading: Row(children: <Widget>[Icon(Icons.arrow_back_ios),Text('Profile')],),
actions: <Widget>[Icon(Icons.edit)],
),
body: SafeArea(
bottom: false,
child: Container(
padding: EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food/lib/ui | mirrored_repositories/Chi_Food/lib/ui/pages/sign.dart | import 'package:chifood/bloc/authBloc/AuthBloc.dart';
import 'package:chifood/bloc/authBloc/AuthState.dart';
import 'package:chifood/config.dart';
import 'package:chifood/ui/widgets/loginForm.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SignScreen extends StatefulWidget {
@override
_SignScreenState createState() => _SignScreenState();
}
class _SignScreenState extends State<SignScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: GestureDetector(
onTap: (){
FocusScope.of(context).unfocus();
},
child:BlocListener<AuthenticationBloc,AuthenticationState>(
listener: (context,state){
if(state is FailAuthenticated){
Scaffold.of(context)..hideCurrentSnackBar() ..showSnackBar(
SnackBar(
content: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [Text('Login Failure'), Icon(Icons.error)],
),
backgroundColor: Colors.red,
),
);
} else if (state is Authenticated){
Navigator.of(context).popAndPushNamed('/HomePage');
}
},
child: SafeArea(
top: false,
bottom: false,
child: Stack(
children: <Widget>[
Image.asset('${asset}signin.jpeg',fit: BoxFit.cover,width: double.infinity,height: double.infinity,),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
height: MediaQuery.of(context).size.height*0.5,
padding: EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(topLeft: Radius.circular(45.0),topRight: Radius.circular(45.0)),
),
child: Column(
crossAxisAlignment:CrossAxisAlignment.start ,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text("Please Sign In",style: TextStyle(fontWeight: FontWeight.bold),),
LoginForm()
],
),
),
)
],
),
),
)
),
);
}
}
| 0 |
mirrored_repositories/Chi_Food | mirrored_repositories/Chi_Food/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:chifood/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/Flutter-Firebase-TodoApp | mirrored_repositories/Flutter-Firebase-TodoApp/lib/main.dart | import 'package:firebase_app_web/Service/Auth_Service.dart';
import 'package:firebase_app_web/pages/HomePage.dart';
import 'package:firebase_app_web/pages/SignUpPage.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
AuthClass authClass = AuthClass();
Widget currentPage = SignUpPage();
@override
void initState() {
super.initState();
// authClass.signOut();
checkLogin();
}
checkLogin() async {
String tokne = await authClass.getToken();
print("tokne");
if (tokne != null)
setState(() {
currentPage = HomePage();
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: currentPage,
);
}
}
| 0 |
mirrored_repositories/Flutter-Firebase-TodoApp/lib | mirrored_repositories/Flutter-Firebase-TodoApp/lib/Service/Auth_Service.dart | import 'package:firebase_app_web/pages/HomePage.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class AuthClass {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
);
final storage = new FlutterSecureStorage();
Future<void> googleSignIn(BuildContext context) async {
try {
GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
if (googleSignInAccount != null) {
UserCredential userCredential =
await _auth.signInWithCredential(credential);
storeTokenAndData(userCredential);
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (builder) => HomePage()),
(route) => false);
final snackBar =
SnackBar(content: Text(userCredential.user.displayName));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
} catch (e) {
print("here---->");
final snackBar = SnackBar(content: Text(e.toString()));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
}
Future<void> signOut({BuildContext context}) async {
try {
await _googleSignIn.signOut();
await _auth.signOut();
await storage.delete(key: "token");
} catch (e) {
final snackBar = SnackBar(content: Text(e.toString()));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
}
void storeTokenAndData(UserCredential userCredential) async {
print("storing token and data");
await storage.write(
key: "token", value: userCredential.credential.token.toString());
await storage.write(
key: "usercredential", value: userCredential.toString());
}
Future<String> getToken() async {
return await storage.read(key: "token");
}
Future<void> verifyPhoneNumber(
String phoneNumber, BuildContext context, Function setData) async {
PhoneVerificationCompleted verificationCompleted =
(PhoneAuthCredential phoneAuthCredential) async {
showSnackBar(context, "Verification Completed");
};
PhoneVerificationFailed verificationFailed =
(FirebaseAuthException exception) {
showSnackBar(context, exception.toString());
};
PhoneCodeSent codeSent =
(String verificationID, [int forceResnedingtoken]) {
showSnackBar(context, "Verification Code sent on the phone number");
setData(verificationID);
};
PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
(String verificationID) {
showSnackBar(context, "Time out");
};
try {
await _auth.verifyPhoneNumber(
timeout: Duration(seconds: 60),
phoneNumber: phoneNumber,
verificationCompleted: verificationCompleted,
verificationFailed: verificationFailed,
codeSent: codeSent,
codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);
} catch (e) {
showSnackBar(context, e.toString());
}
}
Future<void> signInwithPhoneNumber(
String verificationId, String smsCode, BuildContext context) async {
try {
AuthCredential credential = PhoneAuthProvider.credential(
verificationId: verificationId, smsCode: smsCode);
UserCredential userCredential =
await _auth.signInWithCredential(credential);
storeTokenAndData(userCredential);
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (builder) => HomePage()),
(route) => false);
showSnackBar(context, "logged In");
} catch (e) {
showSnackBar(context, e.toString());
}
}
void showSnackBar(BuildContext context, String text) {
final snackBar = SnackBar(content: Text(text));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
}
| 0 |
mirrored_repositories/Flutter-Firebase-TodoApp/lib | mirrored_repositories/Flutter-Firebase-TodoApp/lib/pages/SignInPage.dart | import 'package:firebase_app_web/Service/Auth_Service.dart';
import 'package:firebase_app_web/pages/SignUpPage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase_auth;
import 'HomePage.dart';
class SignInPage extends StatefulWidget {
SignInPage({Key key}) : super(key: key);
@override
_SignInPageState createState() => _SignInPageState();
}
class _SignInPageState extends State<SignInPage> {
firebase_auth.FirebaseAuth firebaseAuth = firebase_auth.FirebaseAuth.instance;
TextEditingController _emailController = TextEditingController();
TextEditingController _pwdController = TextEditingController();
bool circular = false;
AuthClass authClass = AuthClass();
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
color: Colors.black,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Sign In",
style: TextStyle(
fontSize: 35,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
SizedBox(
height: 20,
),
buttonItem("assets/google.svg", "Continue with Google", 25, () {
authClass.googleSignIn(context);
}),
SizedBox(
height: 15,
),
buttonItem("assets/phone.svg", "Continue with Mobile", 30, () {}),
SizedBox(
height: 18,
),
Text(
"Or",
style: TextStyle(color: Colors.white, fontSize: 18),
),
SizedBox(
height: 18,
),
textItem("Email....", _emailController, false),
SizedBox(
height: 15,
),
textItem("Password...", _pwdController, true),
SizedBox(
height: 40,
),
colorButton(),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"If you don't have an Account? ",
style: TextStyle(
color: Colors.white,
fontSize: 16,
),
),
InkWell(
onTap: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (builder) => SignUpPage()),
(route) => false);
},
child: Text(
"SignUp",
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
],
),
SizedBox(
height: 10,
),
Text(
"Forgot Password?",
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
);
}
Widget colorButton() {
return InkWell(
onTap: () async {
try {
firebase_auth.UserCredential userCredential =
await firebaseAuth.signInWithEmailAndPassword(
email: _emailController.text, password: _pwdController.text);
print(userCredential.user.email);
setState(() {
circular = false;
});
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (builder) => HomePage()),
(route) => false);
} catch (e) {
final snackbar = SnackBar(content: Text(e.toString()));
ScaffoldMessenger.of(context).showSnackBar(snackbar);
setState(() {
circular = false;
});
}
},
child: Container(
width: MediaQuery.of(context).size.width - 100,
height: 60,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
gradient: LinearGradient(colors: [
Color(0xfffd746c),
Color(0xffff9068),
Color(0xfffd746c)
]),
),
child: Center(
child: circular
? CircularProgressIndicator()
: Text(
"Sign In",
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
),
),
);
}
Widget buttonItem(
String imagepath, String buttonName, double size, Function onTap) {
return InkWell(
onTap: onTap,
child: Container(
width: MediaQuery.of(context).size.width - 60,
height: 60,
child: Card(
color: Colors.black,
elevation: 8,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
side: BorderSide(
width: 1,
color: Colors.grey,
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SvgPicture.asset(
imagepath,
height: size,
width: size,
),
SizedBox(
width: 15,
),
Text(
buttonName,
style: TextStyle(
color: Colors.white,
fontSize: 17,
),
),
],
),
),
),
);
}
Widget textItem(
String labeltext, TextEditingController controller, bool obscureText) {
return Container(
width: MediaQuery.of(context).size.width - 70,
height: 55,
child: TextFormField(
controller: controller,
obscureText: obscureText,
style: TextStyle(
fontSize: 17,
color: Colors.white,
),
decoration: InputDecoration(
labelText: labeltext,
labelStyle: TextStyle(
fontSize: 17,
color: Colors.white,
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(
width: 1.5,
color: Colors.amber,
),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(
width: 1,
color: Colors.grey,
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Firebase-TodoApp/lib | mirrored_repositories/Flutter-Firebase-TodoApp/lib/pages/PhoneAuth.dart | import 'dart:async';
import 'package:firebase_app_web/Service/Auth_Service.dart';
import 'package:flutter/material.dart';
import 'package:otp_text_field/otp_field.dart';
import 'package:otp_text_field/otp_field_style.dart';
import 'package:otp_text_field/style.dart';
class PhoneAuthPage extends StatefulWidget {
PhoneAuthPage({Key key}) : super(key: key);
@override
_PhoneAuthPageState createState() => _PhoneAuthPageState();
}
class _PhoneAuthPageState extends State<PhoneAuthPage> {
int start = 30;
bool wait = false;
String buttonName = "Send";
TextEditingController phoneController = TextEditingController();
AuthClass authClass = AuthClass();
String verificationIdFinal = "";
String smsCode = "";
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black87,
appBar: AppBar(
backgroundColor: Colors.black87,
title: Text(
"SignUp",
style: TextStyle(color: Colors.white, fontSize: 24),
),
centerTitle: true,
),
body: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 120,
),
textField(),
SizedBox(
height: 30,
),
Container(
width: MediaQuery.of(context).size.width - 30,
child: Row(
children: [
Expanded(
child: Container(
height: 1,
color: Colors.grey,
margin: EdgeInsets.symmetric(horizontal: 12),
),
),
Text(
"Enter 6 digit OTP",
style: TextStyle(fontSize: 16, color: Colors.white),
),
Expanded(
child: Container(
height: 1,
color: Colors.grey,
margin: EdgeInsets.symmetric(horizontal: 12),
),
),
],
),
),
SizedBox(
height: 30,
),
otpField(),
SizedBox(
height: 40,
),
RichText(
text: TextSpan(
children: [
TextSpan(
text: "Send OTP again in ",
style: TextStyle(fontSize: 16, color: Colors.yellowAccent),
),
TextSpan(
text: "00:$start",
style: TextStyle(fontSize: 16, color: Colors.pinkAccent),
),
TextSpan(
text: " sec ",
style: TextStyle(fontSize: 16, color: Colors.yellowAccent),
),
],
)),
SizedBox(
height: 150,
),
InkWell(
onTap: () {
authClass.signInwithPhoneNumber(
verificationIdFinal, smsCode, context);
},
child: Container(
height: 60,
width: MediaQuery.of(context).size.width - 60,
decoration: BoxDecoration(
color: Color(0xffff9601),
borderRadius: BorderRadius.circular(15)),
child: Center(
child: Text(
"Lets Go",
style: TextStyle(
fontSize: 17,
color: Color(0xfffbe2ae),
fontWeight: FontWeight.w700),
),
),
),
)
],
),
),
),
);
}
void startTimer() {
const onsec = Duration(seconds: 1);
Timer _timer = Timer.periodic(onsec, (timer) {
if (start == 0) {
setState(() {
timer.cancel();
wait = false;
});
} else {
setState(() {
start--;
});
}
});
}
Widget otpField() {
return OTPTextField(
length: 6,
width: MediaQuery.of(context).size.width - 34,
fieldWidth: 58,
otpFieldStyle: OtpFieldStyle(
backgroundColor: Color(0xff1d1d1d),
borderColor: Colors.white,
),
style: TextStyle(fontSize: 17, color: Colors.white),
textFieldAlignment: MainAxisAlignment.spaceAround,
fieldStyle: FieldStyle.underline,
onCompleted: (pin) {
print("Completed: " + pin);
setState(() {
smsCode = pin;
});
},
);
}
Widget textField() {
return Container(
width: MediaQuery.of(context).size.width - 40,
height: 60,
decoration: BoxDecoration(
color: Color(0xff1d1d1d),
borderRadius: BorderRadius.circular(15),
),
child: TextFormField(
controller: phoneController,
style: TextStyle(color: Colors.white, fontSize: 17),
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter your phone Number",
hintStyle: TextStyle(color: Colors.white54, fontSize: 17),
contentPadding:
const EdgeInsets.symmetric(vertical: 19, horizontal: 8),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 15),
child: Text(
" (+91) ",
style: TextStyle(color: Colors.white, fontSize: 17),
),
),
suffixIcon: InkWell(
onTap: wait
? null
: () async {
setState(() {
start = 30;
wait = true;
buttonName = "Resend";
});
await authClass.verifyPhoneNumber(
"+91 ${phoneController.text}", context, setData);
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 15),
child: Text(
buttonName,
style: TextStyle(
color: wait ? Colors.grey : Colors.white,
fontSize: 17,
fontWeight: FontWeight.bold,
),
),
),
),
),
),
);
}
void setData(String verificationId) {
setState(() {
verificationIdFinal = verificationId;
});
startTimer();
}
}
| 0 |
mirrored_repositories/Flutter-Firebase-TodoApp/lib | mirrored_repositories/Flutter-Firebase-TodoApp/lib/pages/HomePage.dart | import 'package:firebase_app_web/Service/Auth_Service.dart';
import 'package:firebase_app_web/main.dart';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
AuthClass authClass = AuthClass();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(Icons.logout),
onPressed: () async {
await authClass.signOut();
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (builder) => MyApp()),
(route) => false);
}),
],
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Firebase-TodoApp/lib | mirrored_repositories/Flutter-Firebase-TodoApp/lib/pages/SignUpPage.dart | import 'package:firebase_app_web/Service/Auth_Service.dart';
import 'package:firebase_app_web/pages/HomePage.dart';
import 'package:firebase_app_web/pages/PhoneAuth.dart';
import 'package:firebase_app_web/pages/SignInPage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase_auth;
class SignUpPage extends StatefulWidget {
SignUpPage({Key key}) : super(key: key);
@override
_SignUpPageState createState() => _SignUpPageState();
}
class _SignUpPageState extends State<SignUpPage> {
firebase_auth.FirebaseAuth firebaseAuth = firebase_auth.FirebaseAuth.instance;
TextEditingController _emailController = TextEditingController();
TextEditingController _pwdController = TextEditingController();
bool circular = false;
AuthClass authClass = AuthClass();
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
color: Colors.black,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Sign Up",
style: TextStyle(
fontSize: 35,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
SizedBox(
height: 20,
),
buttonItem("assets/google.svg", "Continue with Google", 25,
() async {
await authClass.googleSignIn(context);
}),
SizedBox(
height: 15,
),
buttonItem("assets/phone.svg", "Continue with Mobile", 30, () {
Navigator.push(context,
MaterialPageRoute(builder: (builder) => PhoneAuthPage()));
}),
SizedBox(
height: 18,
),
Text(
"Or",
style: TextStyle(color: Colors.white, fontSize: 18),
),
SizedBox(
height: 18,
),
textItem("Email....", _emailController, false),
SizedBox(
height: 15,
),
textItem("Password...", _pwdController, true),
SizedBox(
height: 40,
),
colorButton(),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"If you alredy have an Account? ",
style: TextStyle(
color: Colors.white,
fontSize: 16,
),
),
InkWell(
onTap: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (builder) => SignInPage()),
(route) => false);
},
child: Text(
"Login",
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
],
),
],
),
),
),
);
}
Widget colorButton() {
return InkWell(
onTap: () async {
setState(() {
circular = true;
});
try {
firebase_auth.UserCredential userCredential =
await firebaseAuth.createUserWithEmailAndPassword(
email: _emailController.text, password: _pwdController.text);
print(userCredential.user.email);
setState(() {
circular = false;
});
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (builder) => HomePage()),
(route) => false);
} catch (e) {
final snackbar = SnackBar(content: Text(e.toString()));
ScaffoldMessenger.of(context).showSnackBar(snackbar);
setState(() {
circular = false;
});
}
},
child: Container(
width: MediaQuery.of(context).size.width - 100,
height: 60,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
gradient: LinearGradient(colors: [
Color(0xfffd746c),
Color(0xffff9068),
Color(0xfffd746c)
]),
),
child: Center(
child: circular
? CircularProgressIndicator()
: Text(
"Sign Up",
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
),
),
);
}
Widget buttonItem(
String imagepath, String buttonName, double size, Function onTap) {
return InkWell(
onTap: onTap,
child: Container(
width: MediaQuery.of(context).size.width - 60,
height: 60,
child: Card(
color: Colors.black,
elevation: 8,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
side: BorderSide(
width: 1,
color: Colors.grey,
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SvgPicture.asset(
imagepath,
height: size,
width: size,
),
SizedBox(
width: 15,
),
Text(
buttonName,
style: TextStyle(
color: Colors.white,
fontSize: 17,
),
),
],
),
),
),
);
}
Widget textItem(
String labeltext, TextEditingController controller, bool obscureText) {
return Container(
width: MediaQuery.of(context).size.width - 70,
height: 55,
child: TextFormField(
controller: controller,
obscureText: obscureText,
style: TextStyle(
fontSize: 17,
color: Colors.white,
),
decoration: InputDecoration(
labelText: labeltext,
labelStyle: TextStyle(
fontSize: 17,
color: Colors.white,
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(
width: 1.5,
color: Colors.amber,
),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(
width: 1,
color: Colors.grey,
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Firebase-TodoApp/lib | mirrored_repositories/Flutter-Firebase-TodoApp/lib/Custom/ColoredButton.dart | import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
class ColoredButton extends StatelessWidget {
const ColoredButton(
{Key key, this.imagePath, this.onClick, this.text, this.iconData})
: super(key: key);
final String text;
final String imagePath;
final Function onClick;
final IconData iconData;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {},
child: Container(
height: 60,
width: MediaQuery.of(context).size.width - 80,
margin: EdgeInsets.symmetric(horizontal: 20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
gradient: LinearGradient(
colors: [
Color(0xfffd746c),
Color(0xffff9068),
Color(0xfffd746c),
],
),
),
child: Center(
child: Text(
text,
style: TextStyle(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.w500,
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Firebase-TodoApp/lib | mirrored_repositories/Flutter-Firebase-TodoApp/lib/Custom/ButtonItem.dart | import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
class ButtonItem extends StatelessWidget {
const ButtonItem(
{Key key,
this.imagePath,
this.onClick,
this.text,
this.iconData,
this.size})
: super(key: key);
final String text;
final String imagePath;
final Function onClick;
final IconData iconData;
final double size;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {},
child: Container(
height: 60,
width: MediaQuery.of(context).size.width - 60,
child: Card(
color: Colors.black,
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.grey, width: 1),
borderRadius: BorderRadius.circular(15),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 5),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SvgPicture.asset(
imagePath,
height: size,
width: size,
// color: Colors.white,
),
// Icon(iconData),
SizedBox(width: 15),
Text(
text,
style: TextStyle(fontSize: 17, color: Colors.white),
)
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Firebase-TodoApp/lib | mirrored_repositories/Flutter-Firebase-TodoApp/lib/Custom/TextItem.dart | import 'package:flutter/material.dart';
class TextItem extends StatelessWidget {
const TextItem({Key key, this.labelText}) : super(key: key);
final String labelText;
@override
Widget build(BuildContext context) {
return Container(
height: 54,
width: MediaQuery.of(context).size.width - 70,
child: TextFormField(
// style: te,
decoration: InputDecoration(
labelText: labelText,
labelStyle: TextStyle(
color: Colors.white,
fontSize: 17,
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey, width: 1),
borderRadius: BorderRadius.circular(15),
),
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey, width: 1),
borderRadius: BorderRadius.circular(15),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Firebase-TodoApp | mirrored_repositories/Flutter-Firebase-TodoApp/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:firebase_app_web/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/math-riddle-free | mirrored_repositories/math-riddle-free/lib/main.dart | import 'dart:async';
import 'dart:isolate';
import 'package:easy_localization/easy_localization.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:logging/logging.dart';
import 'package:math_riddle/core/app_route.dart';
import 'package:math_riddle/core/app_theme.dart';
import 'package:math_riddle/data/audio/audio_controller.dart';
import 'package:math_riddle/data/persistence/local_storage_settings_persistence.dart';
import 'package:math_riddle/data/persistence/settings_persistence.dart';
import 'package:math_riddle/data/player_progress/persistence/local_storage_player_progress_persistence.dart';
import 'package:math_riddle/data/player_progress/persistence/player_progress_persistence.dart';
import 'package:math_riddle/data/player_progress/player_progress.dart';
import 'package:math_riddle/data/puzzle/free_puzzle_repository.dart';
import 'package:math_riddle/data/puzzle/i_puzzle_repository.dart';
import 'package:math_riddle/data/rating/rate_us_controller.dart';
import 'package:math_riddle/data/setting/settings.dart';
import 'package:math_riddle/firebase_options.dart';
import 'package:math_riddle/view/common/app_lifecycle.dart';
import 'package:provider/provider.dart';
Logger _log = Logger('main.dart');
Future<void> main() async {
runZonedGuarded<Future<void>>(() async {
WidgetsFlutterBinding.ensureInitialized();
if (kDebugMode) {
Animate.restartOnHotReload = true;
}
await EasyLocalization.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform);
FirebaseCrashlytics crashlytics = FirebaseCrashlytics.instance;
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
Isolate.current.addErrorListener(RawReceivePort((dynamic pair) async {
final errorAndStacktrace = pair as List<dynamic>;
await crashlytics.recordError(
errorAndStacktrace.first, errorAndStacktrace.last as StackTrace?,
fatal: true);
}).sendPort);
if (kReleaseMode) {
// Don't log anything below warnings in production.
Logger.root.level = Level.WARNING;
}
Logger.root.onRecord.listen((record) {
debugPrint('${record.level.name}: ${record.time}: '
'${record.loggerName}: '
'${record.message}');
});
_log.info('Going full screen');
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
runApp(
EasyLocalization(
path: 'assets/translations',
supportedLocales: const [
Locale('en', ''),
Locale('es', ''),
Locale('fr', ''),
Locale('ru', ''),
Locale('pt', ''),
Locale('id', ''),
Locale('ko', ''),
Locale('it', ''),
],
fallbackLocale: const Locale('en', ''),
child: MyApp(
settingsPersistence: LocalStorageSettingsPersistence(),
playerProgressPersistence: LocalStoragePlayerProgressPersistence(),
puzzleRepository: FreePuzzleRepository(),
),
),
);
}, (error, stack) => FirebaseCrashlytics.instance.recordError(error, stack));
}
class MyApp extends StatelessWidget {
final PlayerProgressPersistence playerProgressPersistence;
final SettingsPersistence settingsPersistence;
final IPuzzleRepository puzzleRepository;
const MyApp({
required this.playerProgressPersistence,
required this.settingsPersistence,
required this.puzzleRepository,
super.key,
});
@override
Widget build(BuildContext context) {
return AppLifecycleObserver(
child: MultiProvider(
providers: [
Provider.value(value: puzzleRepository),
ChangeNotifierProvider(
create: (context) {
var progress = PlayerProgress(playerProgressPersistence);
progress.getLatestFromStore();
return progress;
},
),
Provider<SettingsController>(
lazy: false,
create: (context) => SettingsController(
persistence: settingsPersistence,
)..loadStateFromPersistence(),
),
Provider<RateUsController>(
lazy: false,
create: (context) =>
RateUsController(store: playerProgressPersistence),
),
ProxyProvider2<SettingsController, ValueNotifier<AppLifecycleState>,
AudioController>(
// Ensures that the AudioController is created on startup,
// and not "only when it's needed", as is default behavior.
// This way, music starts immediately.
lazy: false,
create: (context) => AudioController()..initialize(),
update: (context, settings, lifecycleNotifier, audio) {
if (audio == null) throw ArgumentError.notNull();
audio.attachSettings(settings);
audio.attachLifecycleNotifier(lifecycleNotifier);
return audio;
},
dispose: (context, audio) => audio.dispose(),
),
],
child: Builder(builder: (context) {
return MaterialApp.router(
debugShowCheckedModeBanner: false,
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,
title: 'Math Riddle',
theme: ThemeController.theme(),
routeInformationProvider: AppRoute.router.routeInformationProvider,
routeInformationParser: AppRoute.router.routeInformationParser,
routerDelegate: AppRoute.router.routerDelegate,
);
}),
),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/main/main_menu_screen.dart | import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:lottie/lottie.dart';
import 'package:math_riddle/core/app_assets.dart';
import 'package:math_riddle/data/audio/audio_controller.dart';
import 'package:math_riddle/data/audio/sounds.dart';
import 'package:math_riddle/data/player_progress/player_progress.dart';
import 'package:math_riddle/data/puzzle/i_puzzle_repository.dart';
import 'package:math_riddle/data/setting/settings.dart';
import 'package:math_riddle/view/common/align_effect.dart';
import 'package:math_riddle/view/common/common_filled_label_button_view.dart';
import 'package:math_riddle/view/common/common_text_button_view.dart';
import 'package:math_riddle/view/language/language_screen.dart';
import 'package:math_riddle/view/neopop_button/constants.dart';
import 'package:provider/provider.dart';
class MainMenuScreen extends StatefulHookWidget {
const MainMenuScreen({Key? key}) : super(key: key);
@override
MainMenuScreenState createState() => MainMenuScreenState();
}
class MainMenuScreenState extends State<MainMenuScreen> {
@override
Widget build(BuildContext context) {
useMemoized(() {
AssetLottie('assets/json/success-animation.json').load();
});
useMemoized(() {
AssetLottie('assets/json/confetti-pop-small.json').load();
});
final settingsController = context.watch<SettingsController>();
final audioController = context.watch<AudioController>();
final playerProgress = context.watch<PlayerProgress>();
return Scaffold(
body: Stack(
children: [
Animate(
autoPlay: true,
effects: [
FadeEffect(
delay: 1200.ms,
duration: 1200.ms,
curve: Curves.elasticOut,
),
const MoveEffect(
begin: Offset(0, 20),
end: Offset(0, 0),
),
],
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
margin: const EdgeInsets.only(
left: 30,
right: 30,
),
child: Image.asset(
AppAssets.bgMain,
fit: BoxFit.fitWidth,
),
),
],
),
),
Animate(
autoPlay: true,
effects: [
AlignEffect(
delay: 1200.ms,
duration: 1200.ms,
curve: Curves.elasticOut,
),
const ScaleEffect(
begin: Offset(1, 1),
end: Offset(0.8, 0.8),
),
],
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 24),
child: Image.asset(
AppAssets.icAppLogo,
),
),
),
Animate(
autoPlay: true,
effects: [
FadeEffect(
delay: 1200.ms,
duration: 1200.ms,
curve: Curves.elasticOut,
),
],
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 22,
vertical: 32,
),
child: InkWell(
customBorder: const CircleBorder(),
onTap: () async {
audioController.playSfx(SfxType.iconButtonTap);
await showDialog<void>(
context: context,
barrierDismissible: true,
builder: (context) {
return const LanguageScreen();
},
);
},
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Icon(Icons.language),
),
),
),
),
Animate(
autoPlay: true,
effects: [
FadeEffect(
delay: 1200.ms,
duration: 1200.ms,
curve: Curves.elasticOut,
),
],
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 22,
vertical: 32,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
// ValueListenableBuilder<bool>(
// valueListenable: settingsController.muted,
// builder: (context, muted, child) {
// return IconButton(
// onPressed: () {
// audioController.playSfx(SfxType.iconButtonTap);
// settingsController.toggleMuted();
// },
// icon: Icon(muted ? Icons.volume_off : Icons.volume_up),
// );
// },
// ),
ValueListenableBuilder<bool>(
valueListenable: settingsController.soundsOn,
builder: (context, soundsOn, child) => InkWell(
customBorder: const CircleBorder(),
onTap: () {
audioController.playSfx(SfxType.iconButtonTap);
settingsController.toggleSoundsOn();
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(
soundsOn ? Icons.graphic_eq : Icons.volume_off,
),
),
),
),
ValueListenableBuilder<bool>(
valueListenable: settingsController.musicOn,
builder: (context, musicOn, child) => InkWell(
customBorder: const CircleBorder(),
onTap: () {
audioController.playSfx(SfxType.iconButtonTap);
settingsController.toggleMusicOn();
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(
musicOn ? Icons.music_note : Icons.music_off,
),
),
),
),
],
),
),
),
Animate(
autoPlay: true,
effects: [
MoveEffect(
delay: 1200.ms,
duration: 1200.ms,
curve: Curves.elasticOut,
begin: const Offset(0, 150),
end: const Offset(0, 0),
),
],
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
CommonFilledLabelButtonView(
depth: kButtonDepth,
label: "play".tr().toUpperCase(),
onPressed: () {
audioController.playSfx(SfxType.buttonTap);
if (playerProgress.highestLevelReached <
context
.read<IPuzzleRepository>()
.getGameLevelByOrder()
.length) {
GoRouter.of(context).go(
'/play/session/${playerProgress.highestLevelReached + 1}');
} else {
GoRouter.of(context).go('/play/session/1');
}
},
),
_gap,
Row(
children: [
Expanded(
child: CommonTextButtonView(
label: "levels".tr().toUpperCase(),
height: 52,
fontWeight: FontWeight.w700,
onPressed: () {
audioController.playSfx(SfxType.buttonTap);
GoRouter.of(context).go('/play');
},
),
),
],
),
_gap,
],
),
),
),
],
),
);
}
static const _gap = SizedBox(height: 10);
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/level/level_state.dart | import 'package:collection/collection.dart';
import 'package:math_riddle/core/app_constant.dart';
import 'package:math_riddle/data/model/option.dart';
import 'package:math_riddle/data/model/option_level.dart';
import 'level_base.dart';
class LevelState extends LevelBase {
String input = "";
List<Option> optionList = [];
LevelState({
required super.position,
required super.puzzleRepository,
}) {
_setUpNewLevel(position: position);
}
void _setUpNewLevel({required int position}) {
input = "";
level = puzzleRepository
.getGameLevelByOrder()
.firstWhere((element) => element.position == position);
if (level.gameType != GameType.numpad) {
optionList = (level as OptionLevel).optionList;
} else {
optionList = [];
}
notifyListeners();
}
void onTextChange(String value) {
if (input.length < 3) {
input = input + value;
notifyListeners();
}
}
void onBackSpace() {
if (input.isNotEmpty) {
input = input.substring(0, input.length - 1);
notifyListeners();
}
}
void onOptionSelection({required Option option}) {
optionList = optionList.map((e) {
if (e.name == option.name) {
return option.copyWith(isSelected: true);
} else {
return e.copyWith(isSelected: false);
}
}).toList();
notifyListeners();
}
@override
bool evaluate() {
if (level.gameType == GameType.numpad) {
if (input == level.answer) {
return true;
} else {
input = "";
notifyListeners();
return false;
}
} else {
return level.answer ==
optionList.firstWhereOrNull((element) => element.isSelected)?.name;
}
}
@override
void levelUp({required int newPosition}) {
_setUpNewLevel(position: newPosition);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/level/level_base.dart | import 'package:flutter/foundation.dart';
import 'package:math_riddle/data/model/base_level.dart';
import 'package:math_riddle/data/puzzle/i_puzzle_repository.dart';
abstract class LevelBase extends ChangeNotifier {
final int position;
final IPuzzleRepository puzzleRepository;
late BaseLevel level;
LevelBase({
required this.position,
required this.puzzleRepository,
});
bool evaluate();
void levelUp({required int newPosition});
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/level/level_selection_screen.dart | import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:math_riddle/core/app_colors.dart';
import 'package:math_riddle/data/audio/audio_controller.dart';
import 'package:math_riddle/data/audio/sounds.dart';
import 'package:math_riddle/data/player_progress/player_progress.dart';
import 'package:math_riddle/data/puzzle/i_puzzle_repository.dart';
import 'package:math_riddle/view/common/common_filled_label_button_view.dart';
import 'package:math_riddle/view/common/common_scaffold_view.dart';
import 'package:math_riddle/view/neopop_button/constants.dart';
import 'package:provider/provider.dart';
class LevelSelectionScreen extends StatelessWidget {
const LevelSelectionScreen({super.key});
@override
Widget build(BuildContext context) {
final playerProgress = context.watch<PlayerProgress>();
final puzzleRepository = context.read<IPuzzleRepository>();
final list = puzzleRepository.getGameLevelByOrder();
return CommonScaffoldView(
title: Text("levels".tr()),
body: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 6,
childAspectRatio: 1,
),
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24),
itemCount: list.length,
itemBuilder: (context, index) {
return CommonFilledLabelButtonView(
depth: kSmallButtonDepth,
isLevels: true,
label: "${list[index].position}",
fontSize: 16,
textColor:
playerProgress.highestLevelReached <= list[index].position - 1
? AppColor.white
: AppColor.black,
color:
playerProgress.highestLevelReached <= list[index].position - 1
? AppColor.blue
: AppColor.white,
onPressed:
playerProgress.highestLevelReached >= list[index].position - 1
? () {
final audioController = context.read<AudioController>();
audioController.playSfx(SfxType.buttonTap);
GoRouter.of(context)
.go('/play/session/${list[index].position}');
}
: null,
);
},
),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/language/language_screen.dart | import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:math_riddle/core/app_constant.dart';
import 'package:math_riddle/data/audio/audio_controller.dart';
import 'package:math_riddle/data/audio/sounds.dart';
import 'package:provider/provider.dart';
class LanguageScreen extends StatelessWidget {
const LanguageScreen({super.key});
@override
Widget build(BuildContext context) {
return Material(
color: const Color.fromARGB(96, 12, 12, 12),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
color: const Color(0xff212121),
alignment: Alignment.center,
margin: const EdgeInsets.all(40),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 24),
Text(
'language'.tr(),
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.w600,
fontFamily: "Roboto",
),
),
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
mainAxisSize: MainAxisSize.min,
children: context.supportedLocales
.map(
(e) => TextButton(
onPressed: () {
final audioController =
context.read<AudioController>();
audioController.playSfx(SfxType.iconButtonTap);
EasyLocalization.of(context)?.setLocale(e);
Navigator.of(context).pop();
},
child: Row(
children: [
const SizedBox(width: 8),
Text(
languageList
.firstWhere(
(element) => element.locale == e)
.flag,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w400,
),
),
const SizedBox(width: 8),
Text(
languageList
.firstWhere(
(element) => element.locale == e)
.name,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w400,
fontFamily: "Roboto",
),
),
const Spacer(),
if (context.locale == e)
const Icon(Icons.check_box),
],
),
),
)
.toList(),
),
),
const SizedBox(height: 24),
],
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/rate_us/rate_us_screen.dart | import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:math_riddle/data/rating/rate_us_controller.dart';
import 'package:math_riddle/view/common/common_filled_label_button_view.dart';
import 'package:math_riddle/view/common/common_text_button_view.dart';
import 'package:math_riddle/view/neopop_button/constants.dart';
import 'package:provider/provider.dart';
import 'package:store_redirect/store_redirect.dart';
class RateUsScreen extends StatelessWidget {
const RateUsScreen({super.key});
@override
Widget build(BuildContext context) {
RateUsController rateUsController = context.read<RateUsController>();
return Material(
color: const Color.fromARGB(96, 12, 12, 12),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
color: const Color(0xff212121),
alignment: Alignment.center,
margin: const EdgeInsets.all(40),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 40),
Text(
'rate_us'.tr(),
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.w600,
fontFamily: "Roboto",
),
),
const SizedBox(height: 14),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Text(
"rate_us_text".tr(),
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w400,
fontFamily: "Roboto",
),
),
),
const SizedBox(height: 30),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 40),
child: CommonFilledLabelButtonView(
depth: kMediumButtonDepth,
label: "rate".tr().toUpperCase(),
height: 42,
fontSize: 16,
onPressed: () {
StoreRedirect.redirect();
rateUsController.setRated();
GoRouter.of(context).pop();
},
),
),
const SizedBox(height: 8),
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 40),
child: CommonTextButtonView(
label: "later".tr().toUpperCase(),
height: 42,
fontWeight: FontWeight.w700,
onPressed: () {
if (rateUsController.isRemindMeLater) {
rateUsController.set2ndTimeRemindMeLater();
} else {
rateUsController.setRemindMeLater();
}
GoRouter.of(context).pop();
},
),
),
const SizedBox(height: 28),
],
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/neopop_button/neopop_button_translator.dart | import 'package:flutter/material.dart';
import 'package:math_riddle/view/neopop_button/constants.dart';
/// A widget with [GestureDetector] that forms the basis of the [NeoPopButton].
class NeoPopButtonTranslator extends StatefulWidget {
const NeoPopButtonTranslator({
required this.child,
this.depth = 3,
this.animationDuration = kButtonDuration,
required this.onPressed,
this.onTapDown,
this.onLongPress,
this.forwardDuration,
this.reverseDuration,
super.key,
});
/// The child widget.
final Widget child;
/// The depth of the button.
final double depth;
/// The duration of the animation.
final Duration animationDuration;
/// The duration of the forward animation.
final Duration? forwardDuration;
/// The duration of the reverse animation.
final Duration? reverseDuration;
final VoidCallback onPressed;
final VoidCallback? onTapDown;
final VoidCallback? onLongPress;
@override
State<NeoPopButtonTranslator> createState() => _NeoPopButtonTranslatorState();
}
class _NeoPopButtonTranslatorState extends State<NeoPopButtonTranslator>
with SingleTickerProviderStateMixin {
late AnimationController controller;
@override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
lowerBound: 0,
upperBound: 1,
// lowerBound: 0.0,
// upperBound: 0.1,
duration: widget.forwardDuration ??
Duration(milliseconds: widget.animationDuration.inMilliseconds ~/ 2),
reverseDuration: widget.reverseDuration ??
Duration(milliseconds: widget.animationDuration.inMilliseconds ~/ 2),
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
double per = widget.depth / MediaQuery.of(context).size.width;
return GestureDetector(
onTapDown: (_) {
widget.onTapDown?.call();
controller.forward();
},
onTapUp: (_) {
if (controller.isCompleted) {
controller.reverse().whenComplete(() => widget.onPressed());
} else {
controller.forward().whenComplete(
() =>
controller.reverse().whenComplete(() => widget.onPressed()),
);
}
},
onTapCancel: () => controller.reverse(),
onLongPress: widget.onLongPress == null
? null
: () {
widget.onLongPress?.call();
controller.forward();
},
onLongPressEnd: widget.onLongPress == null
? null
: (_) {
if (controller.isCompleted) {
controller.reverse();
} else {
controller.forward().whenComplete(() => controller.reverse());
}
},
child: AnimatedBuilder(
animation: controller,
builder: (context, child) {
final double depth = 1 - per * controller.value;
return Transform.scale(
scale: depth,
child: widget.child,
);
},
),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/neopop_button/constants.dart | const kButtonDepth = 3.0;
const kMediumButtonDepth = 6.0;
const kSmallButtonDepth = 12.0;
const kButtonDuration = Duration(milliseconds: 50);
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/win/win_game_screen.dart | import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:lottie/lottie.dart';
import 'package:math_riddle/data/audio/audio_controller.dart';
import 'package:math_riddle/data/audio/sounds.dart';
import 'package:math_riddle/data/model/score.dart';
import 'package:math_riddle/view/common/common_filled_label_button_view.dart';
import 'package:math_riddle/view/neopop_button/constants.dart';
import 'package:provider/provider.dart';
class WinGameScreen extends HookWidget {
final Score score;
const WinGameScreen({
super.key,
required this.score,
});
//0.20 //0.25
@override
Widget build(BuildContext context) {
AnimationController animationController = useAnimationController();
return Material(
color: const Color.fromARGB(96, 12, 12, 12),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Stack(
children: [
Column(
children: [
Container(
color: const Color(0xff212121),
alignment: Alignment.center,
padding: const EdgeInsets.all(40),
margin: const EdgeInsets.all(40),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Lottie.asset(
'assets/json/success-animation.json',
width: 120,
height: 120,
fit: BoxFit.fill,
repeat: false,
),
const SizedBox(height: 20),
Text(
"you_won".tr(),
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.w600,
fontFamily: "Roboto",
),
),
const SizedBox(height: 2),
Text(
"${"time".tr()}: ${score.formattedTime}",
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w400,
fontFamily: "Roboto",
),
),
const SizedBox(height: 30),
CommonFilledLabelButtonView(
depth: kMediumButtonDepth,
label: "continue".tr().toUpperCase(),
height: 42,
fontSize: 16,
onPressed: () {
final audioController =
context.read<AudioController>();
audioController.playSfx(SfxType.buttonTap);
GoRouter.of(context).pop();
},
),
],
),
),
],
),
IgnorePointer(
child: Transform.scale(
scale: 1.4,
child: Lottie.asset(
'assets/json/confetti-pop-small.json',
repeat: false,
controller: animationController,
onLoaded: (composition) {
animationController.duration = composition.duration;
Future.delayed(const Duration(milliseconds: 200), () {
animationController.forward();
});
},
),
),
),
],
),
],
),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/hint/hint_screen.dart | import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:math_riddle/data/audio/audio_controller.dart';
import 'package:math_riddle/data/audio/sounds.dart';
import 'package:math_riddle/view/common/common_filled_label_button_view.dart';
import 'package:math_riddle/view/neopop_button/constants.dart';
import 'package:provider/provider.dart';
class HintScreen extends StatelessWidget {
final String hint;
const HintScreen({
super.key,
required this.hint,
});
@override
Widget build(BuildContext context) {
return Material(
color: const Color.fromARGB(96, 12, 12, 12),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
color: const Color(0xff212121),
alignment: Alignment.center,
margin: const EdgeInsets.all(40),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 40),
Text(
'hint'.tr(),
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.w600,
fontFamily: "Roboto",
),
),
const SizedBox(height: 14),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Text(
hint,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w400,
fontFamily: "Roboto",
),
),
),
const SizedBox(height: 30),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 40),
child: CommonFilledLabelButtonView(
depth: kMediumButtonDepth,
label: "ok".tr().toUpperCase(),
height: 42,
fontSize: 16,
onPressed: () {
final audioController = context.read<AudioController>();
audioController.playSfx(SfxType.buttonTap);
GoRouter.of(context).pop();
},
),
),
const SizedBox(height: 40),
],
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/common_filled_label_button_view.dart | import 'package:flutter/material.dart';
import 'package:math_riddle/core/app_colors.dart';
import 'package:math_riddle/view/common/custom_button_border.dart';
import 'package:math_riddle/view/common/custom_level_border.dart';
import 'package:math_riddle/view/neopop_button/neopop_button_translator.dart';
class CommonFilledLabelButtonView extends StatelessWidget {
final String label;
final void Function()? onPressed;
final double height;
final double depth;
final FontWeight fontWeight;
final double fontSize;
final Color color;
final Color textColor;
final bool isLevels;
const CommonFilledLabelButtonView({
super.key,
required this.label,
required this.onPressed,
required this.depth,
this.height = 56,
this.fontWeight = FontWeight.w700,
this.fontSize = 20,
this.color = AppColor.white,
this.textColor = AppColor.black,
this.isLevels = false,
});
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
border: isLevels
? CustomLevelBorder.all(
color: Colors.white,
smallGap: 5,
largeGap: 8,
space: 4,
)
: CustomButtonBorder.all(
color: Colors.white,
smallSpace: 4,
largeSpace: 12,
smallGap: 4,
largeGap: 20,
),
),
padding: const EdgeInsets.all(3),
child: onPressed == null
? Container(
color: AppColor.blackLight,
constraints: BoxConstraints.expand(height: height),
alignment: Alignment.center,
child: Text(
label,
style: TextStyle(
fontSize: fontSize,
fontWeight: fontWeight,
color: AppColor.white,
),
),
)
: NeoPopButtonTranslator(
depth: depth,
onPressed: onPressed!,
child: Container(
color: color,
constraints: BoxConstraints.expand(height: height),
alignment: Alignment.center,
child: Text(
label,
style: TextStyle(
fontSize: fontSize,
fontWeight: fontWeight,
color: textColor,
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/common_scaffold_view.dart | import 'package:flutter/material.dart';
import 'package:math_riddle/data/audio/audio_controller.dart';
import 'package:math_riddle/data/audio/sounds.dart';
import 'package:provider/provider.dart';
class CommonScaffoldView extends StatelessWidget {
final Widget title;
final Widget body;
final List<Widget> actions;
final bool showLanding;
const CommonScaffoldView({
required this.title,
required this.body,
this.actions = const <Widget>[],
this.showLanding = true,
super.key,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: title,
actions: actions,
leading: showLanding
? InkWell(
onTap: () {
final audioController = context.read<AudioController>();
audioController.playSfx(SfxType.buttonTap);
Navigator.pop(context);
},
customBorder: const CircleBorder(),
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Icon(Icons.arrow_back_ios_new),
),
)
: null,
),
body: body,
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/common_input_text_view.dart | import 'package:flutter/material.dart';
import 'package:math_riddle/core/app_colors.dart';
class CommonInputTextView extends StatelessWidget {
final String value;
final double height;
const CommonInputTextView({
required this.value,
required this.height,
super.key,
});
@override
Widget build(BuildContext context) {
return Container(
color: AppColor.blackLight,
constraints: BoxConstraints.expand(height: height),
alignment: Alignment.center,
child: Text(
value,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
),
),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/app_lifecycle.dart | import 'package:flutter/widgets.dart';
import 'package:logging/logging.dart';
import 'package:provider/provider.dart';
class AppLifecycleObserver extends StatefulWidget {
final Widget child;
const AppLifecycleObserver({required this.child, super.key});
@override
State<AppLifecycleObserver> createState() => _AppLifecycleObserverState();
}
class _AppLifecycleObserverState extends State<AppLifecycleObserver>
with WidgetsBindingObserver {
static final _log = Logger('AppLifecycleObserver');
final ValueNotifier<AppLifecycleState> lifecycleListenable =
ValueNotifier(AppLifecycleState.inactive);
@override
Widget build(BuildContext context) {
// Using InheritedProvider because we don't want to use Consumer
// or context.watch or anything like that to listen to this. We want
// to manually add listeners. We're interested in the _events_ of lifecycle
// state changes, and not so much in the state itself. (For example,
// we want to stop sound when the app goes into the background, and
// restart sound again when the app goes back into focus. We're not
// rebuilding any widgets.)
//
// Provider, by default, throws when one
// is trying to provide a Listenable (such as ValueNotifier) without using
// something like ValueListenableProvider. InheritedProvider is more
// low-level and doesn't have this problem.
return InheritedProvider<ValueNotifier<AppLifecycleState>>.value(
value: lifecycleListenable,
child: widget.child,
);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
_log.info(() => 'didChangeAppLifecycleState: $state');
lifecycleListenable.value = state;
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_log.info('Subscribed to app lifecycle updates');
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/custom_button_border.dart | import 'package:flutter/material.dart';
class CustomButtonBorder extends BoxBorder {
const CustomButtonBorder({
this.top = BorderSide.none,
this.right = BorderSide.none,
this.bottom = BorderSide.none,
this.left = BorderSide.none,
this.smallGap = 2,
this.largeGap = 17,
this.smallSpace = 2,
this.largeSpace = 8,
});
const CustomButtonBorder.fromBorderSide(
BorderSide side,
this.smallGap,
this.largeGap,
this.smallSpace,
this.largeSpace,
) : top = side,
right = side,
bottom = side,
left = side;
factory CustomButtonBorder.all({
Color color = const Color(0xFF000000),
double width = 1.0,
BorderStyle style = BorderStyle.solid,
double strokeAlign = BorderSide.strokeAlignInside,
double smallGap = 2,
double largeGap = 17,
double smallSpace = 2,
double largeSpace = 8,
}) {
final BorderSide side = BorderSide(
color: color, width: width, style: style, strokeAlign: strokeAlign);
return CustomButtonBorder.fromBorderSide(
side,
smallGap,
largeGap,
smallSpace,
largeSpace,
);
}
@override
final BorderSide bottom;
@override
final BorderSide top;
final BorderSide right;
final BorderSide left;
final double smallGap;
final double largeGap;
final double smallSpace;
final double largeSpace;
@override
EdgeInsetsGeometry get dimensions => EdgeInsets.all(top.strokeInset);
@override
bool get isUniform => true;
@override
void paint(
Canvas canvas,
Rect rect, {
TextDirection? textDirection,
BoxShape shape = BoxShape.rectangle,
BorderRadius? borderRadius,
}) {
final Paint paint = Paint()..strokeWidth = top.width;
final Path path = Path();
paint.color = top.color;
path.reset();
path.moveTo(rect.left, rect.top);
path.lineTo(rect.left + largeSpace, rect.top);
path.moveTo(rect.left + largeSpace + smallGap, rect.top);
path.lineTo(rect.right - largeGap - largeSpace, rect.top);
path.moveTo(rect.right - largeSpace, rect.top);
path.lineTo(rect.right, rect.top);
path.lineTo(rect.right, rect.bottom - smallGap - smallSpace);
path.moveTo(rect.right, rect.bottom - smallSpace);
path.lineTo(rect.right, rect.bottom);
path.lineTo(rect.right - largeSpace, rect.bottom);
path.moveTo(rect.right - largeSpace - smallGap, rect.bottom);
path.lineTo(rect.left + largeSpace + largeGap, rect.bottom);
path.moveTo(rect.left + largeSpace, rect.bottom);
path.lineTo(rect.left, rect.bottom);
path.lineTo(rect.left, rect.top + smallGap + smallSpace);
path.moveTo(rect.left, rect.top + smallGap);
path.lineTo(rect.left, rect.top);
paint.style = PaintingStyle.stroke;
paint.strokeCap=StrokeCap.round;
canvas.drawPath(path, paint);
}
@override
ShapeBorder scale(double t) {
return Border(
top: top.scale(t),
right: right.scale(t),
bottom: bottom.scale(t),
left: left.scale(t),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/common_text_button_view.dart | import 'package:flutter/material.dart';
import 'package:math_riddle/core/app_colors.dart';
class CommonTextButtonView extends StatelessWidget {
final String label;
final void Function() onPressed;
final double height;
final FontWeight fontWeight;
const CommonTextButtonView({
required this.label,
required this.onPressed,
this.fontWeight = FontWeight.w500,
required this.height,
super.key,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(0.5),
child: TextButton(
onPressed: onPressed,
style: TextButton.styleFrom(
fixedSize: Size.fromHeight(height),
),
child: Text(
label,
style: TextStyle(
fontSize: 14,
fontWeight: fontWeight,
color: AppColor.white,
decoration: TextDecoration.underline,
letterSpacing: 1.6,
),
),
),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/image_option_view.dart | import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:math_riddle/data/audio/audio_controller.dart';
import 'package:math_riddle/data/audio/sounds.dart';
import 'package:math_riddle/data/model/image_option.dart';
import 'package:math_riddle/data/model/option.dart';
import 'package:math_riddle/view/common/common_filled_button_view.dart';
import 'package:math_riddle/view/common/common_image_button_view.dart';
import 'package:math_riddle/view/level/level_state.dart';
import 'package:provider/provider.dart';
class ImageOptionView extends StatelessWidget {
final List<Option> list;
final void Function() onWrong;
final void Function() onWin;
final double height;
const ImageOptionView({
super.key,
required this.list,
required this.onWrong,
required this.onWin,
required this.height,
});
@override
Widget build(BuildContext context) {
final audioController = context.read<AudioController>();
return Column(
children: [
Row(
children: [
...list.mapIndexed((i, e) {
return Expanded(
child: CommonImageButtonView(
imageOption: e as ImageOption,
index: i,
selectedList: list.map((e) => e.isSelected).toList(),
onPressed: (option) {
audioController.playSfx(SfxType.click);
context
.read<LevelState>()
.onOptionSelection(option: option);
},
),
);
}).toList()
],
),
Row(
children: [
Expanded(
child: CommonFilledEnterButtonView(
onPressed: () {
audioController.playSfx(SfxType.click);
bool isWin = context.read<LevelState>().evaluate();
if (isWin) {
onWin();
} else {
onWrong();
}
},
height: height,
),
),
],
),
],
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/align_effect.dart | import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
@immutable
class AlignEffect extends Effect<Alignment> {
static const Alignment neutralValue = Alignment.center;
static const Alignment defaultValue = Alignment.topCenter;
const AlignEffect({
super.delay,
super.duration,
super.curve,
super.begin = neutralValue,
super.end = defaultValue,
});
@override
Widget build(
BuildContext context,
Widget child,
AnimationController controller,
EffectEntry entry,
) {
Animation<Alignment> animation = buildAnimation(controller, entry);
return getOptimizedBuilder<Alignment>(
animation: animation,
builder: (_, __) {
return Align(
alignment: animation.value,
child: child,
);
},
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/numpad_view.dart | import 'package:flutter/material.dart';
import 'package:math_riddle/data/audio/audio_controller.dart';
import 'package:math_riddle/data/audio/sounds.dart';
import 'package:math_riddle/view/common/common_filled_button_view.dart';
import 'package:math_riddle/view/common/common_input_text_view.dart';
import 'package:math_riddle/view/level/level_state.dart';
import 'package:provider/provider.dart';
class NumPadView extends StatelessWidget {
final void Function() onWrong;
final void Function() onWin;
final double height;
const NumPadView({
super.key,
required this.onWrong,
required this.onWin,
required this.height,
});
@override
Widget build(BuildContext context) {
final audioController = context.read<AudioController>();
return Column(
children: [
Selector<LevelState, String>(
selector: (p0, p1) => p1.input,
builder: (context, value, child) {
return CommonInputTextView(
value: value,
height: height,
);
},
),
Row(
children: [
Expanded(
flex: 10,
child: Column(
children: [
Row(
children: [
...["1", "2", "3", "4", "5"].map((e) {
return Expanded(
flex: 2,
child: CommonFilledButtonView(
label: e,
height: height,
onPressed: (value) {
audioController.playSfx(SfxType.click);
context.read<LevelState>().onTextChange(value);
},
),
);
}).toList()
],
),
Row(
children: [
...["6", "7", "8", "9", "0"].map((e) {
return Expanded(
flex: 2,
child: CommonFilledButtonView(
label: e,
height: height,
onPressed: (value) {
audioController.playSfx(SfxType.click);
context.read<LevelState>().onTextChange(value);
},
),
);
}).toList()
],
),
],
),
),
Expanded(
flex: 3,
child: Column(
children: [
Row(
children: [
Expanded(
child: CommonFilledEnterButtonView(
onPressed: () {
audioController.playSfx(SfxType.click);
bool isWin = context.read<LevelState>().evaluate();
if (isWin) {
onWin();
} else {
onWrong();
}
},
height: height,
),
),
],
),
Row(
children: [
Expanded(
child: CommonFilledBackButtonView(
onPressed: () {
audioController.playSfx(SfxType.clickBack);
context.read<LevelState>().onBackSpace();
},
height: height,
),
),
],
),
],
),
)
],
),
],
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/option_view.dart | import 'package:flutter/material.dart';
import 'package:math_riddle/data/audio/audio_controller.dart';
import 'package:math_riddle/data/audio/sounds.dart';
import 'package:math_riddle/data/model/option.dart';
import 'package:math_riddle/view/common/common_filled_button_view.dart';
import 'package:math_riddle/view/level/level_state.dart';
import 'package:provider/provider.dart';
class OptionView extends StatelessWidget {
final List<Option> list;
final void Function() onWrong;
final void Function() onWin;
final double height;
const OptionView({
super.key,
required this.list,
required this.onWrong,
required this.onWin,
required this.height,
});
@override
Widget build(BuildContext context) {
final audioController = context.read<AudioController>();
return Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
flex: 10,
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Row(
children: [
...list.take(list.length == 6 ? 3 : 2).map((e) {
return Expanded(
child: CommonFilledButtonView(
label: e.name,
height: height,
isSelected: e.isSelected,
onPressed: (value) {
audioController.playSfx(SfxType.click);
context
.read<LevelState>()
.onOptionSelection(option: e);
},
),
);
}).toList()
],
),
Row(
children: [
...list.skip(list.length == 6 ? 3 : 2).map((e) {
return Expanded(
child: CommonFilledButtonView(
label: e.name,
height: height,
isSelected: e.isSelected,
onPressed: (value) {
audioController.playSfx(SfxType.click);
context
.read<LevelState>()
.onOptionSelection(option: e);
},
),
);
}).toList()
],
),
],
),
),
Expanded(
flex: 3,
child: CommonFilledEnterButtonView(
height: (height * 2) + 1,
onPressed: () {
audioController.playSfx(SfxType.click);
bool isWin = context.read<LevelState>().evaluate();
if (isWin) {
onWin();
} else {
onWrong();
}
},
),
),
],
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/common_filled_button_view.dart | import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:math_riddle/core/app_colors.dart';
import 'package:math_riddle/view/neopop_button/constants.dart';
import 'package:math_riddle/view/neopop_button/neopop_button_translator.dart';
class CommonFilledButtonView extends StatelessWidget {
final String label;
final bool isSelected;
final void Function(String) onPressed;
final double height;
final FontWeight fontWeight;
final double fontSize;
const CommonFilledButtonView({
required this.label,
required this.onPressed,
required this.height,
this.isSelected = false,
this.fontWeight = FontWeight.w500,
this.fontSize = 20,
super.key,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(0.5),
child: NeoPopButtonTranslator(
onPressed: () {
onPressed(label);
},
depth: kSmallButtonDepth,
child: Container(
color: isSelected ? AppColor.blue : AppColor.white,
constraints: BoxConstraints.expand(height: height),
alignment: Alignment.center,
child: Text(
label,
style: TextStyle(
fontSize: fontSize,
fontWeight: fontWeight,
color: isSelected ? AppColor.white : AppColor.black,
),
),
),
),
);
}
}
class CommonFilledEnterButtonView extends StatelessWidget {
final void Function() onPressed;
final double height;
const CommonFilledEnterButtonView({
required this.onPressed,
required this.height,
super.key,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(0.5),
child: NeoPopButtonTranslator(
onPressed: onPressed,
depth: kSmallButtonDepth,
child: Container(
color: AppColor.green,
constraints: BoxConstraints.expand(height: height),
alignment: Alignment.center,
child: Text(
"enter".tr(),
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: Colors.white,
),
),
),
),
);
}
}
class CommonFilledBackButtonView extends StatelessWidget {
final void Function() onPressed;
final double height;
const CommonFilledBackButtonView({
required this.onPressed,
required this.height,
super.key,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(0.5),
child: NeoPopButtonTranslator(
onPressed: onPressed,
depth: kSmallButtonDepth,
child: Container(
color: AppColor.red,
constraints: BoxConstraints.expand(height: height),
alignment: Alignment.center,
child: const Icon(
Icons.backspace_outlined,
color: Colors.white,
size: 16,
),
),
),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/custom_level_border.dart | import 'package:flutter/material.dart';
class CustomLevelBorder extends BoxBorder {
const CustomLevelBorder({
this.top = BorderSide.none,
this.right = BorderSide.none,
this.bottom = BorderSide.none,
this.left = BorderSide.none,
this.smallGap = 2,
this.largeGap = 17,
this.space = 4,
});
const CustomLevelBorder.fromBorderSide(
BorderSide side,
this.smallGap,
this.largeGap,
this.space,
) : top = side,
right = side,
bottom = side,
left = side;
factory CustomLevelBorder.all({
Color color = const Color(0xFF000000),
double width = 1.0,
BorderStyle style = BorderStyle.solid,
double strokeAlign = BorderSide.strokeAlignInside,
double smallGap = 2,
double largeGap = 17,
double space = 4,
}) {
final BorderSide side = BorderSide(
color: color, width: width, style: style, strokeAlign: strokeAlign);
return CustomLevelBorder.fromBorderSide(
side,
smallGap,
largeGap,
space,
);
}
@override
final BorderSide bottom;
@override
final BorderSide top;
final BorderSide right;
final BorderSide left;
final double smallGap;
final double largeGap;
final double space;
@override
EdgeInsetsGeometry get dimensions => EdgeInsets.all(top.strokeInset);
@override
bool get isUniform => true;
@override
void paint(
Canvas canvas,
Rect rect, {
TextDirection? textDirection,
BoxShape shape = BoxShape.rectangle,
BorderRadius? borderRadius,
}) {
final Paint paint = Paint()..strokeWidth = top.width;
final Path path = Path();
switch (top.style) {
case BorderStyle.solid:
paint.color = top.color;
path.reset();
path.moveTo(rect.left, rect.top);
path.lineTo(rect.left + space, rect.top);
path.moveTo(rect.left + space + largeGap, rect.top);
path.lineTo(rect.right - space - smallGap, rect.top);
path.moveTo(rect.right - space, rect.top);
path.lineTo(rect.right, rect.top);
paint.style = PaintingStyle.stroke;
paint.strokeCap = StrokeCap.round;
canvas.drawPath(path, paint);
break;
case BorderStyle.none:
break;
}
switch (right.style) {
case BorderStyle.solid:
paint.color = right.color;
path.reset();
path.moveTo(rect.right, rect.top);
path.lineTo(rect.right, rect.top + space);
path.moveTo(rect.right, rect.top + space + smallGap);
path.lineTo(rect.right, rect.bottom - space - largeGap);
path.moveTo(rect.right, rect.bottom - space);
path.lineTo(rect.right, rect.bottom);
paint.style = PaintingStyle.stroke;
paint.strokeCap = StrokeCap.round;
canvas.drawPath(path, paint);
break;
case BorderStyle.none:
break;
}
switch (bottom.style) {
case BorderStyle.solid:
paint.color = bottom.color;
path.reset();
path.moveTo(rect.left, rect.bottom);
path.lineTo(rect.left + space, rect.bottom);
path.moveTo(rect.left + space + largeGap, rect.bottom);
path.lineTo(rect.right - space - smallGap, rect.bottom);
path.moveTo(rect.right - space, rect.bottom);
path.lineTo(rect.right, rect.bottom);
paint.style = PaintingStyle.stroke;
paint.strokeCap = StrokeCap.round;
canvas.drawPath(path, paint);
break;
case BorderStyle.none:
break;
}
switch (left.style) {
case BorderStyle.solid:
paint.color = left.color;
path.reset();
path.moveTo(rect.left, rect.top);
path.lineTo(rect.left, rect.top + space);
path.moveTo(rect.left, rect.top + space + smallGap);
path.lineTo(rect.left, rect.bottom - space - largeGap);
path.moveTo(rect.left, rect.bottom - space);
path.lineTo(rect.left, rect.bottom);
paint.style = PaintingStyle.stroke;
paint.strokeCap = StrokeCap.round;
canvas.drawPath(path, paint);
break;
case BorderStyle.none:
break;
}
}
@override
ShapeBorder scale(double t) {
return Border(
top: top.scale(t),
right: right.scale(t),
bottom: bottom.scale(t),
left: left.scale(t),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/custom_image_button_border.dart | import 'package:flutter/material.dart';
class CustomImageButtonBorder extends BoxBorder {
const CustomImageButtonBorder({
this.top = BorderSide.none,
this.right = BorderSide.none,
this.bottom = BorderSide.none,
this.left = BorderSide.none,
});
const CustomImageButtonBorder.fromBorderSide(BorderSide side)
: top = side,
right = side,
bottom = side,
left = side;
factory CustomImageButtonBorder.all({
Color color = const Color(0xFF000000),
double width = 1.0,
BorderStyle style = BorderStyle.solid,
double strokeAlign = BorderSide.strokeAlignInside,
}) {
final BorderSide side = BorderSide(
color: color, width: width, style: style, strokeAlign: strokeAlign);
return CustomImageButtonBorder.fromBorderSide(side);
}
@override
final BorderSide bottom;
@override
final BorderSide top;
final BorderSide right;
final BorderSide left;
@override
EdgeInsetsGeometry get dimensions => EdgeInsets.all(top.strokeInset);
@override
bool get isUniform => true;
@override
void paint(
Canvas canvas,
Rect rect, {
TextDirection? textDirection,
BoxShape shape = BoxShape.rectangle,
BorderRadius? borderRadius,
}) {
final Paint paint = Paint()..strokeWidth = top.width;
final Path path = Path();
switch (top.style) {
case BorderStyle.solid:
paint.color = top.color;
path.reset();
path.moveTo(rect.left, rect.top);
path.lineTo(rect.right, rect.top);
paint.style = PaintingStyle.stroke;
paint.strokeCap = StrokeCap.round;
canvas.drawPath(path, paint);
break;
case BorderStyle.none:
break;
}
switch (right.style) {
case BorderStyle.solid:
paint.color = right.color;
path.reset();
path.moveTo(rect.right, rect.top);
path.lineTo(rect.right, rect.bottom);
paint.style = PaintingStyle.stroke;
paint.strokeCap = StrokeCap.round;
canvas.drawPath(path, paint);
break;
case BorderStyle.none:
break;
}
switch (bottom.style) {
case BorderStyle.solid:
paint.color = bottom.color;
path.reset();
path.moveTo(rect.left, rect.bottom);
path.lineTo(rect.right, rect.bottom);
paint.style = PaintingStyle.stroke;
paint.strokeCap = StrokeCap.round;
canvas.drawPath(path, paint);
break;
case BorderStyle.none:
break;
}
switch (left.style) {
case BorderStyle.solid:
paint.color = left.color;
path.reset();
path.moveTo(rect.left, rect.top);
path.lineTo(rect.left, rect.bottom);
paint.style = PaintingStyle.stroke;
paint.strokeCap = StrokeCap.round;
canvas.drawPath(path, paint);
break;
case BorderStyle.none:
break;
}
}
@override
ShapeBorder scale(double t) {
return Border(
top: top.scale(t),
right: right.scale(t),
bottom: bottom.scale(t),
left: left.scale(t),
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/common/common_image_button_view.dart | import 'package:flutter/material.dart';
import 'package:math_riddle/core/app_colors.dart';
import 'package:math_riddle/data/model/image_option.dart';
import 'package:math_riddle/view/common/custom_image_button_border.dart';
import 'package:math_riddle/view/neopop_button/constants.dart';
import 'package:math_riddle/view/neopop_button/neopop_button_translator.dart';
class CommonImageButtonView extends StatelessWidget {
final ImageOption imageOption;
final int index;
final List<bool> selectedList;
final void Function(ImageOption) onPressed;
const CommonImageButtonView({
required this.imageOption,
required this.index,
required this.selectedList,
required this.onPressed,
super.key,
});
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
border: CustomImageButtonBorder(
right: BorderSide(
color: selectedList[index] ? AppColor.blue : Colors.white,
width: selectedList[index] ? 2 : 1,
),
top: BorderSide(
color: selectedList[index] ? AppColor.blue : Colors.white,
width: selectedList[index] ? 2 : 1,
),
bottom: BorderSide(
color: selectedList[index] ? AppColor.blue : Colors.white,
width: selectedList[index] ? 2 : 1,
),
left: BorderSide(
color: getLeftBorderColor(),
width: selectedList[index] ? 2 : 1,
),
),
),
padding: const EdgeInsets.all(0.5),
child: NeoPopButtonTranslator(
onPressed: () {
onPressed(imageOption);
},
depth: kSmallButtonDepth,
child: Image.asset(
imageOption.image,
),
),
);
}
Color getLeftBorderColor() {
if (selectedList[0]) {
if (index == 0) {
return AppColor.blue;
} else if (index == 1) {
return Colors.transparent;
} else {
return AppColor.white;
}
} else if (selectedList[1]) {
if (index == 1) {
return AppColor.blue;
} else if (index == 2) {
return Colors.transparent;
} else {
return AppColor.white;
}
} else if (selectedList[2]) {
if (index == 2) {
return AppColor.blue;
} else if (index == 3) {
return Colors.transparent;
} else {
return AppColor.white;
}
} else if (selectedList[3]) {
if (index == 3) {
return AppColor.blue;
} else {
return AppColor.white;
}
} else {
return AppColor.white;
}
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/view | mirrored_repositories/math-riddle-free/lib/view/session/play_session_screen.dart | import 'dart:async';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:go_router/go_router.dart';
import 'package:logging/logging.dart' hide Level;
import 'package:math_riddle/core/app_colors.dart';
import 'package:math_riddle/core/app_constant.dart';
import 'package:math_riddle/data/audio/audio_controller.dart';
import 'package:math_riddle/data/audio/sounds.dart';
import 'package:math_riddle/data/model/base_level.dart';
import 'package:math_riddle/data/model/option.dart';
import 'package:math_riddle/data/model/score.dart';
import 'package:math_riddle/data/player_progress/player_progress.dart';
import 'package:math_riddle/data/puzzle/i_puzzle_repository.dart';
import 'package:math_riddle/data/rating/rate_us_controller.dart';
import 'package:math_riddle/view/common/common_scaffold_view.dart';
import 'package:math_riddle/view/common/image_option_view.dart';
import 'package:math_riddle/view/common/numpad_view.dart';
import 'package:math_riddle/view/common/option_view.dart';
import 'package:math_riddle/view/hint/hint_screen.dart';
import 'package:math_riddle/view/level/level_state.dart';
import 'package:math_riddle/view/rate_us/rate_us_screen.dart';
import 'package:math_riddle/view/win/win_game_screen.dart';
import 'package:provider/provider.dart';
import 'package:tuple/tuple.dart';
import 'package:wakelock/wakelock.dart';
class PlaySessionScreen extends StatelessWidget {
final int position;
const PlaySessionScreen(this.position, {super.key});
@override
Widget build(BuildContext context) {
IPuzzleRepository puzzleRepository = context.read<IPuzzleRepository>();
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => LevelState(
position: position,
puzzleRepository: puzzleRepository,
),
),
],
child: LevelStateScreen(
position,
puzzleRepository,
),
);
}
}
class LevelStateScreen extends StatefulWidget {
final int position;
final IPuzzleRepository puzzleRepository;
const LevelStateScreen(this.position, this.puzzleRepository, {super.key});
@override
State<LevelStateScreen> createState() => _LevelStateScreenState();
}
class _LevelStateScreenState extends State<LevelStateScreen> {
static final _log = Logger('LevelStateScreen');
static const _celebrationDuration = Duration(milliseconds: 400);
static const _preCelebrationDuration = Duration(milliseconds: 50);
late DateTime _startOfPlay;
late AnimationController animationController;
@override
void initState() {
super.initState();
_startOfPlay = DateTime.now();
Wakelock.enable();
}
@override
void dispose() {
Wakelock.disable();
super.dispose();
}
@override
Widget build(BuildContext context) {
return CommonScaffoldView(
title: Selector<LevelState, int>(
selector: (p0, p1) => p1.level.position,
builder: (context, value, child) {
return Text("${"level".tr()} $value");
},
),
actions: [
Selector<LevelState, int>(
selector: (p0, p1) => p1.level.id,
builder: (context, value, child) {
return "${value}_hint".tr().isEmpty
? const SizedBox()
: IconButton(
icon: const Icon(Icons.help_outline),
onPressed: () async {
final audioController = context.read<AudioController>();
audioController.playSfx(SfxType.iconButtonTap);
await showDialog<void>(
context: context,
builder: (context) {
return HintScreen(hint: "${value}_hint".tr());
},
);
},
);
},
),
],
body: Column(
children: [
Expanded(
child: Column(
children: [
const SizedBox(height: 24),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Selector<LevelState, Tuple2<int, int>>(
selector: (p0, p1) {
return Tuple2(p1.level.position, p1.level.id);
},
builder: (context, value, child) {
return Text(
key: ValueKey(value),
"${"${value.item2}_question".tr()}\n",
textAlign: TextAlign.center,
maxLines: 2,
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.w500,
height: 1.1,
),
).animate(key: ValueKey(value.item1)).fade().scaleX(
begin: .5,
end: 1,
curve: Curves.easeOutBack,
duration: 600.milliseconds,
);
},
),
),
const SizedBox(height: 24),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Selector<LevelState, Tuple2<int, String>>(
selector: (p0, p1) {
return Tuple2(p1.level.position, p1.level.image);
},
builder: (context, value, child) {
return Image.asset(
key: ValueKey(value),
value.item2,
).animate(key: ValueKey(value.item1)).fade()
..scaleXY(
begin: 0.5,
end: 1,
curve: Curves.easeOutBack,
duration: 600.milliseconds,
);
},
)
.animate(
autoPlay: false,
onInit: (controller) {
animationController = controller;
},
)
.shimmer(
duration: 1000.ms,
color: AppColor.red,
) // shimmer +
.shake(hz: 4, curve: Curves.easeInOutCubic) // shake +
.scaleXY(
begin: 1,
end: 0.9,
duration: 400.ms,
) // scale up
.then(delay: 200.ms) // then wait and
.scaleXY(
begin: 0.9,
end: 1,
duration: 400.ms,
),
),
),
const SizedBox(height: 24),
],
),
),
LayoutBuilder(builder: (context, constraints) {
double height = (constraints.maxWidth / 7.5);
return SizedBox(
height: (height * 3) + 2,
child: Selector<LevelState, Tuple2<BaseLevel, List<Option>>>(
selector: (p0, p1) => Tuple2(p1.level, p1.optionList),
builder: (context, value, child) {
return AnimatedSwitcher(
duration: const Duration(milliseconds: 900),
transitionBuilder: (child, animation) {
return FadeTransition(
key: ValueKey<Key?>(child.key),
opacity: animation,
child: SlideTransition(
position: Tween(
begin: const Offset(0.0, 1.0),
end: const Offset(0.0, 0.0),
).animate(animation),
child: child,
),
);
},
child: (value.item1.gameType == GameType.numpad)
? NumPadView(
key: const ValueKey(GameType.numpad),
onWin: _playerWon,
onWrong: _playerWrong,
height: height,
)
: (value.item1.gameType == GameType.option
? OptionView(
key: const ValueKey(GameType.option),
list: value.item2,
onWin: _playerWon,
onWrong: _playerWrong,
height: height,
)
: ImageOptionView(
key: const ValueKey(GameType.imageOption),
list: value.item2,
onWin: _playerWon,
onWrong: _playerWrong,
height: height,
)),
);
},
),
);
}),
],
),
);
}
Future<void> _playerWon() async {
BaseLevel level = context.read<LevelState>().level;
_log.info('Level ${level.position} won');
final score = Score(
level.position,
level.difficulty,
DateTime.now().difference(_startOfPlay),
);
final playerProgress = context.read<PlayerProgress>();
playerProgress.setLevelReached(level.position);
// Let the player see the game just after winning for a bit.
await Future<void>.delayed(_preCelebrationDuration);
if (!mounted) return;
final audioController = context.read<AudioController>();
audioController.playSfx(SfxType.congrats);
if (!mounted) return;
await showDialog<void>(
context: context,
builder: (context) {
return WinGameScreen(score: score);
},
);
await Future<void>.delayed(_celebrationDuration);
if (mounted) {
if (level.position + 1 <
widget.puzzleRepository.getGameLevelByOrder().length + 1) {
_startOfPlay = DateTime.now();
context.read<LevelState>().levelUp(newPosition: level.position + 1);
RateUsController rateUsController = context.read<RateUsController>();
if (level.position + 1 == 10 &&
!rateUsController.isRemindMeLater &&
!rateUsController.isRated) {
await showDialog<void>(
context: context,
builder: (context) {
return const RateUsScreen();
},
);
} else if (level.position + 1 == 25 &&
rateUsController.isRemindMeLater &&
!rateUsController.is2ndTimeRemindMeLater &&
!rateUsController.isRated) {
await showDialog<void>(
context: context,
builder: (context) {
return const RateUsScreen();
},
);
}
} else {
GoRouter.of(context).pop();
}
}
}
Future<void> _playerWrong() async {
animationController.forward(from: 0);
BaseLevel level = context.read<LevelState>().level;
_log.info('Level ${level.position} wrong');
if (!mounted) return;
final audioController = context.read<AudioController>();
audioController.playSfx(SfxType.wrong);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data | mirrored_repositories/math-riddle-free/lib/data/player_progress/player_progress.dart | import 'dart:async';
import 'package:flutter/foundation.dart';
import 'persistence/player_progress_persistence.dart';
/// Encapsulates the player's progress.
class PlayerProgress extends ChangeNotifier {
static const maxHighestScoresPerPlayer = 10;
final PlayerProgressPersistence _store;
int _highestLevelReached = 0;
/// Creates an instance of [PlayerProgress] backed by an injected
/// persistence [store].
PlayerProgress(PlayerProgressPersistence store) : _store = store;
/// The highest level that the player has reached so far.
int get highestLevelReached => _highestLevelReached;
/// Fetches the latest data from the backing persistence store.
Future<void> getLatestFromStore() async {
final level = await _store.getHighestLevelReached();
if (level > _highestLevelReached) {
_highestLevelReached = level;
notifyListeners();
} else if (level < _highestLevelReached) {
await _store.saveHighestLevelReached(_highestLevelReached);
}
}
/// Resets the player's progress so it's like if they just started
/// playing the game for the first time.
void reset() {
_highestLevelReached = 0;
notifyListeners();
_store.saveHighestLevelReached(_highestLevelReached);
}
/// Registers [level] as reached.
///
/// If this is higher than [highestLevelReached], it will update that
/// value and save it to the injected persistence store.
void setLevelReached(int level) {
if (level > _highestLevelReached) {
_highestLevelReached = level;
notifyListeners();
unawaited(_store.saveHighestLevelReached(level));
}
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data/player_progress | mirrored_repositories/math-riddle-free/lib/data/player_progress/persistence/local_storage_player_progress_persistence.dart | import 'package:shared_preferences/shared_preferences.dart';
import 'player_progress_persistence.dart';
/// An implementation of [PlayerProgressPersistence] that uses
/// `package:shared_preferences`.
class LocalStoragePlayerProgressPersistence extends PlayerProgressPersistence {
final Future<SharedPreferences> instanceFuture =
SharedPreferences.getInstance();
@override
Future<int> getHighestLevelReached() async {
final prefs = await instanceFuture;
return prefs.getInt('highestLevelReached') ?? 0;
}
@override
Future<void> saveHighestLevelReached(int level) async {
final prefs = await instanceFuture;
await prefs.setInt('highestLevelReached', level);
}
@override
Future<int> getAppOpenCount() async {
final prefs = await instanceFuture;
return prefs.getInt('appOpenCount') ?? 0;
}
@override
Future<void> setAppOpenCount() async {
final prefs = await instanceFuture;
int count = await getAppOpenCount();
await prefs.setInt('appOpenCount', count + 1);
}
@override
Future<bool> isRated() async {
final prefs = await instanceFuture;
return prefs.getBool('isRated') ?? false;
}
@override
Future<void> setRated() async {
final prefs = await instanceFuture;
await prefs.setBool('isRated', true);
}
@override
Future<bool> isRemindMeLater() async {
final prefs = await instanceFuture;
return prefs.getBool('isRemindMeLater') ?? false;
}
@override
Future<void> setRemindMeLater() async {
final prefs = await instanceFuture;
await prefs.setBool('isRemindMeLater', true);
}
@override
Future<bool> is2ndTimeRemindMeLater() async {
final prefs = await instanceFuture;
return prefs.getBool('is2ndTimeRemindMeLater') ?? false;
}
@override
Future<void> set2ndTimeRemindMeLater() async {
final prefs = await instanceFuture;
await prefs.setBool('is2ndTimeRemindMeLater', true);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data/player_progress | mirrored_repositories/math-riddle-free/lib/data/player_progress/persistence/memory_player_progress_persistence.dart | import 'player_progress_persistence.dart';
/// An in-memory implementation of [PlayerProgressPersistence].
/// Useful for testing.
class MemoryOnlyPlayerProgressPersistence implements PlayerProgressPersistence {
int level = 0;
@override
Future<int> getHighestLevelReached() async {
await Future<void>.delayed(const Duration(milliseconds: 500));
return level;
}
@override
Future<void> saveHighestLevelReached(int level) async {
await Future<void>.delayed(const Duration(milliseconds: 500));
this.level = level;
}
@override
Future<int> getAppOpenCount() {
throw UnimplementedError();
}
@override
Future<bool> isRated() {
throw UnimplementedError();
}
@override
Future<bool> isRemindMeLater() {
throw UnimplementedError();
}
@override
Future<void> setAppOpenCount() {
throw UnimplementedError();
}
@override
Future<void> setRated() {
throw UnimplementedError();
}
@override
Future<void> setRemindMeLater() {
throw UnimplementedError();
}
@override
Future<bool> is2ndTimeRemindMeLater() {
throw UnimplementedError();
}
@override
Future<void> set2ndTimeRemindMeLater() {
throw UnimplementedError();
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data/player_progress | mirrored_repositories/math-riddle-free/lib/data/player_progress/persistence/player_progress_persistence.dart | /// An interface of persistence stores for the player's progress.
///
/// Implementations can range from simple in-memory storage through
/// local preferences to cloud saves.
abstract class PlayerProgressPersistence {
Future<int> getHighestLevelReached();
Future<void> saveHighestLevelReached(int level);
Future<int> getAppOpenCount();
Future<void> setAppOpenCount();
Future<bool> isRated();
Future<void> setRated();
Future<bool> isRemindMeLater();
Future<bool> is2ndTimeRemindMeLater();
Future<void> setRemindMeLater();
Future<void> set2ndTimeRemindMeLater();
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data | mirrored_repositories/math-riddle-free/lib/data/audio/audio_controller.dart | import 'dart:collection';
import 'dart:math';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/widgets.dart';
import 'package:logging/logging.dart';
import 'package:math_riddle/data/setting/settings.dart';
import 'songs.dart';
import 'sounds.dart';
/// Allows playing music and sound. A facade to `package:audioplayers`.
class AudioController {
static final _log = Logger('AudioController');
final AudioPlayer _musicPlayer;
/// This is a list of [AudioPlayer] instances which are rotated to play
/// sound effects.
final List<AudioPlayer> _sfxPlayers;
int _currentSfxPlayer = 0;
final Queue<Song> _playlist;
final Random _random = Random();
SettingsController? _settings;
ValueNotifier<AppLifecycleState>? _lifecycleNotifier;
/// Creates an instance that plays music and sound.
///
/// Use [polyphony] to configure the number of sound effects (SFX) that can
/// play at the same time. A [polyphony] of `1` will always only play one
/// sound (a new sound will stop the previous one). See discussion
/// of [_sfxPlayers] to learn why this is the case.
///
/// Background music does not count into the [polyphony] limit. Music will
/// never be overridden by sound effects because that would be silly.
AudioController({int polyphony = 2})
: assert(polyphony >= 1),
_musicPlayer = AudioPlayer(playerId: 'musicPlayer'),
_sfxPlayers = Iterable.generate(
polyphony, (i) => AudioPlayer(playerId: 'sfxPlayer#$i'))
.toList(growable: false),
_playlist = Queue.of(List<Song>.of(songs)..shuffle()) {
_musicPlayer.onPlayerComplete.listen(_changeSong);
}
/// Enables the [AudioController] to listen to [AppLifecycleState] events,
/// and therefore do things like stopping playback when the game
/// goes into the background.
void attachLifecycleNotifier(
ValueNotifier<AppLifecycleState> lifecycleNotifier) {
_lifecycleNotifier?.removeListener(_handleAppLifecycle);
lifecycleNotifier.addListener(_handleAppLifecycle);
_lifecycleNotifier = lifecycleNotifier;
}
/// Enables the [AudioController] to track changes to settings.
/// Namely, when any of [SettingsController.muted],
/// [SettingsController.musicOn] or [SettingsController.soundsOn] changes,
/// the audio controller will act accordingly.
void attachSettings(SettingsController settingsController) {
if (_settings == settingsController) {
// Already attached to this instance. Nothing to do.
return;
}
// Remove handlers from the old settings controller if present
final oldSettings = _settings;
if (oldSettings != null) {
oldSettings.muted.removeListener(_mutedHandler);
oldSettings.musicOn.removeListener(_musicOnHandler);
oldSettings.soundsOn.removeListener(_soundsOnHandler);
}
_settings = settingsController;
// Add handlers to the new settings controller
settingsController.muted.addListener(_mutedHandler);
settingsController.musicOn.addListener(_musicOnHandler);
settingsController.soundsOn.addListener(_soundsOnHandler);
if (!settingsController.muted.value && settingsController.musicOn.value) {
_startMusic();
}
}
void dispose() {
_lifecycleNotifier?.removeListener(_handleAppLifecycle);
_stopAllSound();
_musicPlayer.dispose();
for (final player in _sfxPlayers) {
player.dispose();
}
}
/// Preloads all sound effects.
Future<void> initialize() async {
_log.info('Preloading sound effects');
// This assumes there is only a limited number of sound effects in the game.
// If there are hundreds of long sound effect files, it's better
// to be more selective when preloading.
await AudioCache.instance.loadAll(SfxType.values
.expand(soundTypeToFilename)
.map((path) => 'sfx/$path')
.toList());
}
/// Plays a single sound effect, defined by [type].
///
/// The controller will ignore this call when the attached settings'
/// [SettingsController.muted] is `true` or if its
/// [SettingsController.soundsOn] is `false`.
void playSfx(SfxType type) {
final muted = _settings?.muted.value ?? true;
if (muted) {
_log.info(() => 'Ignoring playing sound ($type) because audio is muted.');
return;
}
final soundsOn = _settings?.soundsOn.value ?? false;
if (!soundsOn) {
_log.info(() =>
'Ignoring playing sound ($type) because sounds are turned off.');
return;
}
_log.info(() => 'Playing sound: $type');
final options = soundTypeToFilename(type);
final filename = options[_random.nextInt(options.length)];
_log.info(() => '- Chosen filename: $filename');
final currentPlayer = _sfxPlayers[_currentSfxPlayer];
currentPlayer.play(AssetSource('sfx/$filename'),
volume: soundTypeToVolume(type));
_currentSfxPlayer = (_currentSfxPlayer + 1) % _sfxPlayers.length;
}
void _changeSong(void _) {
_log.info('Last song finished playing.');
// Put the song that just finished playing to the end of the playlist.
_playlist.addLast(_playlist.removeFirst());
// Play the next song.
_playFirstSongInPlaylist();
}
void _handleAppLifecycle() {
switch (_lifecycleNotifier!.value) {
case AppLifecycleState.paused:
case AppLifecycleState.detached:
_stopAllSound();
break;
case AppLifecycleState.resumed:
if (!_settings!.muted.value && _settings!.musicOn.value) {
_resumeMusic();
}
break;
case AppLifecycleState.inactive:
// No need to react to this state change.
break;
}
}
void _musicOnHandler() {
if (_settings!.musicOn.value) {
// Music got turned on.
if (!_settings!.muted.value) {
_resumeMusic();
}
} else {
// Music got turned off.
_stopMusic();
}
}
void _mutedHandler() {
if (_settings!.muted.value) {
// All sound just got muted.
_stopAllSound();
} else {
// All sound just got un-muted.
if (_settings!.musicOn.value) {
_resumeMusic();
}
}
}
Future<void> _playFirstSongInPlaylist() async {
_log.info(() => 'Playing ${_playlist.first} now.');
await _musicPlayer.play(AssetSource('music/${_playlist.first.filename}'));
}
Future<void> _resumeMusic() async {
_log.info('Resuming music');
switch (_musicPlayer.state) {
case PlayerState.paused:
_log.info('Calling _musicPlayer.resume()');
try {
await _musicPlayer.resume();
} catch (e) {
// Sometimes, resuming fails with an "Unexpected" error.
_log.severe(e);
await _playFirstSongInPlaylist();
}
break;
case PlayerState.stopped:
_log.info("resumeMusic() called when music is stopped. "
"This probably means we haven't yet started the music. "
"For example, the game was started with sound off.");
await _playFirstSongInPlaylist();
break;
case PlayerState.playing:
_log.warning('resumeMusic() called when music is playing. '
'Nothing to do.');
break;
case PlayerState.completed:
_log.warning('resumeMusic() called when music is completed. '
"Music should never be 'completed' as it's either not playing "
"or looping forever.");
await _playFirstSongInPlaylist();
break;
}
}
void _soundsOnHandler() {
for (final player in _sfxPlayers) {
if (player.state == PlayerState.playing) {
player.stop();
}
}
}
void _startMusic() {
_log.info('starting music');
_playFirstSongInPlaylist();
}
void _stopAllSound() {
if (_musicPlayer.state == PlayerState.playing) {
_musicPlayer.pause();
}
for (final player in _sfxPlayers) {
player.stop();
}
}
void _stopMusic() {
_log.info('Stopping music');
if (_musicPlayer.state == PlayerState.playing) {
_musicPlayer.pause();
}
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data | mirrored_repositories/math-riddle-free/lib/data/audio/songs.dart | const Set<Song> songs = {
// Filenames with whitespace break package:audioplayers on iOS
// (as of February 2022), so we use no whitespace.
Song('ambient-inspiration-136110.mp3', 'Ambient Inspiration',
artist: 'The Mountain'),
Song('inspirational-background-112290.mp3', 'Inspiration Background',
artist: 'AudioCoffee'),
};
class Song {
final String filename;
final String name;
final String? artist;
const Song(this.filename, this.name, {this.artist});
@override
String toString() => 'Song<$filename>';
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data | mirrored_repositories/math-riddle-free/lib/data/audio/sounds.dart | List<String> soundTypeToFilename(SfxType type) {
switch (type) {
case SfxType.click:
return const [
'1_click.wav',
];
case SfxType.clickBack:
return const [
'1_click_back.wav',
];
case SfxType.wrong:
return const [
'1_wrong.mp3',
];
case SfxType.buttonTap:
return const [
'1_transition.wav',
];
case SfxType.iconButtonTap:
return const [
'1_ball.wav',
];
case SfxType.congrats:
return const ["1_win.mp3"];
}
}
/// Allows control over loudness of different SFX types.
double soundTypeToVolume(SfxType type) {
switch (type) {
case SfxType.buttonTap:
case SfxType.iconButtonTap:
case SfxType.wrong:
case SfxType.click:
case SfxType.clickBack:
case SfxType.congrats:
return 1.0;
}
}
enum SfxType {
click,
clickBack,
wrong,
buttonTap,
iconButtonTap,
congrats,
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data | mirrored_repositories/math-riddle-free/lib/data/model/language.dart | import 'package:flutter/widgets.dart';
class Language {
final String name;
final String flag;
final Locale locale;
const Language({
required this.name,
required this.flag,
required this.locale,
});
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data | mirrored_repositories/math-riddle-free/lib/data/model/image_option.dart | import 'package:math_riddle/data/model/option.dart';
class ImageOption extends Option {
final String image;
const ImageOption({
required this.image,
required super.name,
super.isSelected,
});
@override
ImageOption copyWith({
String? name,
String? image,
bool? isSelected,
}) {
return ImageOption(
name: name ?? this.name,
image: image ?? this.image,
isSelected: isSelected ?? this.isSelected,
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data | mirrored_repositories/math-riddle-free/lib/data/model/option.dart | class Option {
final String name;
final bool isSelected;
const Option({
required this.name,
this.isSelected = false,
});
Option copyWith({
String? name,
bool? isSelected,
}) {
return Option(
name: name ?? this.name,
isSelected: isSelected ?? this.isSelected,
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data | mirrored_repositories/math-riddle-free/lib/data/model/score.dart | import 'package:flutter/foundation.dart';
/// Encapsulates a score and the arithmetic to compute it.
@immutable
class Score {
final int score;
final Duration duration;
final int level;
factory Score(int level, int difficulty, Duration duration) {
// The higher the difficulty, the higher the score.
var score = difficulty;
// The lower the time to beat the level, the higher the score.
score *= 10000 ~/ (duration.inSeconds.abs() + 1);
return Score._(score, duration, level);
}
const Score._(this.score, this.duration, this.level);
String get formattedTime {
final buf = StringBuffer();
if (duration.inHours > 0) {
buf.write('${duration.inHours}');
buf.write(':');
}
final minutes = duration.inMinutes % Duration.minutesPerHour;
if (minutes > 9) {
buf.write('$minutes');
} else {
buf.write('0');
buf.write('$minutes');
}
buf.write(':');
buf.write((duration.inSeconds % Duration.secondsPerMinute)
.toString()
.padLeft(2, '0'));
return buf.toString();
}
@override
String toString() => 'Score<$score,$formattedTime,$level>';
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data | mirrored_repositories/math-riddle-free/lib/data/model/image_option_level.dart | import 'package:math_riddle/core/app_constant.dart';
import 'package:math_riddle/data/model/option_level.dart';
class ImageOptionLevel extends OptionLevel {
const ImageOptionLevel({
super.position,
required super.id,
super.gameType = GameType.imageOption,
required super.difficulty,
required super.image,
required super.answer,
required super.optionList,
});
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data | mirrored_repositories/math-riddle-free/lib/data/model/option_level.dart | import 'package:math_riddle/core/app_constant.dart';
import 'package:math_riddle/data/model/base_level.dart';
import 'package:math_riddle/data/model/option.dart';
class OptionLevel extends BaseLevel {
final List<Option> optionList;
const OptionLevel({
super.position,
required super.id,
super.gameType = GameType.option,
required super.difficulty,
required super.image,
required super.answer,
this.optionList = abcdOption,
});
@override
OptionLevel copyWith({
int? position,
int? id,
GameType? gameType,
int? difficulty,
String? image,
String? answer,
List<Option>? optionList,
}) {
return OptionLevel(
position: position ?? this.position,
id: id ?? this.id,
gameType: gameType ?? this.gameType,
difficulty: difficulty ?? this.difficulty,
image: image ?? this.image,
answer: answer ?? this.answer,
optionList: optionList ?? this.optionList,
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data | mirrored_repositories/math-riddle-free/lib/data/model/base_level.dart | import 'package:math_riddle/core/app_constant.dart';
class BaseLevel {
final int position;
final int id;
final GameType gameType;
final int difficulty;
final String image;
final String answer;
const BaseLevel({
this.position = 1,
required this.id,
this.gameType = GameType.numpad,
required this.difficulty,
required this.image,
required this.answer,
});
BaseLevel copyWith({
int? position,
int? id,
GameType? gameType,
int? difficulty,
String? image,
String? answer,
}) {
return BaseLevel(
position: position ?? this.position,
id: id ?? this.id,
gameType: gameType ?? this.gameType,
difficulty: difficulty ?? this.difficulty,
image: image ?? this.image,
answer: answer ?? this.answer,
);
}
}
| 0 |
mirrored_repositories/math-riddle-free/lib/data | mirrored_repositories/math-riddle-free/lib/data/persistence/memory_settings_persistence.dart | import 'package:math_riddle/data/persistence/settings_persistence.dart';
/// An in-memory implementation of [SettingsPersistence].
/// Useful for testing.
class MemoryOnlySettingsPersistence implements SettingsPersistence {
bool musicOn = true;
bool soundsOn = true;
bool muted = false;
String playerName = 'Player';
@override
Future<bool> getMusicOn() async => musicOn;
@override
Future<bool> getMuted({required bool defaultValue}) async => muted;
@override
Future<String> getPlayerName() async => playerName;
@override
Future<bool> getSoundsOn() async => soundsOn;
@override
Future<void> saveMusicOn(bool value) async => musicOn = value;
@override
Future<void> saveMuted(bool value) async => muted = value;
@override
Future<void> savePlayerName(String value) async => playerName = value;
@override
Future<void> saveSoundsOn(bool value) async => soundsOn = value;
}
| 0 |
Subsets and Splits