repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/shared/custom_button.dart | import 'package:flutter/material.dart';
class CustomButton extends StatelessWidget {
const CustomButton(
{Key? key,
required this.btnColor,
required this.textColor,
required this.textButton,
required this.onPressed})
: super(key: key);
final Color btnColor;
final Color textColor;
final String textButton;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return MaterialButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
elevation: 0.0,
highlightElevation: 0.0,
color: btnColor,
padding: EdgeInsets.symmetric(vertical: 8.0),
onPressed: onPressed,
child: Text(
textButton,
style: TextStyle(
color: textColor, fontSize: 10, fontWeight: FontWeight.w700),
),
);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/shared/loading_dialog.dart | import 'package:flutter/material.dart';
class LoadingDialog extends StatelessWidget {
const LoadingDialog({Key? key, this.message = 'Please wait'})
: super(key: key);
final String message;
@override
Widget build(BuildContext context) {
return Dialog(
child: ColoredBox(
color: Colors.white,
child: SizedBox(
height: 100.0,
width: 100.0,
child: Padding(
padding:
const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
height: 32.0,
width: 32.0,
child: CircularProgressIndicator()),
SizedBox(width: 32.0),
Text(
message,
style: TextStyle(
fontSize: 16,
color: Colors.black,
fontWeight: FontWeight.w500),
),
],
),
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/shared/custom_reviews_card.dart | import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:restaurant_app/bloc/restaurant/model/customer_reviews.dart';
import 'package:restaurant_app/utils/assets.dart';
import 'package:restaurant_app/utils/colors.dart';
class CustomReviewsCard extends StatelessWidget {
final CustomerReviews customerReviews;
const CustomReviewsCard({Key? key, required this.customerReviews})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(right: 8),
padding: EdgeInsets.all(8),
width: MediaQuery.of(context).size.width / 2,
decoration: BoxDecoration(
color: whiteColor,
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
SvgPicture.asset(
USER_ICON,
width: 40,
),
SizedBox(
width: 8,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
customerReviews.name,
style: Theme.of(context).textTheme.subtitle2,
),
SizedBox(
height: 4,
),
Text(
customerReviews.date,
style: TextStyle(fontSize: 11),
),
],
),
)
],
),
SizedBox(
height: 8,
),
Text(
customerReviews.review,
overflow: TextOverflow.ellipsis,
maxLines: 3,
style: TextStyle(color: Colors.black),
),
],
),
);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/shared/custom_loading_indicator.dart | import 'package:flutter/material.dart';
class CustomLoadingIndicator extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(child: CircularProgressIndicator());
}
} | 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/shared/custom_menus_card.dart | import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class CustomMenusCard extends StatelessWidget {
final String image, name;
const CustomMenusCard({Key? key, required this.image, required this.name})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width / 2,
child: InkWell(
borderRadius: BorderRadius.circular(10),
onTap: () {
Fluttertoast.showToast(msg: name);
},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Stack(
children: <Widget>[
Container(
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
child: Container(
height: MediaQuery.of(context).size.width / 3,
width: MediaQuery.of(context).size.width / 2,
decoration: BoxDecoration(image: DecorationImage(
image: AssetImage(image),
fit: BoxFit.cover
)),
)),
),
///Stack 2
Container(
height: MediaQuery.of(context).size.width / 3,
width: MediaQuery.of(context).size.width / 2,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [0.1, 0.98],
colors: [Colors.transparent, Colors.grey[900]!])),
),
///Stack 3
Positioned(
left: 0,
bottom: 0,
child: Container(
width: MediaQuery.of(context).size.width / 2,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
),
padding: EdgeInsets.only(left: 6.0, bottom: 5.0, right: 6.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
name,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 14.0),
),
SizedBox(
height: 10.0,
),
],
),
),
)
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/shared/custom_error_image.dart | import 'package:flutter/material.dart';
class CustomErrorImage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(child: Icon(Icons.error));
}
} | 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/detail/detail_restaurant_page.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:restaurant_app/bloc/restaurant/mapper/restaurant_mapper.dart';
import 'package:restaurant_app/bloc/restaurant/model/detail_restaurant.dart';
import 'package:restaurant_app/bloc/restaurant/restaurant.dart';
import 'package:restaurant_app/ui/detail/components/container_customer_reviews.dart';
import 'package:restaurant_app/ui/detail/components/container_drinks.dart';
import 'package:restaurant_app/ui/detail/components/container_foods.dart';
import 'package:restaurant_app/ui/review/add_review_page.dart';
import 'package:restaurant_app/ui/shared/custom_button.dart';
import 'package:restaurant_app/utils/assets.dart';
import 'package:restaurant_app/utils/colors.dart';
import 'package:restaurant_app/utils/dialog_utils.dart';
import '../shared/custom_error_image.dart';
import '../shared/custom_loading_indicator.dart';
class DetailRestaurantPage extends StatefulWidget {
final String id;
const DetailRestaurantPage({Key? key, required this.id}) : super(key: key);
static const String routeName = '/detail_restaurant';
@override
_DetailRestaurantPageState createState() => _DetailRestaurantPageState();
}
const double _silverAppBarExtendedHeight = 300.0;
const double _paddingTopOfTitle = 20.0;
class _DetailRestaurantPageState extends State<DetailRestaurantPage> {
var _top = 0.0;
final _scrollDistance = _silverAppBarExtendedHeight - kToolbarHeight;
ValueNotifier<double> _collapsingAppBarNotifier = ValueNotifier(0.0);
late ScrollController _scrollController;
@override
void dispose() {
super.dispose();
_scrollController.dispose();
}
@override
void initState() {
super.initState();
_fetchRestaurantDetail();
_checkFavoriteById();
_scrollController = ScrollController();
_scrollController.addListener(() {
_collapsingAppBarNotifier.value = _scrollController.offset;
});
}
Widget _appBarTitle(String name) {
return ValueListenableBuilder(
valueListenable: _collapsingAppBarNotifier,
builder: (BuildContext context, double value, Widget? child) {
if (value >= _scrollDistance) {
return Text(
name,
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.w700,
),
);
} else {
return SizedBox.shrink();
}
},
);
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
_fetchFavorites();
return true;
},
child: Scaffold(
body: MultiBlocListener(
child: _blocDetailRestaurant(),
listeners: [
BlocListener<RestaurantBloc, RestaurantState>(
listener: (context, state) {
if (state is AddToFavoriteLoadingState) {
showLoading(context);
} else if (state is AddToFavoriteSuccessState) {
hideLoading(context);
_checkFavoriteById();
Fluttertoast.showToast(msg: 'Restaurant added to favorite');
} else if (state is AddToFavoriteErrorState) {
hideLoading(context);
Fluttertoast.showToast(msg: 'something wrong');
}
},
),
BlocListener<RestaurantBloc, RestaurantState>(
listener: (context, state) {
if (state is DeleteFavoriteLoadingState) {
showLoading(context);
} else if (state is DeleteFavoriteSuccessState) {
hideLoading(context);
_checkFavoriteById();
Fluttertoast.showToast(msg: 'Remove from favorite');
} else if (state is DeleteFavoriteErrorState) {
hideLoading(context);
Fluttertoast.showToast(msg: 'something wrong');
}
},
),
],
),
),
);
}
_blocDetailRestaurant() {
return BlocBuilder<RestaurantBloc, RestaurantState>(
buildWhen: (previousState, state) {
return state is FetchRestaurantDetailLoadingState ||
state is FetchRestaurantDetailSuccessState ||
state is FetchRestaurantDetailErrorState;
},
builder: (context, state) {
if (state is FetchRestaurantDetailSuccessState) {
DetailRestaurant detailRestaurant = state.detailRestaurant;
return _buildPage(detailRestaurant);
} else if (state is FetchRestaurantDetailLoadingState) {
return Padding(
padding: EdgeInsets.only(top: 100),
child: Center(
child: CircularProgressIndicator(),
),
);
} else if (state is FetchRestaurantDetailErrorState) {
return Center(
child: Center(
child: Text(state.message),
),
);
} else {
return Padding(
padding: EdgeInsets.only(top: 100),
child: Center(
child: CircularProgressIndicator(),
),
);
}
},
);
}
_buildPage(DetailRestaurant detailRestaurant) {
return CustomScrollView(
controller: _scrollController,
slivers: [
SliverAppBar(
brightness: Brightness.dark,
backgroundColor: primaryColor,
elevation: 0.0,
expandedHeight: _silverAppBarExtendedHeight,
floating: false,
leading: Container(
margin: EdgeInsets.only(left: 16),
decoration: BoxDecoration(
color: primaryColor.withOpacity(0.50), shape: BoxShape.circle),
child: GestureDetector(
child: Icon(Icons.arrow_back),
onTap: () => Navigator.maybePop(context),
),
),
title: _appBarTitle(detailRestaurant.name),
pinned: true,
flexibleSpace: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
_top = constraints.biggest.height;
return Stack(
children: [
FlexibleSpaceBar(
background: Hero(
tag: detailRestaurant.pictureId,
child: CachedNetworkImage(
fit: BoxFit.cover,
imageUrl: LARGE_IMAGE_URL + detailRestaurant.pictureId,
placeholder: (context, url) => CustomLoadingIndicator(),
errorWidget: (context, url, error) =>
CustomErrorImage(),
),
),
),
Visibility(
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
height: _paddingTopOfTitle,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(24.0),
topRight: Radius.circular(24.0),
),
color: Colors.white,
),
),
),
visible: (_top >
MediaQuery.of(context).padding.top + kToolbarHeight),
),
],
);
},
),
),
SliverPadding(
padding: const EdgeInsets.fromLTRB(24, 8, 24, 16),
sliver: SliverFillRemaining(
child: SingleChildScrollView(
physics: NeverScrollableScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
detailRestaurant.name,
style: Theme.of(context).textTheme.subtitle1,
textAlign: TextAlign.start,
),
SizedBox(height: 12.0),
Row(
children: [
Icon(
Icons.location_pin,
color: primaryColor,
size: 20,
),
SizedBox(
width: 2,
),
Text(detailRestaurant.city,
style: Theme.of(context).textTheme.bodyText1)
],
),
],
),
SizedBox(
child: BlocBuilder<RestaurantBloc, RestaurantState>(
buildWhen: (previousState, state) {
return state is CheckFavoriteLoadingState ||
state is FavoredState ||
state is UnfavorableState;
},
builder: (context, state) {
if (state is FavoredState) {
var _isFavorite = state.isFavorite;
return (_isFavorite)
? _buttonFavorite(detailRestaurant.id)
: _buttonNotFavorite(detailRestaurant);
} else if (state is UnfavorableState) {
var _isFavorite = state.isFavorite;
return (_isFavorite)
? _buttonFavorite(detailRestaurant.id)
: _buttonNotFavorite(detailRestaurant);
} else if (state is CheckFavoriteLoadingState) {
return Padding(
padding: EdgeInsets.only(top: 100),
child: Center(
child: CircularProgressIndicator(),
),
);
} else {
return Padding(
padding: EdgeInsets.only(top: 100),
child: Center(
child: CircularProgressIndicator(),
),
);
}
},
),
)
],
),
SizedBox(
height: 12,
),
Text(
'Overview',
style: Theme.of(context).textTheme.subtitle2,
textAlign: TextAlign.start,
),
SizedBox(
height: 4,
),
Text(
detailRestaurant.description,
style: Theme.of(context).textTheme.caption,
textAlign: TextAlign.justify,
),
SizedBox(
height: 8,
),
Text(
'Foods',
style: Theme.of(context).textTheme.subtitle2,
textAlign: TextAlign.start,
),
SizedBox(
height: 4,
),
ContainerFoods(
detailRestaurant: detailRestaurant,
),
SizedBox(
height: 8,
),
Text(
'Drinks',
style: Theme.of(context).textTheme.subtitle2,
textAlign: TextAlign.start,
),
SizedBox(
height: 4,
),
ContainerDrinks(
detailRestaurant: detailRestaurant,
),
SizedBox(
height: 8,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Customer Reviews',
style: Theme.of(context).textTheme.subtitle2,
textAlign: TextAlign.start,
),
CustomButton(
onPressed: () {
Navigator.of(context)
.pushNamed(AddReviewPage.routeName,
arguments: detailRestaurant.id)
.then((value) => _onPageClosed(value));
},
textButton: 'Add Review',
btnColor: primaryColor,
textColor: Colors.white,
)
],
),
SizedBox(
height: 8,
),
ContainerCustomerReviews(
detailRestaurant: detailRestaurant,
),
],
),
),
),
),
],
);
}
_buttonNotFavorite(DetailRestaurant detailRestaurant) {
return Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(16),
onTap: () {
context.read<RestaurantBloc>().add(AddToFavoriteEvent(
restaurant: mapDetailToRestaurantItem(detailRestaurant)));
},
child: Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.pinkAccent,
borderRadius: BorderRadius.circular(16),
),
child: Icon(
Icons.favorite_border,
size: 28,
color: Colors.white,
),
),
),
);
}
Widget _buttonFavorite(String id) {
return Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(16),
onTap: () {
context.read<RestaurantBloc>().add(DeleteFavoriteEvent(id: id));
},
child: Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.pinkAccent,
borderRadius: BorderRadius.circular(16),
),
child: Icon(
Icons.favorite,
size: 28,
color: Colors.white,
),
),
),
);
}
_fetchRestaurantDetail() {
context
.read<RestaurantBloc>()
.add(FetchedRestaurantDetailEvent(id: widget.id));
}
_checkFavoriteById() {
BlocProvider.of<RestaurantBloc>(context)
.add(CheckFavoriteEvent(id: widget.id));
}
_fetchFavorites() {
context.read<RestaurantBloc>().add(FetchedFavoritesEvent());
}
_onPageClosed(void value) {
_fetchRestaurantDetail();
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui/detail | mirrored_repositories/Restaurant-Flutter/lib/ui/detail/components/container_drinks.dart | import 'package:flutter/material.dart';
import 'package:restaurant_app/bloc/restaurant/model/detail_restaurant.dart';
import 'package:restaurant_app/ui/shared/custom_menus_card.dart';
import 'package:restaurant_app/utils/assets.dart';
class ContainerDrinks extends StatelessWidget {
final DetailRestaurant detailRestaurant;
const ContainerDrinks({Key? key, required this.detailRestaurant})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.width / 3.2,
child: ListView.builder(
shrinkWrap: true,
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
itemCount: detailRestaurant.menu.drinks.length,
itemBuilder: (context, index) {
return CustomMenusCard(
image: DRINKS_ICON,
name: detailRestaurant.menu.drinks[index].name);
}),
);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui/detail | mirrored_repositories/Restaurant-Flutter/lib/ui/detail/components/container_foods.dart | import 'package:flutter/material.dart';
import 'package:restaurant_app/bloc/restaurant/model/detail_restaurant.dart';
import 'package:restaurant_app/ui/shared/custom_menus_card.dart';
import 'package:restaurant_app/utils/assets.dart';
class ContainerFoods extends StatelessWidget {
final DetailRestaurant detailRestaurant;
const ContainerFoods({Key? key, required this.detailRestaurant})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.width / 3.2,
child: ListView.builder(
shrinkWrap: true,
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
itemCount: detailRestaurant.menu.foods.length,
itemBuilder: (context, index) {
return CustomMenusCard(
image: FOODS_ICON,
name: detailRestaurant.menu.foods[index].name);
}),
);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui/detail | mirrored_repositories/Restaurant-Flutter/lib/ui/detail/components/container_customer_reviews.dart | import 'package:flutter/material.dart';
import 'package:restaurant_app/bloc/restaurant/model/detail_restaurant.dart';
import 'package:restaurant_app/ui/shared/custom_reviews_card.dart';
class ContainerCustomerReviews extends StatelessWidget {
final DetailRestaurant detailRestaurant;
const ContainerCustomerReviews({Key? key, required this.detailRestaurant})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height / 6,
child: ListView.builder(
shrinkWrap: true,
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
itemCount: detailRestaurant.customerReviews.length,
itemBuilder: (context, index) {
return CustomReviewsCard(
customerReviews: detailRestaurant.customerReviews[index],
);
}),
);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/review/add_review_page.dart | import 'package:flutter/material.dart';
import 'package:restaurant_app/ui/review/add_review_body.dart';
import 'package:restaurant_app/utils/colors.dart';
class AddReviewPage extends StatelessWidget {
static const String routeName = '/add_review';
final String id;
const AddReviewPage({Key? key, required this.id}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: primaryColor,
title: Text('Add Review'),
),
body: AddReviewBody(id: id),
);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/review/add_review_body.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:restaurant_app/bloc/restaurant/restaurant.dart';
import 'package:restaurant_app/data/model/request/customer_review_request.dart';
import 'package:restaurant_app/ui/shared/custom_button.dart';
import 'package:restaurant_app/utils/colors.dart';
import 'package:restaurant_app/utils/dialog_utils.dart';
import 'package:restaurant_app/utils/validation_helper.dart';
class AddReviewBody extends StatefulWidget {
final String id;
const AddReviewBody({Key? key, required this.id}) : super(key: key);
@override
_AddReviewBodyState createState() => _AddReviewBodyState();
}
class _AddReviewBodyState extends State<AddReviewBody> {
TextEditingController _nameController = TextEditingController();
TextEditingController _reviewController = TextEditingController();
final _addReviewKey = new GlobalKey<FormState>();
@override
void dispose() {
super.dispose();
_nameController.dispose();
_reviewController.dispose();
}
@override
Widget build(BuildContext context) {
return BlocListener<RestaurantBloc, RestaurantState>(
listener: (context, state) {
if (state is AddCustomerReviewLoadingState) {
showLoading(context);
} else if (state is AddCustomerReviewSuccessState) {
_doubleBackPressed();
Fluttertoast.showToast(msg: 'Reviews successfully added');
} else if (state is AddCustomerReviewErrorState) {
hideLoading(context);
Fluttertoast.showToast(msg: 'something wrong');
}
},
child: _buildForm(),
);
}
_buildForm() {
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Form(
key: _addReviewKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 16,
),
Text(
'Name',
style: Theme.of(context).textTheme.subtitle2,
),
SizedBox(
height: 8,
),
TextFormField(
style: Theme.of(context).textTheme.caption,
controller: _nameController,
keyboardType: TextInputType.text,
validator: (value) {
return validationFieldMinMaxRequired(
value: value!, fieldName: "Name", maxValue: 265);
},
decoration: InputDecoration(hintText: "Name"),
),
SizedBox(
height: 16,
),
Text(
'Review',
style: Theme.of(context).textTheme.subtitle2,
),
SizedBox(
height: 8,
),
TextFormField(
style: Theme.of(context).textTheme.caption,
controller: _reviewController,
keyboardType: TextInputType.multiline,
minLines: 4,
maxLines: 100,
validator: (value) {
return validationFieldMinMaxRequired(
value: value!, fieldName: "Review", maxValue: 265);
},
decoration: InputDecoration(hintText: "Review"),
),
SizedBox(
height: 16,
),
SizedBox(
width: double.infinity,
height: 40,
child: CustomButton(
btnColor: primaryColor,
textColor: Colors.white,
textButton: 'Add Review',
onPressed: () {
if (_addReviewKey.currentState!.validate()) {
_addReviewKey.currentState!.save();
var _request = CustomerReviewRequest(
id: widget.id,
review: _reviewController.text,
name: _nameController.text);
context.read<RestaurantBloc>().add(
AddedCustomerReviewsEvent(
customerReviewRequest: _request));
}
},
),
)
],
),
),
),
);
}
void _doubleBackPressed() {
Navigator.of(context).pop();
Navigator.of(context).pop();
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/favorite/favorites_page.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:restaurant_app/bloc/restaurant/model/restaurant.dart';
import 'package:restaurant_app/bloc/restaurant/restaurant.dart';
import 'package:restaurant_app/ui/shared/container_restaurants.dart';
class FavoritesPage extends StatelessWidget {
const FavoritesPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
_fetchFavorites(context);
return BlocBuilder<RestaurantBloc, RestaurantState>(
buildWhen: (previousState, state) {
return state is FetchFavoritesSuccessState ||
state is FetchFavoritesLoadingState ||
state is FetchFavoritesEmptyState ||
state is FetchFavoritesErrorState;
},
builder: (context, state) {
if (state is FetchFavoritesSuccessState) {
List<Restaurant> restaurants = state.restaurants;
return _buildHomePage(restaurants: restaurants);
} else if (state is FetchFavoritesLoadingState) {
return Padding(
padding: EdgeInsets.only(top: 100),
child: Center(
child: CircularProgressIndicator(),
),
);
} else if (state is FetchFavoritesEmptyState) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.error,
color: Colors.red[700],
size: 40,
),
SizedBox(
height: 8,
),
Text(state.emptyMessage)
],
),
);
} else if (state is FetchFavoritesErrorState) {
return Center(
child: Center(
child: Text(state.message),
),
);
} else {
return Padding(
padding: EdgeInsets.only(top: 100),
child: Center(
child: Text('ELSE'),
),
);
}
},
);
}
Widget _buildHomePage({required List<Restaurant> restaurants}) {
return ListView.builder(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: restaurants.length,
itemBuilder: (context, index) {
return ContainerRestaurants(
data: restaurants[index],
);
},
);
}
_fetchFavorites(BuildContext context) {
context.read<RestaurantBloc>().add(FetchedFavoritesEvent());
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/splash/splash_screen.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:restaurant_app/ui/main/main_page.dart';
class SplashScreen extends StatefulWidget {
const SplashScreen({Key? key}) : super(key: key);
static const String routeName = '/splash';
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen>
with TickerProviderStateMixin {
late Timer _timer;
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
initAnimation();
moveToMainPage();
}
@override
void dispose() {
_timer.cancel();
_controller.dispose();
super.dispose();
}
initAnimation() {
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
)..repeat(reverse: true);
_animation = CurvedAnimation(parent: _controller, curve: Curves.easeIn);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FadeTransition(
opacity: _animation,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 80,
height: 80,
child: Image.asset('assets/images/dicoding_logo.jpeg')),
SizedBox(
height: 16,
),
Text(
'Restaurant App',
style: Theme.of(context).textTheme.subtitle1,
)
],
),
),
],
),
),
),
);
}
Timer moveToMainPage() {
return _timer = Timer(Duration(seconds: 3), () async {
Navigator.of(context).pushReplacementNamed(MainApp.routeName);
});
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/settings/settings_page.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:restaurant_app/bloc/scheduler/scheduler.dart';
class SettingsPage extends StatelessWidget {
Widget _buildList(BuildContext context, bool switchState) {
return ListView(
children: [
Material(
child: ListTile(
title: Text('Daily Reminder'),
trailing: Switch.adaptive(
value: switchState,
onChanged: (value) async {
if (Platform.isIOS) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Coming Soon!'),
content: Text('This feature will be coming soon!'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Ok'),
),
],
);
},
);
} else {
_schedulerNotification(context, value);
}
},
)),
),
],
);
}
@override
Widget build(BuildContext context) {
_preferenceDailyReminderEvent(context);
return BlocListener<SchedulerBloc, SchedulerState>(
listener: (context, state) {
if (state is SchedulerRestaurantEnableState) {
_preferenceDailyReminderEvent(context);
Fluttertoast.showToast(msg: "Daily Reminder is Enable");
} else if (state is SchedulerRestaurantDisableState) {
_preferenceDailyReminderEvent(context);
Fluttertoast.showToast(msg: "Daily reminder is Disable");
}
},
child: BlocBuilder<SchedulerBloc, SchedulerState>(
buildWhen: (previousState, state) {
return state is SchedulerPreferencesEnabledState ||
state is SchedulerPreferencesDisabledState;
}, builder: (context, state) {
if (state is SchedulerPreferencesEnabledState) {
bool switchState = state.status;
return _buildList(context, switchState);
} else if (state is SchedulerPreferencesDisabledState) {
bool switchState = state.status;
return _buildList(context, switchState);
}
return Padding(
padding: EdgeInsets.only(top: 100),
child: Center(
child: CircularProgressIndicator(),
),
);
}),
);
}
_schedulerNotification(BuildContext context, bool value) {
context.read<SchedulerBloc>().add(ScheduledRestaurantsEvent(value: value));
}
_preferenceDailyReminderEvent(BuildContext context) {
context.read<SchedulerBloc>().add(PreferenceDailyReminderEvent());
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/search/search_body.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:restaurant_app/bloc/restaurant/model/restaurant.dart';
import 'package:restaurant_app/bloc/restaurant/restaurant.dart';
import 'package:restaurant_app/ui/shared/container_restaurants.dart';
import 'package:restaurant_app/utils/colors.dart';
class SearchBody extends StatefulWidget {
const SearchBody({Key? key}) : super(key: key);
@override
_SearchBodyState createState() => _SearchBodyState();
}
class _SearchBodyState extends State<SearchBody> {
TextEditingController _searchController = new TextEditingController();
@override
void initState() {
super.initState();
_fetchRestaurant(context, _searchController.text);
}
@override
void dispose() {
super.dispose();
_searchController.dispose();
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: primaryColor,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(16),
bottomRight: Radius.circular(16))),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
style: TextStyle(fontSize: 14),
keyboardType: TextInputType.text,
controller: _searchController,
decoration: InputDecoration(
hintText: 'Search...',
suffixIcon: InkWell(
onTap: () {
_fetchRestaurant(context, _searchController.text);
},
child: Icon(
Icons.search,
size: 16,
color: primaryColor,
)),
),
),
],
),
),
_buildPage(),
],
),
);
}
_fetchRestaurant(BuildContext context, String query) {
context.read<RestaurantBloc>().add(SearchRestaurantEvent(
query: query,
));
}
Widget _buildPage() {
return BlocBuilder<RestaurantBloc, RestaurantState>(
buildWhen: (previousState, state) {
return state is SearchRestaurantErrorState ||
state is SearchRestaurantLoadingState ||
state is SearchRestaurantSuccessState ||
state is SearchRestaurantEmptyState;
},
builder: (context, state) {
if (state is SearchRestaurantSuccessState) {
List<Restaurant> restaurants = state.restaurants;
return _buildList(restaurants: restaurants);
} else if (state is SearchRestaurantLoadingState) {
return Padding(
padding: EdgeInsets.only(top: 200),
child: Center(
child: CircularProgressIndicator(),
),
);
} else if (state is SearchRestaurantErrorState) {
return Center(
child: Center(
child: Text(state.message),
),
);
} else if (state is SearchRestaurantEmptyState) {
return Padding(
padding: EdgeInsets.only(top: 200),
child: Center(
child: Column(
children: [
Icon(
Icons.error,
color: Colors.red,
size: 40,
),
SizedBox(
height: 8,
),
Text(state.message),
],
),
),
);
} else {
return Padding(
padding: EdgeInsets.only(top: 100),
child: Center(
child: CircularProgressIndicator(),
),
);
}
},
);
}
_buildList({required List<Restaurant> restaurants}) {
return SizedBox(
height: MediaQuery.of(context).size.height - 164,
child: ListView.builder(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: restaurants.length,
itemBuilder: (context, index) {
return ContainerRestaurants(
data: restaurants[index],
);
},
),
);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/search/search_page.dart | import 'package:flutter/material.dart';
import 'package:restaurant_app/ui/search/search_body.dart';
import 'package:restaurant_app/utils/colors.dart';
class SearchPage extends StatelessWidget {
static const String routeName = '/search';
const SearchPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
titleSpacing: 16,
title: Text('Search', style: Theme.of(context).textTheme.headline6),
brightness: Brightness.dark,
backgroundColor: primaryColor,
),
body: SearchBody(),
);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter | mirrored_repositories/Restaurant-Flutter/test/restaurant_client_test.dart | import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mock_web_server/mock_web_server.dart';
import 'package:restaurant_app/data/model/response/restaurant_item.dart';
import 'package:restaurant_app/data/model/response/restaurant_response.dart';
import 'package:restaurant_app/data/remote/restaurant_api_client.dart';
late MockWebServer _server;
late RestaurantApiClient _client;
final _headers = {"Content-Type": "application/json"};
final dispatcherMap = <String, MockResponse>{};
void main() {
setUp(() async {
_server = MockWebServer();
await _server.start();
final dio = Dio();
dio.interceptors.add(LogInterceptor(responseBody: true));
_client = RestaurantApiClient(dio, baseUrl: _server.url);
});
tearDown(() {
_server.shutdown();
});
test("test empty restaurant list", () async {
_server.enqueue(body: mockEmptyResponseJson, headers: _headers);
final tasks = await _client.getRestaurantData();
expect(tasks.restaurants, isNotNull);
expect(tasks.restaurants.length, 0);
});
test("test restaurant list", () async {
_server.enqueue(body: mockRestaurantResponseJson, headers: _headers);
final tasks = await _client.getRestaurantData();
expect(tasks.restaurants, isNotNull);
expect(tasks.restaurants.length, 1);
});
}
final List<RestaurantItem> mockEmptyList = [];
final RestaurantResponse mockEmptyResponse = RestaurantResponse(
error: false,
count: 0,
message: 'success',
restaurants: mockEmptyList,
);
final mockEmptyResponseJson = jsonEncode(mockEmptyResponse);
final mockRestaurantItem = RestaurantItem(
id: 's1knt6za9kkfw1e867',
name: 'Kafe Kita',
description:
'Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi',
pictureId: '25',
city: 'Gorontalo',
rating: 4,
);
final List<RestaurantItem> mockRestaurants = []..add(mockRestaurantItem);
final RestaurantResponse mockRestaurantResponse = RestaurantResponse(
error: false,
count: 1,
message: 'success',
restaurants: mockRestaurants,
);
final mockRestaurantResponseJson = jsonEncode(mockRestaurantResponse);
| 0 |
mirrored_repositories/PraxisFlutter | mirrored_repositories/PraxisFlutter/lib/main_staging.dart | import 'package:praxis_flutter/application/platform_app.dart';
import 'package:praxis_flutter/bootstrap.dart';
const staging = "staging";
void main() async {
bootstrap(() => const PraxisApp(), staging);
}
| 0 |
mirrored_repositories/PraxisFlutter | mirrored_repositories/PraxisFlutter/lib/injection.config.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// InjectableConfigGenerator
// **************************************************************************
import 'package:get_it/get_it.dart' as _i1;
import 'package:injectable/injectable.dart' as _i2;
import 'infrastructure/notifications/firebase_messaging.dart' as _i3;
import 'ui/model/jokes/ui_jokes_mapper.dart'
as _i4; // ignore_for_file: unnecessary_lambdas
// ignore_for_file: lines_longer_than_80_chars
/// an extension to register the provided dependencies inside of [GetIt]
extension GetItInjectableX on _i1.GetIt {
/// initializes the registration of provided dependencies inside of [GetIt]
_i1.GetIt $initGetIt(
{String? environment, _i2.EnvironmentFilter? environmentFilter}) {
final gh = _i2.GetItHelper(this, environment, environmentFilter);
gh.factory<_i3.PraxisFirebaseMessaging>(
() => _i3.PraxisFirebaseMessaging());
gh.factory<_i4.UIJokeMapper>(() => _i4.UIJokeMapper());
return this;
}
}
| 0 |
mirrored_repositories/PraxisFlutter | mirrored_repositories/PraxisFlutter/lib/main_testing.dart | import 'package:injectable/injectable.dart';
import 'package:praxis_flutter/application/platform_app.dart';
import 'package:praxis_flutter/bootstrap.dart';
void main() async {
bootstrap(() => const PraxisApp(), Environment.test);
}
| 0 |
mirrored_repositories/PraxisFlutter | mirrored_repositories/PraxisFlutter/lib/injection.dart | import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
import 'package:praxis_data/injection.dart';
import 'package:praxis_flutter/injection.config.dart';
@InjectableInit(
initializerName: r'$initGetIt', // default
preferRelativeImports: true, // default
asExtension: true, // default
)
void configureAppInjection(String env) {
configureDataInjection(env);
GetIt.instance.$initGetIt(environment: env);
} | 0 |
mirrored_repositories/PraxisFlutter | mirrored_repositories/PraxisFlutter/lib/main_production.dart | import 'package:injectable/injectable.dart';
import 'package:praxis_flutter/application/platform_app.dart';
import 'package:praxis_flutter/bootstrap.dart';
void main() async {
bootstrap(() => const PraxisApp(),Environment.prod);
} | 0 |
mirrored_repositories/PraxisFlutter | mirrored_repositories/PraxisFlutter/lib/firebase_options.dart | // File generated by FlutterFire CLI.
// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
show defaultTargetPlatform, kIsWeb, TargetPlatform;
/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
/// options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
if (kIsWeb) {
return web;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return android;
case TargetPlatform.iOS:
return ios;
case TargetPlatform.macOS:
return macos;
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}
static const FirebaseOptions web = FirebaseOptions(
apiKey: 'AIzaSyCesmG-VOABs1sNKbzSYBarGzrBA64gc60',
appId: '1:1080315079875:web:c1d58cb4d08c950e2c8676',
messagingSenderId: '1080315079875',
projectId: 'flutterpraxis',
authDomain: 'flutterpraxis.firebaseapp.com',
storageBucket: 'flutterpraxis.appspot.com',
measurementId: 'G-YD3PRBQRYJ',
);
static const FirebaseOptions android = FirebaseOptions(
apiKey: 'AIzaSyAPsKE8FTqFfLyHxSF5UR_xfYF0TzwbobE',
appId: '1:1080315079875:android:50def698dd6274af2c8676',
messagingSenderId: '1080315079875',
projectId: 'flutterpraxis',
storageBucket: 'flutterpraxis.appspot.com',
);
static const FirebaseOptions ios = FirebaseOptions(
apiKey: 'AIzaSyD648P_AQMaTgT7Pbry-s_jAskmBpABBc0',
appId: '1:1080315079875:ios:3398c66d2dc3c3722c8676',
messagingSenderId: '1080315079875',
projectId: 'flutterpraxis',
storageBucket: 'flutterpraxis.appspot.com',
iosClientId: '1080315079875-p3tudhenbh67jshudgrc5pqu63sovep8.apps.googleusercontent.com',
iosBundleId: 'com.mutualmobile.praxisFlutter',
);
static const FirebaseOptions macos = FirebaseOptions(
apiKey: 'AIzaSyD648P_AQMaTgT7Pbry-s_jAskmBpABBc0',
appId: '1:1080315079875:ios:3398c66d2dc3c3722c8676',
messagingSenderId: '1080315079875',
projectId: 'flutterpraxis',
storageBucket: 'flutterpraxis.appspot.com',
iosClientId: '1080315079875-p3tudhenbh67jshudgrc5pqu63sovep8.apps.googleusercontent.com',
iosBundleId: 'com.mutualmobile.praxisFlutter',
);
}
| 0 |
mirrored_repositories/PraxisFlutter | mirrored_repositories/PraxisFlutter/lib/bootstrap.dart | import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'package:bloc/bloc.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/widgets.dart';
import 'package:get_it/get_it.dart';
import 'package:logging/logging.dart';
import 'package:flutter_web_plugins/url_strategy.dart';
import 'package:praxis_flutter/bloc/app_bloc_observer.dart';
import 'package:praxis_flutter/firebase_options.dart';
import 'package:praxis_flutter/infrastructure/notifications/firebase_messaging.dart';
import 'package:praxis_flutter/injection.dart';
Future<void> bootstrap(FutureOr<Widget> Function() builder, String env) async {
flutterLogError();
WidgetsFlutterBinding.ensureInitialized();
usePathUrlStrategy();
HttpOverrides.global = MyHttpOverrides();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
configureAppInjection(env);
await runZonedGuarded(
() async {
Bloc.observer = AppBlocObserver();
runApp(await builder());
},
(error, stackTrace) => log(error.toString(), stackTrace: stackTrace),
);
GetIt.instance.get<PraxisFirebaseMessaging>().setupMessaging();
}
void flutterLogError() {
FlutterError.onError = (details) {
log(details.exceptionAsString(), stackTrace: details.stack);
};
Logger.root.level = Level.INFO; // defaults to Level.INFO
Logger.root.onRecord.listen((record) {
print('${record.level.name}: ${record.time}: ${record.message}');
});
}
class MyHttpOverrides extends HttpOverrides{
@override
HttpClient createHttpClient(SecurityContext? context){
return super.createHttpClient(context)
..badCertificateCallback = (X509Certificate cert, String host, int port)=> true;
}
} | 0 |
mirrored_repositories/PraxisFlutter | mirrored_repositories/PraxisFlutter/lib/main_development.dart | import 'package:injectable/injectable.dart';
import 'package:praxis_flutter/application/platform_app.dart';
import 'package:praxis_flutter/bootstrap.dart';
void main() async {
bootstrap(() => const PraxisApp(),Environment.dev);
}
| 0 |
mirrored_repositories/PraxisFlutter/lib | mirrored_repositories/PraxisFlutter/lib/gen/assets.gen.dart | /// GENERATED CODE - DO NOT MODIFY BY HAND
/// *****************************************************
/// FlutterGen
/// *****************************************************
// ignore_for_file: directives_ordering,unnecessary_import
import 'package:flutter/widgets.dart';
class Assets {
Assets._();
}
class AssetGenImage extends AssetImage {
const AssetGenImage(String assetName) : super(assetName);
Image image({
Key? key,
ImageFrameBuilder? frameBuilder,
ImageLoadingBuilder? loadingBuilder,
ImageErrorWidgetBuilder? errorBuilder,
String? semanticLabel,
bool excludeFromSemantics = false,
double? width,
double? height,
Color? color,
BlendMode? colorBlendMode,
BoxFit? fit,
AlignmentGeometry alignment = Alignment.center,
ImageRepeat repeat = ImageRepeat.noRepeat,
Rect? centerSlice,
bool matchTextDirection = false,
bool gaplessPlayback = false,
bool isAntiAlias = false,
FilterQuality filterQuality = FilterQuality.low,
}) {
return Image(
key: key,
image: this,
frameBuilder: frameBuilder,
loadingBuilder: loadingBuilder,
errorBuilder: errorBuilder,
semanticLabel: semanticLabel,
excludeFromSemantics: excludeFromSemantics,
width: width,
height: height,
color: color,
colorBlendMode: colorBlendMode,
fit: fit,
alignment: alignment,
repeat: repeat,
centerSlice: centerSlice,
matchTextDirection: matchTextDirection,
gaplessPlayback: gaplessPlayback,
isAntiAlias: isAntiAlias,
filterQuality: filterQuality,
);
}
String get path => assetName;
}
| 0 |
mirrored_repositories/PraxisFlutter/lib | mirrored_repositories/PraxisFlutter/lib/application/platform_app.dart | import 'package:flex_color_scheme/flex_color_scheme.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:praxis_flutter/l10n/l10n.dart';
import 'package:praxis_flutter/presentation/core/widgets/abstract_plaform_widget.dart';
import 'package:praxis_flutter/routing/routes.dart';
class PraxisApp extends AbstractPlatformWidget<CupertinoApp, MaterialApp> {
/// Platform dependent app widget (CupertinoApp for iOS, MaterialApp for android)
final String title;
const PraxisApp({Key? key, this.title = 'Praxis'}) : super(key: key);
@override
CupertinoApp buildCupertino(BuildContext context) {
return CupertinoApp.router(
routeInformationProvider: praxisRoutes.routeInformationProvider,
debugShowCheckedModeBanner: false,
title: title,
theme: const CupertinoThemeData(),
routeInformationParser: praxisRoutes.routeInformationParser,
routerDelegate: praxisRoutes.routerDelegate,
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
);
}
@override
MaterialApp buildMaterial(BuildContext context) {
var lightTheme = FlexColorScheme.light(scheme: FlexScheme.blueWhale).toTheme;
var darkTheme = FlexColorScheme.dark(scheme: FlexScheme.blueWhale).toTheme;
return MaterialApp.router(
routeInformationProvider: praxisRoutes.routeInformationProvider,
debugShowCheckedModeBanner: false,
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
title: title,
theme: lightTheme,
darkTheme: darkTheme,
themeMode: ThemeMode.system,
routeInformationParser: praxisRoutes.routeInformationParser,
routerDelegate: praxisRoutes.routerDelegate,
);
}
}
| 0 |
mirrored_repositories/PraxisFlutter/lib/features | mirrored_repositories/PraxisFlutter/lib/features/login/login_cubit.dart | import 'package:bloc/bloc.dart';
import 'package:flutter/widgets.dart';
import 'package:get_it/get_it.dart';
import 'package:praxis_flutter/models/ui_state.dart';
import 'package:praxis_flutter_domain/entities/login_request.dart';
import 'package:praxis_flutter_domain/entities/login_result.dart';
import 'package:praxis_flutter_domain/use_cases/login_use_case.dart';
class LoginCubit extends Cubit<UiState<LoginResult>> {
final loginController = TextEditingController(text: 'random@gmail.com');
final passwordController = TextEditingController(text: 'random');
final LoginUseCase loginUseCase = GetIt.instance.get<LoginUseCase>();
LoginCubit() : super(Initial());
void login() {
emit(Loading());
loginUseCase.perform(
handleResponse,
error,
() {},
LoginRequest(
loginController.value.text, passwordController.value.text));
}
void handleResponse(LoginResult? response) {
if (response == null) {
emit(Failure(exception: Exception("Unexpected error occurred!")));
} else {
emit(Success(data: response));
}
}
error(e) {
emit(Failure(exception: e));
}
@override
Future<void> close() {
loginUseCase.dispose();
return super.close();
}
}
| 0 |
mirrored_repositories/PraxisFlutter/lib/features | mirrored_repositories/PraxisFlutter/lib/features/login/login_page.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:praxis_flutter/features/login/login_cubit.dart';
import 'package:praxis_flutter/l10n/l10n.dart';
import 'package:praxis_flutter/models/ui_state.dart';
import 'package:praxis_flutter/presentation/core/extensions/widget_extensions.dart';
import 'package:praxis_flutter/presentation/core/widgets/platform_button.dart';
import 'package:praxis_flutter/presentation/core/widgets/platform_dialog.dart';
import 'package:praxis_flutter/presentation/core/widgets/platform_progress_bar.dart';
import 'package:praxis_flutter/presentation/core/widgets/platform_scaffold.dart';
import 'package:praxis_flutter/presentation/core/widgets/platform_text_field.dart';
import 'package:praxis_flutter/routing/routes.dart';
import 'package:praxis_flutter_domain/entities/login_result.dart';
import 'package:praxis_flutter_domain/validations.dart';
class LoginPage extends StatelessWidget {
const LoginPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => LoginCubit(),
child: BlocListener<LoginCubit, UiState<LoginResult>>(
child: PraxisScaffold(
body: SafeArea(child: buildColumn(context)),
iosNavBar: CupertinoNavigationBar(
middle: title(),
),
androidAppBar: AppBar(
title: title(),
),
),
listener: (BuildContext context, state) {
if (state is Failure) {
print("Reaching in failure with value: ${(state as Failure).exception}");
if ((state as Failure).exception is EmailValidationException) {
showAlertDialog(
context: context,
title: context.l10n.emailErrorTitle,
content: context.l10n.emailErrorMessage,
defaultActionText: "OK");
}
if ((state as Failure).exception is PasswordTooShortException) {
showAlertDialog(
context: context,
title: context.l10n.passwordErrorTitle,
content: context.l10n.passwordErrorMessage,
defaultActionText: "OK");
}
} else if (state is Success) {
context.go(homeRoute);
}
},
),
);
}
Text title() => const Text("Login");
Widget buildColumn(BuildContext context) {
return BlocBuilder<LoginCubit, UiState<LoginResult>>(
builder: (context, selected) {
return Column(
children: [
const FlutterLogo(
size: 120,
).paddingAll(24),
PraxisTextField(
hintText: "Username",
controller: context.read<LoginCubit>().loginController,
).paddingAll(8),
PraxisTextField(
hintText: "Password",
obscureText: true,
controller: context.read<LoginCubit>().passwordController,
).paddingAll(8),
loginButton(context).paddingAll(8)
],
);
});
}
Widget loginButton(BuildContext context) {
return BlocBuilder<LoginCubit, UiState<LoginResult>>(
builder: (context, selected) {
if (selected is Loading) {
return const PraxisProgressBar();
}
return PraxisButton(
title: "Login",
onPressed: () {
context.read<LoginCubit>().login();
});
});
}
}
| 0 |
mirrored_repositories/PraxisFlutter/lib/features | mirrored_repositories/PraxisFlutter/lib/features/home/home_page.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:praxis_flutter/presentation/core/widgets/platform_button.dart';
import 'package:praxis_flutter/presentation/core/widgets/platform_dialog.dart';
import 'package:praxis_flutter/presentation/core/widgets/platform_scaffold.dart';
import 'package:praxis_flutter/presentation/core/extensions/widget_extensions.dart';
import 'package:praxis_flutter/routing/routes.dart';
import 'package:go_router/go_router.dart';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return PraxisScaffold(
androidAppBar: AppBar(
title: appBarTitle(),
),
iosNavBar: CupertinoNavigationBar(
middle: appBarTitle(),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
heading().paddingAll(4),
showRandomJokes(context).paddingAll(4),
aboutWidget(context).paddingAll(4)
],
));
}
Widget aboutWidget(context) {
return PraxisButton(
title: "About",
onPressed: () {
showAlertDialog(
context: context,
title: "About Praxis",
content:
"PraxisFlutter is a sample flutter app which can be used as a base project for other projects written in flutter. "
"The app uses clean architecture to provide a robust base to the app.\n\n"
"The http library is used to fetch jokes along with the async/await which handles connections asynchronously and makes the app more reliable.",
defaultActionText: "OK");
});
}
Widget heading() {
return const Text(
"Chuck Norris Random Joke Generator",
);
}
Text appBarTitle() => const Text("Praxis");
Widget showRandomJokes(BuildContext context) {
return PraxisButton(
title: "Show random Jokes",
onPressed: () {
context.push(jokeListRoute);
});
}
}
| 0 |
mirrored_repositories/PraxisFlutter/lib/features | mirrored_repositories/PraxisFlutter/lib/features/splash/splash_cubit.dart | import 'package:bloc/bloc.dart';
class SplashCubit extends Cubit<bool> {
SplashCubit() : super(false);
void toggle() => emit(!state);
}
| 0 |
mirrored_repositories/PraxisFlutter/lib/features | mirrored_repositories/PraxisFlutter/lib/features/splash/splash_page.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:praxis_flutter/features/splash/splash_cubit.dart';
import 'package:praxis_flutter/presentation/core/widgets/platform_button.dart';
import 'package:praxis_flutter/presentation/core/widgets/platform_scaffold.dart';
import 'package:praxis_flutter/routing/routes.dart';
class SplashPage extends StatelessWidget {
const SplashPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => SplashCubit(),
child: const SplashView(),
);
}
}
class SplashView extends StatelessWidget {
const SplashView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return PraxisScaffold(
androidAppBar: AppBar(
title: praxisPlayground(),
),
iosNavBar: CupertinoNavigationBar(
middle: praxisPlayground(),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
flutterLogo(),
verticalSpace(),
pressMeButton(),
verticalSpace(),
loginButton(context)
],
),
));
}
FlutterLogo flutterLogo() {
return const FlutterLogo(
size: 160,
);
}
SizedBox verticalSpace() {
return const SizedBox(
height: 24,
);
}
pressMeButton() {
return BlocBuilder<SplashCubit, bool>(builder: (context, selected) {
return PraxisButton(
title: !selected ? "Press Me!" : "You Pressed me! woo hoo!",
onPressed: () {
context.read<SplashCubit>().toggle();
},
);
});
}
PraxisButton loginButton(BuildContext context) {
return PraxisButton(
title: "Login ?",
onPressed: () {
context.go(loginRoute);
},
);
}
Text praxisPlayground() => const Text("Welcome to Praxis Playground");
}
| 0 |
mirrored_repositories/PraxisFlutter/lib/features | mirrored_repositories/PraxisFlutter/lib/features/joke_list/jokes_cubit.dart | import 'package:bloc/bloc.dart';
import 'package:get_it/get_it.dart';
import 'package:praxis_flutter/models/ui_state.dart';
import 'package:praxis_flutter/ui/model/jokes/ui_joke.dart';
import 'package:praxis_flutter/ui/model/jokes/ui_jokes_mapper.dart';
import 'package:praxis_flutter_domain/entities/api_response.dart'
as api_response;
import 'package:praxis_flutter_domain/use_cases/get_five_random_jokes_usecase.dart';
class JokesCubit extends Cubit<UiState<UIJokeList>> {
final getFiveRandomJokesUseCase = GetIt.I.get<GetFiveRandomJokesUseCase>();
final jokeMapper = GetIt.I.get<UIJokeMapper>();
JokesCubit() : super(Initial()) {
loadJokes();
}
void loadJokes() {
emit(Loading());
getFiveRandomJokesUseCase.perform(handleResponse, error, complete);
}
void handleResponse(GetJokeListUseCaseResponse? response) {
final useCaseResponseJokes = response?.jokeList;
if (useCaseResponseJokes == null) {
emit(Failure(exception: Exception("Couldn't fetch jokes!")));
} else {
if (useCaseResponseJokes is api_response.Failure) {
emit(Failure(
exception: (useCaseResponseJokes as api_response.Failure).error));
} else if (useCaseResponseJokes is api_response.Success) {
var jokes = (useCaseResponseJokes as api_response.Success);
final uiJokes = jokeMapper.mapToPresentation(jokes.data);
emit(Success(data: uiJokes));
}
}
}
void complete() {}
error(e) {
emit(Failure(exception: e));
}
@override
Future<void> close() {
getFiveRandomJokesUseCase.dispose();
return super.close();
}
}
| 0 |
mirrored_repositories/PraxisFlutter/lib/features | mirrored_repositories/PraxisFlutter/lib/features/joke_list/joke_list_page.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:praxis_flutter/features/joke_list/jokes_cubit.dart';
import 'package:praxis_flutter/models/ui_state.dart';
import 'package:praxis_flutter/presentation/core/extensions/widget_extensions.dart';
import 'package:praxis_flutter/presentation/core/widgets/platform_button.dart';
import 'package:praxis_flutter/presentation/core/widgets/platform_progress_bar.dart';
import 'package:praxis_flutter/presentation/core/widgets/platform_scaffold.dart';
import 'package:praxis_flutter/ui/model/jokes/ui_joke.dart';
class JokesPage extends StatelessWidget {
const JokesPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => JokesCubit(),
child: BlocListener<JokesCubit, UiState<UIJokeList>>(
child: const JokeListPage(),
listener: (context, state) {},
),
);
}
}
class JokeListPage extends StatelessWidget {
const JokeListPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return PraxisScaffold(
androidAppBar: AppBar(
title: text(),
),
iosNavBar: CupertinoNavigationBar(
middle: text(),
),
body: BlocBuilder<JokesCubit, UiState<UIJokeList>>(
builder: (context, state) {
return Stack(
alignment: Alignment.center,
children: [
state is Loading
? const Align(
child: PraxisProgressBar(),
alignment: Alignment.center,
)
: state is Success
? buildJokesList(state as Success)
: state is Failure
? retryButton(state as Failure, context)
: Container()
],
);
}));
}
ListView buildJokesList(Success state) {
return ListView.builder(
itemCount: state.data.jokes.length,
itemBuilder: (context, index) {
return Text(state.data.jokes[index].value).paddingAll(8);
});
}
Text text() => const Text("Praxis");
retryButton(Failure state, BuildContext context) {
return SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
PraxisButton(
title: "Retry ?",
onPressed: () {
context.read<JokesCubit>().loadJokes();
}),
Text(state.exception.toString()).paddingAll(8),
],
),
);
}
}
| 0 |
mirrored_repositories/PraxisFlutter/lib | mirrored_repositories/PraxisFlutter/lib/models/ui_state.dart | abstract class UiState<T> {}
class Initial<T> extends UiState<T> {}
class Loading<T> extends UiState<T> {}
class Success<T> extends UiState<T> {
T data;
Success({required this.data});
}
class Failure<T> extends UiState<T> {
Exception exception;
Failure({required this.exception});
} | 0 |
mirrored_repositories/PraxisFlutter/lib/infrastructure | mirrored_repositories/PraxisFlutter/lib/infrastructure/notifications/firebase_messaging.dart | import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:injectable/injectable.dart';
import 'package:logging/logging.dart';
import 'package:praxis_flutter/firebase_options.dart';
final Logger messagingLogger = Logger('PraxisFirebaseMessaging');
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
messagingLogger.fine("Handling a background message: ${message.messageId}");
}
@injectable
class PraxisFirebaseMessaging {
FirebaseMessaging messaging = FirebaseMessaging.instance;
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
AndroidNotificationChannel channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
importance: Importance.max,
);
void setupMessaging() async {
setupLocalNotifications();
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
await iosNotificationPermissions();
listenForMessages();
}
Future<void> iosNotificationPermissions() async {
NotificationSettings settings = await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
whenMessagingAuthorized();
} else if (settings.authorizationStatus ==
AuthorizationStatus.provisional) {
messagingLogger.fine('User granted provisional permission');
whenMessagingAuthorized(); // TODO how do we handle this ?
} else {
messagingLogger.fine('User declined or has not accepted permission');
}
}
void whenMessagingAuthorized() async {
messaging.getToken(vapidKey: "BJPCVj0UQyIqSPWi25_vBmefW6VFJjXUQR45ZI8xylcfmrsCgWPW5go9JnWT6bmh-nqhOiWna6tC6Fg3SS0zif0").then((value) {
messagingLogger.fine(value);
});
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, // Required to display a heads up notification
badge: true,
sound: true,
);
}
void listenForMessages() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
messagingLogger.fine('Got a message whilst in the foreground!');
messagingLogger.fine('Message data: ${message.data}');
if (message.notification != null) {
messagingLogger.fine(
'Message also contained a notification: ${message.notification}');
}
showLocalNotification(message);
});
}
void setupLocalNotifications() async {
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
}
void showLocalNotification(RemoteMessage message) {
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
AppleNotification? apple = message.notification?.apple;
if (notification != null) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
iOS: iosNotificationDetails(apple),
android: androidNotificationDetails(android),
));
}
}
DarwinNotificationDetails iosNotificationDetails(AppleNotification? apple) {
return DarwinNotificationDetails(
sound: apple?.sound?.name, subtitle: apple?.subtitle);
}
AndroidNotificationDetails androidNotificationDetails(
AndroidNotification? android) {
return AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
icon: android?.smallIcon,
);
}
}
| 0 |
mirrored_repositories/PraxisFlutter/lib | mirrored_repositories/PraxisFlutter/lib/bloc/app_bloc_observer.dart | import 'dart:developer';
import 'package:flutter_bloc/flutter_bloc.dart';
class AppBlocObserver extends BlocObserver {
@override
void onChange(BlocBase bloc, Change change) {
super.onChange(bloc, change);
log('onChange(${bloc.runtimeType}, $change)');
}
@override
void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
log('onError(${bloc.runtimeType}, $error, $stackTrace)');
super.onError(bloc, error, stackTrace);
}
} | 0 |
mirrored_repositories/PraxisFlutter/lib/presentation/core | mirrored_repositories/PraxisFlutter/lib/presentation/core/widgets/platform_scaffold.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:praxis_flutter/presentation/core/widgets/abstract_plaform_widget.dart';
class PraxisScaffold
extends AbstractPlatformWidget<CupertinoPageScaffold, Scaffold> {
const PraxisScaffold(
{Key? key, required this.body, this.androidAppBar, this.iosNavBar})
: super(key: key);
final Widget body;
final PreferredSizeWidget? androidAppBar;
final ObstructingPreferredSizeWidget? iosNavBar;
@override
CupertinoPageScaffold buildCupertino(BuildContext context) {
return CupertinoPageScaffold(
backgroundColor: CupertinoTheme.of(context).scaffoldBackgroundColor,
navigationBar: iosNavBar,
child: SizedBox(
child: body,
width: MediaQuery.of(context).size.width,
),
);
}
@override
Scaffold buildMaterial(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
appBar: androidAppBar,
body: SizedBox(
child: body,
width: MediaQuery.of(context).size.width,
),
);
}
}
| 0 |
mirrored_repositories/PraxisFlutter/lib/presentation/core | mirrored_repositories/PraxisFlutter/lib/presentation/core/widgets/platform_button.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:praxis_flutter/presentation/core/widgets/abstract_plaform_widget.dart';
class PraxisButton
extends AbstractPlatformWidget<CupertinoButton, MaterialButton> {
final String title;
final Function() onPressed;
const PraxisButton({Key? key, required this.title, required this.onPressed}) : super(key: key);
@override
CupertinoButton buildCupertino(BuildContext context) {
return CupertinoButton(onPressed: onPressed, child: Text(title));
}
@override
MaterialButton buildMaterial(BuildContext context) {
return MaterialButton(
color: Theme.of(context).colorScheme.secondary,
onPressed: onPressed,
child: Text(title),
);
}
}
| 0 |
mirrored_repositories/PraxisFlutter/lib/presentation/core | mirrored_repositories/PraxisFlutter/lib/presentation/core/widgets/platform_progress_bar.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:praxis_flutter/presentation/core/widgets/abstract_plaform_widget.dart';
class PraxisProgressBar
extends AbstractPlatformWidget<
CupertinoActivityIndicator,
CircularProgressIndicator> {
const PraxisProgressBar({Key? key})
: super(key: key);
@override
CupertinoActivityIndicator buildCupertino(BuildContext context) {
return const CupertinoActivityIndicator();
}
@override
CircularProgressIndicator buildMaterial(BuildContext context) {
return const CircularProgressIndicator();
}
}
| 0 |
mirrored_repositories/PraxisFlutter/lib/presentation/core | mirrored_repositories/PraxisFlutter/lib/presentation/core/widgets/abstract_plaform_widget.dart | import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
class AbstractPlatformWidget<C extends Widget, M extends Widget>
extends StatelessWidget {
const AbstractPlatformWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
if (kIsWeb) {
return buildMaterial(context);
}
return Platform.isIOS || Platform.isMacOS
? buildCupertino(context)
: buildMaterial(context);
}
C buildCupertino(BuildContext context) => throw UnimplementedError();
M buildMaterial(BuildContext context) => throw UnimplementedError();
}
| 0 |
mirrored_repositories/PraxisFlutter/lib/presentation/core | mirrored_repositories/PraxisFlutter/lib/presentation/core/widgets/platform_dialog.dart | import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
Future<dynamic> showAlertDialog({
required BuildContext context,
required String title,
required String content,
String? cancelActionText,
required String defaultActionText,
}) async {
if (kIsWeb) {
return materialDialog(
context, title, content, cancelActionText, defaultActionText);
}
return Platform.isIOS || Platform.isMacOS
? cupertinoDialog(
context, title, content, cancelActionText, defaultActionText)
: materialDialog(
context, title, content, cancelActionText, defaultActionText);
}
Future<dynamic> cupertinoDialog(BuildContext context, String title,
String content, String? cancelActionText, String defaultActionText) {
return showCupertinoDialog(
context: context,
builder: (context) => CupertinoAlertDialog(
title: Text(title),
content: Text(content),
actions: <Widget>[
if (cancelActionText != null)
CupertinoDialogAction(
child: Text(cancelActionText),
onPressed: () => Navigator.of(context).pop(false),
),
CupertinoDialogAction(
child: Text(defaultActionText),
onPressed: () => Navigator.of(context).pop(true),
),
],
),
);
}
Future<dynamic> materialDialog(BuildContext context, String title,
String content, String? cancelActionText, String defaultActionText) {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(title),
content: Text(content),
actions: <Widget>[
if (cancelActionText != null)
TextButton(
child: Text(cancelActionText),
onPressed: () => Navigator.of(context).pop(false),
),
TextButton(
child: Text(defaultActionText),
onPressed: () => Navigator.of(context).pop(true),
),
],
),
);
}
| 0 |
mirrored_repositories/PraxisFlutter/lib/presentation/core | mirrored_repositories/PraxisFlutter/lib/presentation/core/widgets/platform_tab_scaffold.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:praxis_flutter/presentation/core/widgets/abstract_plaform_widget.dart';
class PraxisTabScaffold
extends AbstractPlatformWidget<CupertinoTabScaffold, Widget> {
const PraxisTabScaffold({
Key? key,
required this.tabsIcons,
required this.tabBuilder,
this.currentIndex = 0,
}) : super(key: key);
/// List of icons, showed at the bottom navigation bar.
final List<BottomNavigationBarItem> tabsIcons;
/// Use builder, extend of list of widget, bacuse its better
/// to have a correct context
final Widget Function(BuildContext, int) tabBuilder;
/// Defualt selected page
final int currentIndex;
@override
CupertinoTabScaffold buildCupertino(BuildContext context) {
return CupertinoTabScaffold(
tabBar: CupertinoTabBar(
backgroundColor:
CupertinoTheme.of(context).scaffoldBackgroundColor.withOpacity(.65),
currentIndex: currentIndex,
items: tabsIcons,
),
tabBuilder: tabBuilder,
);
}
@override
Widget buildMaterial(BuildContext context) {
return _MaterialTabScaffold(
tabsIcons: tabsIcons,
tabBuilder: tabBuilder,
currentIndex: currentIndex,
);
}
}
class _MaterialTabScaffold extends StatefulWidget {
const _MaterialTabScaffold({
Key? key,
required this.tabsIcons,
required this.tabBuilder,
this.currentIndex = 0,
}) : super(key: key);
final List<BottomNavigationBarItem> tabsIcons;
final Widget Function(BuildContext, int) tabBuilder;
final int currentIndex;
@override
_MaterialTabScaffoldState createState() => _MaterialTabScaffoldState();
}
class _MaterialTabScaffoldState extends State<_MaterialTabScaffold> {
late int _currentIndex = widget.currentIndex;
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
backgroundColor: CupertinoColors.darkBackgroundGray.withOpacity(0.65),
onTap: (index) => setState(() {
_currentIndex = index;
}),
currentIndex: _currentIndex,
items: widget.tabsIcons,
),
body: widget.tabBuilder(context, _currentIndex),
);
}
} | 0 |
mirrored_repositories/PraxisFlutter/lib/presentation/core | mirrored_repositories/PraxisFlutter/lib/presentation/core/widgets/platform_text_field.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:praxis_flutter/presentation/core/widgets/abstract_plaform_widget.dart';
class PraxisTextField
extends AbstractPlatformWidget<CupertinoTextField, TextField> {
const PraxisTextField({
Key? key,
this.controller,
this.focusNode,
this.maxLength,
this.inputFormatters,
this.keyboardType,
this.autocorrect = true,
this.toolbarOptions,
this.hintText,
this.obscureText = false
}) : super(key: key);
final TextEditingController? controller;
final FocusNode? focusNode;
final int? maxLength;
final List<TextInputFormatter>? inputFormatters;
final TextInputType? keyboardType;
final bool autocorrect;
final ToolbarOptions? toolbarOptions;
final String? hintText;
final bool obscureText;
@override
CupertinoTextField buildCupertino(BuildContext context) {
return CupertinoTextField(
controller: controller,
focusNode: focusNode,
maxLength: maxLength,
inputFormatters: inputFormatters,
keyboardType: keyboardType,
autocorrect: autocorrect,
toolbarOptions: toolbarOptions,
placeholder: hintText,
obscureText: obscureText,
);
}
@override
TextField buildMaterial(BuildContext context) {
return TextField(
controller: controller,
focusNode: focusNode,
maxLength: maxLength,
inputFormatters: inputFormatters,
keyboardType: keyboardType,
autocorrect: autocorrect,
toolbarOptions: toolbarOptions,
decoration: InputDecoration(
labelText: hintText,
),
obscureText: obscureText,
);
}
} | 0 |
mirrored_repositories/PraxisFlutter/lib/presentation/core | mirrored_repositories/PraxisFlutter/lib/presentation/core/extensions/context_extensions.dart | import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
extension ContextExt on BuildContext {
/// The same of [MediaQuery.of(context).size]
Size get mediaQuerySize => MediaQuery.of(this).size;
/// The same of [MediaQuery.of(context).size.height]
/// Note: updates when you rezise your screen (like on a browser or
/// desktop window)
double get height => mediaQuerySize.height;
/// The same of [MediaQuery.of(context).size.width]
/// Note: updates when you rezise your screen (like on a browser or
/// desktop window)
double get width => mediaQuerySize.width;
/// Gives you the power to get a portion of the height.
/// Useful for responsive applications.
///
/// [dividedBy] is for when you want to have a portion of the value you
/// would get like for example: if you want a value that represents a third
/// of the screen you can set it to 3, and you will get a third of the height
///
/// [reducedBy] is a percentage value of how much of the height you want
/// if you for example want 46% of the height, then you reduce it by 56%.
double heightTransformer({double dividedBy = 1, double reducedBy = 0.0}) {
return (mediaQuerySize.height -
((mediaQuerySize.height / 100) * reducedBy)) /
dividedBy;
}
/// Gives you the power to get a portion of the width.
/// Useful for responsive applications.
///
/// [dividedBy] is for when you want to have a portion of the value you
/// would get like for example: if you want a value that represents a third
/// of the screen you can set it to 3, and you will get a third of the width
///
/// [reducedBy] is a percentage value of how much of the width you want
/// if you for example want 46% of the width, then you reduce it by 56%.
double widthTransformer({double dividedBy = 1, double reducedBy = 0.0}) {
return (mediaQuerySize.width - ((mediaQuerySize.width / 100) * reducedBy)) /
dividedBy;
}
/// Divide the height proportionally by the given value
double ratio({
double dividedBy = 1,
double reducedByW = 0.0,
double reducedByH = 0.0,
}) {
return heightTransformer(dividedBy: dividedBy, reducedBy: reducedByH) /
widthTransformer(dividedBy: dividedBy, reducedBy: reducedByW);
}
/// similar to [MediaQuery.of(context).padding]
ThemeData get theme => Theme.of(this);
/// Check if dark mode theme is enable
bool get isDarkMode => (theme.brightness == Brightness.dark);
/// give access to Theme.of(context).iconTheme.color
Color? get iconColor => theme.iconTheme.color;
/// similar to [MediaQuery.of(context).padding]
TextTheme get textTheme => Theme.of(this).textTheme;
/// similar to [MediaQuery.of(context).padding]
EdgeInsets get mediaQueryPadding => MediaQuery.of(this).padding;
/// similar to [MediaQuery.of(context).padding]
MediaQueryData get mediaQuery => MediaQuery.of(this);
/// similar to [MediaQuery.of(context).viewPadding]
EdgeInsets get mediaQueryViewPadding => MediaQuery.of(this).viewPadding;
/// similar to [MediaQuery.of(context).viewInsets]
EdgeInsets get mediaQueryViewInsets => MediaQuery.of(this).viewInsets;
/// similar to [MediaQuery.of(context).orientation]
Orientation get orientation => MediaQuery.of(this).orientation;
/// check if device is on landscape mode
bool get isLandscape => orientation == Orientation.landscape;
/// check if device is on portrait mode
bool get isPortrait => orientation == Orientation.portrait;
/// similar to [MediaQuery.of(this).devicePixelRatio]
double get devicePixelRatio => MediaQuery.of(this).devicePixelRatio;
/// similar to [MediaQuery.of(this).textScaleFactor]
double get textScaleFactor => MediaQuery.of(this).textScaleFactor;
/// get the shortestSide from screen
double get mediaQueryShortestSide => mediaQuerySize.shortestSide;
/// True if width be larger than 800
bool get showNavbar => (width > 800);
/// True if the width is smaller than 600p
bool get isPhoneOrLess => width <= 600;
/// True if the width is higher than 600p
bool get isPhoneOrWider => width >= 600;
/// True if the shortestSide is smaller than 600p
bool get isPhone => (mediaQueryShortestSide < 600);
/// True if the width is smaller than 600p
bool get isSmallTabletOrLess => width <= 600;
/// True if the width is higher than 600p
bool get isSmallTabletOrWider => width >= 600;
/// True if the shortestSide is largest than 600p
bool get isSmallTablet => (mediaQueryShortestSide >= 600);
/// True if the shortestSide is largest than 720p
bool get isLargeTablet => (mediaQueryShortestSide >= 720);
/// True if the width is smaller than 720p
bool get isLargeTabletOrLess => width <= 720;
/// True if the width is higher than 720p
bool get isLargeTabletOrWider => width >= 720;
/// True if the current device is Tablet
bool get isTablet => isSmallTablet || isLargeTablet;
/// True if the width is smaller than 1200p
bool get isDesktopOrLess => width <= 1200;
/// True if the width is higher than 1200p
bool get isDesktopOrWider => width >= 1200;
/// same as [isDesktopOrLess]
bool get isDesktop => isDesktopOrLess;
/// Returns a specific value according to the screen size
/// if the device width is higher than or equal to 1200 return
/// [desktop] value. if the device width is higher than or equal to 600
/// and less than 1200 return [tablet] value.
/// if the device width is less than 300 return [watch] value.
/// in other cases return [mobile] value.
T responsiveValue<T>({
T? watch,
T? mobile,
T? tablet,
T? desktop,
}) {
assert(
watch != null || mobile != null || tablet != null || desktop != null);
var deviceWidth = mediaQuerySize.width;
//big screen width can display smaller sizes
final strictValues = [
if (deviceWidth >= 1200) desktop, //desktop is allowed
if (deviceWidth >= 600) tablet, //tablet is allowed
if (deviceWidth >= 300) mobile, //mobile is allowed
watch, //watch is allowed
].whereType<T>();
final looseValues = [
watch,
mobile,
tablet,
desktop,
].whereType<T>();
return strictValues.firstOrNull ?? looseValues.first;
}
} | 0 |
mirrored_repositories/PraxisFlutter/lib/presentation/core | mirrored_repositories/PraxisFlutter/lib/presentation/core/extensions/widget_extensions.dart | import 'package:flutter/widgets.dart';
/// add Padding Property to widget
extension WidgetPaddingX on Widget {
Widget paddingAll(double padding) =>
Padding(padding: EdgeInsets.all(padding), child: this);
Widget paddingSymmetric({double horizontal = 0.0, double vertical = 0.0}) =>
Padding(
padding:
EdgeInsets.symmetric(horizontal: horizontal, vertical: vertical),
child: this);
Widget paddingOnly({
double left = 0.0,
double top = 0.0,
double right = 0.0,
double bottom = 0.0,
}) =>
Padding(
padding: EdgeInsets.only(
top: top, left: left, right: right, bottom: bottom),
child: this);
Widget get paddingZero => Padding(padding: EdgeInsets.zero, child: this);
}
/// Add margin property to widget
extension WidgetMarginX on Widget {
Widget marginAll(double margin) =>
Container(margin: EdgeInsets.all(margin), child: this);
Widget marginSymmetric({double horizontal = 0.0, double vertical = 0.0}) =>
Container(
margin:
EdgeInsets.symmetric(horizontal: horizontal, vertical: vertical),
child: this);
Widget marginOnly({
double left = 0.0,
double top = 0.0,
double right = 0.0,
double bottom = 0.0,
}) =>
Container(
margin: EdgeInsets.only(
top: top, left: left, right: right, bottom: bottom),
child: this);
Widget get marginZero => Container(margin: EdgeInsets.zero, child: this);
}
/// Allows you to insert widgets inside a CustomScrollView
extension WidgetSliverBoxX on Widget {
Widget get sliverBox => SliverToBoxAdapter(child: this);
} | 0 |
mirrored_repositories/PraxisFlutter/lib/presentation/core | mirrored_repositories/PraxisFlutter/lib/presentation/core/ds/pair.dart | class Pair<A, B> {
A? first;
B? second;
Pair(this.first, this.second);
}
| 0 |
mirrored_repositories/PraxisFlutter/lib | mirrored_repositories/PraxisFlutter/lib/routing/routes.dart | import 'package:go_router/go_router.dart';
import 'package:praxis_flutter/features/home/home_page.dart';
import 'package:praxis_flutter/features/joke_list/joke_list_page.dart';
import 'package:praxis_flutter/features/login/login_page.dart';
import 'package:praxis_flutter/features/splash/splash_page.dart';
const loginRoute = '/login';
const jokeListRoute = "/jokesList";
const homeRoute = '/home';
const rootRoute = '/';
final praxisRoutes = GoRouter(
routes: [
splashRoute(),
loginPageRoute(),
homePageRoute(),
jokeListRoutePage()
],
);
jokeListRoutePage() {
return GoRoute(
path: jokeListRoute,
builder: (context, state) => const JokesPage(),
);
}
GoRoute homePageRoute() {
return GoRoute(
path: homeRoute,
builder: (context, state) => const HomePage(),
);
}
GoRoute loginPageRoute() {
return GoRoute(
path: loginRoute,
builder: (context, state) => const LoginPage(),
);
}
GoRoute splashRoute() {
return GoRoute(
path: rootRoute,
builder: (context, state) => const SplashPage(),
);
}
| 0 |
mirrored_repositories/PraxisFlutter/lib/ui | mirrored_repositories/PraxisFlutter/lib/ui/model/ui_model.dart | class UIModel {}
| 0 |
mirrored_repositories/PraxisFlutter/lib/ui/model | mirrored_repositories/PraxisFlutter/lib/ui/model/jokes/ui_joke.dart | import 'package:praxis_flutter/ui/model/ui_model.dart';
class UiJoke extends UIModel {
String value;
String id;
UiJoke(this.id, this.value);
}
class UIJokeList extends UIModel {
List<UiJoke> jokes;
UIJokeList(this.jokes);
} | 0 |
mirrored_repositories/PraxisFlutter/lib/ui/model | mirrored_repositories/PraxisFlutter/lib/ui/model/jokes/ui_jokes_mapper.dart | import 'package:injectable/injectable.dart';
import 'package:praxis_flutter/ui/model/jokes/ui_joke.dart';
import 'package:praxis_flutter_domain/mapper/ui_model_mapper.dart';
import 'package:praxis_flutter_domain/entities/jokes/dm_joke_list.dart';
import 'package:praxis_flutter_domain/entities/jokes/dm_joke.dart';
@injectable
class UIJokeMapper extends UiModelMapper<JokesListWithType, UIJokeList> {
@override
JokesListWithType mapToDomain(UIJokeList modelItem) {
return JokesListWithType(
modelItem.jokes.map((e) => Joke(e.id, e.value)).toList());
}
@override
UIJokeList mapToPresentation(JokesListWithType model) {
return UIJokeList(model.jokeList.map((e) => UiJoke(e.id, e.value)).toList());
}
}
| 0 |
mirrored_repositories/PraxisFlutter/lib | mirrored_repositories/PraxisFlutter/lib/l10n/l10n.dart | import 'package:flutter/widgets.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
export 'package:flutter_gen/gen_l10n/app_localizations.dart';
extension AppLocalizationsX on BuildContext {
AppLocalizations get l10n => AppLocalizations.of(this);
}
| 0 |
mirrored_repositories/PraxisFlutter/integration_test | mirrored_repositories/PraxisFlutter/integration_test/splash/splash_test.dart | import 'package:integration_test/integration_test.dart';
import '_splash_test_io.dart' if (dart.library.html) '_splash_test_web.dart' as tests;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
tests.main();
} | 0 |
mirrored_repositories/PraxisFlutter/integration_test | mirrored_repositories/PraxisFlutter/integration_test/splash/_splash_test_io.dart | import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:praxis_flutter/main_testing.dart' as app;
import 'package:praxis_flutter/presentation/core/widgets/platform_button.dart';
void main() {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('verify text', (WidgetTester tester) async {
// Build our app and trigger a frame.
app.main();
// Trace the timeline of the following operation. The timeline result will
// be written to `build/integration_response_data.json` with the key
// `timeline`.
await (binding as IntegrationTestWidgetsFlutterBinding)
.traceAction(() async {
// Trigger a frame.
await tester.pumpAndSettle();
final button = find.byWidgetPredicate(
(Widget widget) =>
widget is Text && widget.data == "Press Me!",
);
expect(
button,
findsOneWidget,
);
var pressButton = find.text("Press Me!");
await tester.tap(pressButton);
await tester.pump(const Duration(milliseconds: 500));
expect(
find.byWidgetPredicate(
(Widget widget) =>
widget is Text && widget.data == "You Pressed me! woo hoo!",
),
findsOneWidget,
);
});
});
}
| 0 |
mirrored_repositories/PraxisFlutter/integration_test | mirrored_repositories/PraxisFlutter/integration_test/splash/_splash_test_web.dart | import 'dart:html' as html;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:praxis_flutter/main_testing.dart' as app;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('verify text', (WidgetTester tester) async {
// Build our app and trigger a frame.
app.main();
// Trigger a frame.
await tester.pumpAndSettle();
final button = find.byWidgetPredicate(
(Widget widget) =>
widget is Text && widget.data == "Press Me!",
);
expect(
button,
findsOneWidget,
);
var pressButton = find.text("Press Me!");
await tester.tap(pressButton);
await tester.pump(const Duration(milliseconds: 500));
expect(
find.byWidgetPredicate(
(Widget widget) =>
widget is Text && widget.data == "You Pressed me! woo hoo!",
),
findsOneWidget,
);
});
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_data | mirrored_repositories/PraxisFlutter/praxis_data/lib/injection.config.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// InjectableConfigGenerator
// **************************************************************************
import 'package:get_it/get_it.dart' as _i1;
import 'package:injectable/injectable.dart' as _i2;
import 'package:praxis_flutter_domain/repositories/jokes/jokes_repository.dart'
as _i10;
import 'package:praxis_flutter_domain/repositories/login_repo.dart' as _i5;
import 'package:praxis_flutter_domain/use_cases/get_five_random_jokes_usecase.dart'
as _i3;
import 'package:praxis_flutter_domain/use_cases/login_use_case.dart' as _i7;
import 'mapper/jokes/jokes_mappers.dart' as _i4;
import 'repositories/jokes/data_jokes_repository.dart' as _i11;
import 'repositories/pr_login_repo.dart' as _i6;
import 'sources/local/praxis_database.dart' as _i8;
import 'sources/network/jokes_api.dart' as _i9;
import 'usecases/usecase_module.dart'
as _i12; // ignore_for_file: unnecessary_lambdas
// ignore_for_file: lines_longer_than_80_chars
/// an extension to register the provided dependencies inside of [GetIt]
extension GetItInjectableX on _i1.GetIt {
/// initializes the registration of provided dependencies inside of [GetIt]
_i1.GetIt $initGetIt(
{String? environment, _i2.EnvironmentFilter? environmentFilter}) {
final gh = _i2.GetItHelper(this, environment, environmentFilter);
final useCaseModule = _$UseCaseModule();
gh.factory<_i3.GetFiveRandomJokesUseCase>(
() => useCaseModule.getJokesUseCase);
gh.factory<_i4.JokeMapper>(() => _i4.JokeMapper());
gh.factory<_i4.JokesListMapper>(
() => _i4.JokesListMapper(get<_i4.JokeMapper>()));
gh.factory<_i5.LoginRepo>(() => _i6.PraxisLoginRepo());
gh.factory<_i7.LoginUseCase>(() => useCaseModule.loginUseCase);
gh.singleton<_i8.PraxisDatabase>(_i8.PraxisDatabase());
gh.factory<_i9.JokesApi>(() => _i9.JokesApi(get<_i4.JokesListMapper>()));
gh.factory<_i10.JokesRepository>(() => _i11.DataJokesRepository(
get<_i4.JokesListMapper>(),
get<_i9.JokesApi>(),
get<_i8.PraxisDatabase>(),
get<_i4.JokeMapper>()));
return this;
}
}
class _$UseCaseModule extends _i12.UseCaseModule {}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_data | mirrored_repositories/PraxisFlutter/praxis_data/lib/injection.dart | import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
import 'package:praxis_data/injection.config.dart';
@InjectableInit(
initializerName: r'$initGetIt', // default
preferRelativeImports: true, // default
asExtension: true, // default
)
void configureDataInjection(String env) {
GetIt.instance.$initGetIt(environment: env);
} | 0 |
mirrored_repositories/PraxisFlutter/praxis_data/lib | mirrored_repositories/PraxisFlutter/praxis_data/lib/mapper/entity_mapper.dart | abstract class EntityMapper<Domain, Data> {
Domain mapToDomain(Data entity);
Data mapToData(Domain model);
} | 0 |
mirrored_repositories/PraxisFlutter/praxis_data/lib/mapper | mirrored_repositories/PraxisFlutter/praxis_data/lib/mapper/jokes/jokes_mappers.dart | import 'package:injectable/injectable.dart';
import 'package:praxis_data/mapper/entity_mapper.dart';
import 'package:praxis_data/models/jokes/dt_joke.dart';
import 'package:praxis_data/models/jokes/dt_joke_list.dart';
import 'package:praxis_flutter_domain/entities/jokes/dm_joke_list.dart';
import 'package:praxis_flutter_domain/entities/jokes/dm_joke.dart';
@injectable
class JokesListMapper extends EntityMapper<JokesListWithType, DTJokeList> {
JokeMapper jokeMapper;
JokesListMapper(this.jokeMapper);
@override
DTJokeList mapToData(JokesListWithType model) {
return DTJokeList(
model.jokeList.map((e) => jokeMapper.mapToData(e)).toList());
}
@override
JokesListWithType mapToDomain(DTJokeList entity) {
return JokesListWithType(
entity.jokeList.map((e) => jokeMapper.mapToDomain(e)).toList());
}
}
@injectable
class JokeMapper extends EntityMapper<Joke, DTJoke> {
@override
DTJoke mapToData(Joke model) {
return DTJoke(model.id, model.value);
}
@override
Joke mapToDomain(DTJoke entity) {
return Joke(entity.id, entity.value);
}
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_data/lib/models | mirrored_repositories/PraxisFlutter/praxis_data/lib/models/jokes/dt_joke.dart | const String jokesTable = "jokesTable";
class JokeFields {
static const String id = "id";
static const String value = "value";
}
class DTJoke {
final String id;
final String value;
DTJoke(this.id, this.value);
DTJoke.fromJson(Map<String, dynamic> map)
: id = map['id'],
value = map['value'];
Map<String, Object?> toJson() => {JokeFields.id: id, JokeFields.value: value};
static DTJoke dtJokeFromJson(Map<String, Object?> json) =>
DTJoke(json[JokeFields.id] as String, json[JokeFields.value] as String);
@override
String toString() {
return '$id, $value';
}
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_data/lib/models | mirrored_repositories/PraxisFlutter/praxis_data/lib/models/jokes/dt_joke_list.dart | import 'package:praxis_data/mapper/entity_mapper.dart';
import 'package:praxis_data/models/jokes/dt_joke.dart';
class DTJokeList {
final List<DTJoke> jokeList;
DTJokeList(this.jokeList);
DTJokeList.fromJson(Map<String, dynamic> map)
:
jokeList = List<DTJoke>.from((map['result'].cast<Map<String, dynamic>>())
.toList()
.map((map) => DTJoke.fromJson(map)));
@override
String toString() {
return '$jokeList';
}
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_data/lib | mirrored_repositories/PraxisFlutter/praxis_data/lib/repositories/pr_login_repo.dart | import 'package:injectable/injectable.dart';
import 'package:praxis_flutter_domain/entities/login_result.dart';
import 'package:praxis_flutter_domain/repositories/login_repo.dart';
@Injectable(as: LoginRepo)
class PraxisLoginRepo extends LoginRepo {
@override
Future<LoginResult> login(String username, String password) async {
await Future.delayed(const Duration(seconds: 3));
return const LoginResult("some jwt", "some refresh token");
}
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_data/lib/repositories | mirrored_repositories/PraxisFlutter/praxis_data/lib/repositories/jokes/data_jokes_repository.dart | import 'dart:async';
import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
import 'package:praxis_data/mapper/jokes/jokes_mappers.dart';
import 'package:praxis_data/sources/local/praxis_database.dart';
import 'package:praxis_data/sources/network/jokes_api.dart';
import 'package:praxis_data/utils/platform_utils.dart';
import 'package:praxis_flutter_domain/entities/api_response.dart';
import 'package:praxis_flutter_domain/entities/jokes/dm_joke_list.dart';
import 'package:praxis_flutter_domain/repositories/jokes/jokes_repository.dart';
@Injectable(as: JokesRepository)
class DataJokesRepository implements JokesRepository {
final JokesListMapper mapper;
final JokesApi _jokesApi;
final PraxisDatabase _praxisDatabase;
final JokeMapper _jokeMapper;
DataJokesRepository(
this.mapper, this._jokesApi, this._praxisDatabase, this._jokeMapper);
@override
Future<ApiResponse<JokesListWithType>> getFiveRandomJokes() async {
// Checking platform since sqflite doesn't support WEB
if (isMobile()) {
try {
final networkResponse = await _jokesApi.getFiveRandomJokes();
if (networkResponse is Success) {
await _praxisDatabase.deleteAllJokes();
final networkJokes = (networkResponse as Success).data as JokesListWithType;
final jokes = mapper.mapToData(networkJokes);
jokes.jokeList.forEach((joke) {
_praxisDatabase.insertJoke(joke);
});
}
} on Exception catch (e, _) {
return Failure(error: e);
}
final dbJokes = await _praxisDatabase.getAllJokes();
final domainJokes =
dbJokes.map((dbJoke) => _jokeMapper.mapToDomain(dbJoke)).toList();
return Success(data: JokesListWithType( domainJokes));
} else {
return _jokesApi.getFiveRandomJokes();
}
}
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_data/lib | mirrored_repositories/PraxisFlutter/praxis_data/lib/utils/platform_utils.dart | import 'package:flutter/foundation.dart';
bool isMobile() =>
defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS;
| 0 |
mirrored_repositories/PraxisFlutter/praxis_data/lib | mirrored_repositories/PraxisFlutter/praxis_data/lib/usecases/usecase_module.dart | import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
import 'package:praxis_flutter_domain/use_cases/get_five_random_jokes_usecase.dart';
import 'package:praxis_flutter_domain/use_cases/login_use_case.dart';
@module
abstract class UseCaseModule {
LoginUseCase get loginUseCase => LoginUseCase(GetIt.instance.get());
GetFiveRandomJokesUseCase get getJokesUseCase =>
GetFiveRandomJokesUseCase(GetIt.instance.get());
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_data/lib/sources | mirrored_repositories/PraxisFlutter/praxis_data/lib/sources/network/jokes_api.dart | import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';
import 'package:praxis_data/mapper/jokes/jokes_mappers.dart';
import 'package:praxis_data/models/jokes/dt_joke_list.dart';
import 'package:praxis_data/sources/network/exceptions/api_exception.dart';
import 'package:praxis_data/sources/network/url.dart';
import 'package:praxis_flutter_domain/entities/api_response.dart';
import 'package:praxis_flutter_domain/entities/jokes/dm_joke_list.dart';
import 'package:logging/logging.dart';
const String genericApiFailMsg = "Unexpected API response!";
@injectable
class JokesApi {
final _logger = Logger('jokesApi');
final dio = Dio();
final JokesListMapper _mapper;
JokesApi(this._mapper);
Future<ApiResponse<JokesListWithType>> getFiveRandomJokes() async {
try {
final networkResponse = await dio.get(URL.fiveRandomJokesUrl);
if (networkResponse.data != null) {
final parsedDataResponse = DTJokeList.fromJson(networkResponse.data);
final parsedDomainResponse = _mapper.mapToDomain(parsedDataResponse);
return Success(data: parsedDomainResponse);
} else {
return Failure(
error: APIException(
networkResponse.statusMessage ?? genericApiFailMsg,
networkResponse.statusCode ?? 0,
networkResponse.statusMessage ?? genericApiFailMsg));
}
} on Exception catch (e, _) {
_logger.log(Level.WARNING, "API Error: ${e.toString()}");
return Failure(error: e);
}
}
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_data/lib/sources | mirrored_repositories/PraxisFlutter/praxis_data/lib/sources/network/url.dart | class URL {
static const String baseUrl = 'https://api.chucknorris.io';
static const String fiveRandomJokesUrl = '$baseUrl/jokes/search?query=animal';
} | 0 |
mirrored_repositories/PraxisFlutter/praxis_data/lib/sources/network | mirrored_repositories/PraxisFlutter/praxis_data/lib/sources/network/exceptions/api_exception.dart | class APIException implements Exception {
final String message;
final int statusCode;
final String statusText;
APIException(this.message, this.statusCode, this.statusText);
} | 0 |
mirrored_repositories/PraxisFlutter/praxis_data/lib/sources | mirrored_repositories/PraxisFlutter/praxis_data/lib/sources/local/praxis_database.dart | import 'dart:async';
import 'package:injectable/injectable.dart';
import 'package:path/path.dart';
import 'package:praxis_data/models/jokes/dt_joke.dart';
import 'package:sqflite/sqflite.dart';
const String _dbName = "praxis.db";
@singleton
class PraxisDatabase {
Database? _database;
PraxisDatabase();
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDB(_dbName);
return _database!;
}
Future<Database> _initDB(String filePath) async {
final dbPath = await getDatabasesPath();
final path = join(dbPath, filePath);
return await openDatabase(path, version: 1, onCreate: _createDB);
}
Future _createDB(Database db, int version) async {
const idType = "TEXT PRIMARY KEY";
const jokeType = "TEXT NOT NULL";
await db.execute("""
CREATE TABLE $jokesTable (
${JokeFields.id} $idType,
${JokeFields.value} $jokeType
)
""");
}
Future<bool> insertJoke(DTJoke joke) async {
final db = await database;
return await db.insert(jokesTable, joke.toJson(),
conflictAlgorithm: ConflictAlgorithm.replace) >
0;
}
Future<bool> deleteAllJokes() async {
final db = await database;
return await db.delete(jokesTable) > 0;
}
Future<List<DTJoke>> getAllJokes() async {
final db = await database;
final jokeMapList = await db.query(jokesTable);
final List<DTJoke> jokeList =
jokeMapList.map((jokeMap) => DTJoke.dtJokeFromJson(jokeMap)).toList();
return jokeList;
}
Future close() async {
final db = await database;
db.close();
}
}
| 0 |
mirrored_repositories/PraxisFlutter | mirrored_repositories/PraxisFlutter/test/widget_test.dart | import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:praxis_flutter/application/platform_app.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const PraxisApp());
// 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/PraxisFlutter/clean_architecture | mirrored_repositories/PraxisFlutter/clean_architecture/lib/clean_architecture.dart | library clean_architecture;
export 'package:clean_architecture/src/usecase.dart';
export 'package:clean_architecture/src/background_usecase.dart'; | 0 |
mirrored_repositories/PraxisFlutter/clean_architecture/lib | mirrored_repositories/PraxisFlutter/clean_architecture/lib/src/background_usecase.dart | import 'package:flutter/foundation.dart';
import 'dart:isolate';
import 'package:rxdart/rxdart.dart';
import 'dart:async';
import 'package:clean_architecture/src/usecase.dart';
enum BackgroundUseCaseState { idle, loading, calculating }
typedef UseCaseTask = void Function(
BackgroundUseCaseParams backgroundUseCaseParams);
/// Data structure sent from the isolate back to the main isolate
class BackgroundUseCaseMessage<T> {
T? data;
Error? error;
bool? done;
BackgroundUseCaseMessage({this.data, this.error, this.done = false});
}
/// Data structure sent from the main isolate to the other isolate
class BackgroundUseCaseParams<T> {
T? params;
SendPort port;
BackgroundUseCaseParams(this.port, {this.params});
}
/// A specialized type of [UseCase] that executes on a different isolate.
/// The purpose is identical to [UseCase], except that this runs on a different isolate.
/// A [BackgroundUseCase] is useful when performing expensive operations that ideally
/// should not be performed on the main isolate.
///
/// The code that is to be run on a different isolate can be provided through a
/// static method of the usecase. Then, a reference of that method should be returned
/// by overriding the [buildUseCaseTask] as shown below. Input data for the isolate
/// is provided by inside the `params` variable in [BackgroundUseCaseParams], which is
/// passed to the static method of type [UseCaseTask].
///
/// Output data can be passed back to the main isolate through `port.send()` provided
/// in the `port` member of [BackgroundUseCaseParams]. Any and all output should be
/// wrapped inside a [BackgroundUseCaseMessage]. Data can be passed by specifying the
/// `data` parameter, while errors can be reported through the `error` parameter.
///
/// In addition, a `done` flag can be set to indicate that the isolate has completed its task.
///
/// An example would be a usecase that performs matrix multiplication.
/// ```dart
/// class MatMulUseCase extends BackgroundUseCase<List<List<double>>, MatMulUseCaseParams> {
/// @override
/// buildUseCaseTask() {
/// return matmul;
/// }
///
/// static void matmul(BackgroundUseCaseParams params) async {
/// MatMulUseCaseParams matMulParams = params.params as MatMulUseCaseParams;
/// List<List<double>> result = List<List<double>>.generate(
/// 10, (i) => List<double>.generate(10, (j) => 0));
///
/// for (int i = 0; i < matMulParams.mat1.length; i++) {
/// for (int j = 0; j < matMulParams.mat1.length; j++) {
/// for (int k = 0; k < matMulParams.mat1.length; k++) {
/// result[i][j] += matMulParams.mat1[i][k] * matMulParams.mat2[k][j];
/// }
/// }
/// }
/// params.port.send(BackgroundUseCaseMessage(data: result));
///
/// }
///}
///
/// ```
/// Just like a regular [UseCase], a parameter class is recommended for any [BackgroundUseCase].
/// An example corresponding to the above example would be
/// ```dart
/// class MatMulUseCaseParams {
/// List<List<double>> mat1;
/// List<List<double>> mat2;
/// MatMulUseCaseParams(this.mat1, this.mat2);
/// MatMulUseCaseParams.random() {
/// var size = 10;
/// mat1 = List<List<double>>.generate(size,
/// (i) => List<double>.generate(size, (j) => i.toDouble() * size + j));
///
/// mat2 = List<List<double>>.generate(size,
/// (i) => List<double>.generate(size, (j) => i.toDouble() * size + j));
/// }
///}
/// ```
abstract class BackgroundUseCase<T, Params> extends UseCase<T, Params> {
BackgroundUseCaseState _state = BackgroundUseCaseState.idle;
late Isolate? _isolate;
final BehaviorSubject<T> _subject;
final ReceivePort _receivePort;
static late UseCaseTask _run;
BackgroundUseCase()
: assert(!kIsWeb, '''
[BackgroundUseCase] is not supported on web due to dart:isolate limitations.
'''),
_receivePort = ReceivePort(),
_subject = BehaviorSubject(),
super() {
_receivePort.listen(_handleMessage);
}
BackgroundUseCaseState get state => _state;
bool get isRunning => _state != BackgroundUseCaseState.idle;
/// Executes the usecase on a different isolate. Spawns [_isolate]
/// using the static method provided by [buildUseCaseTask] and listens
/// to a [BehaviorSubject] using the [observer] provided by the user.
/// All [Params] are sent to the [_isolate] through [BackgroundUseCaseParams].
@override
void execute(
void onData(T? event)?, Function? onError, void onDone()?, [Params? params]) async {
if (!isRunning) {
_state = BackgroundUseCaseState.loading;
_subject.listen(onData,
onError: onError, onDone: onDone);
_run = buildUseCaseTask();
Isolate.spawn<BackgroundUseCaseParams>(_run,
BackgroundUseCaseParams(_receivePort.sendPort, params: params))
.then<void>((Isolate isolate) {
if (!isRunning) {
logger.info('Killing background isolate.');
isolate.kill(priority: Isolate.immediate);
} else {
_state = BackgroundUseCaseState.calculating;
_isolate = isolate;
}
});
}
}
@override
@nonVirtual
Future<Stream<T?>> buildUseCaseStream(_) => Future.value(null);
/// Provides a [UseCaseTask] to be executed on a different isolate.
/// Must be overridden.
UseCaseTask buildUseCaseTask();
@override
void dispose() {
_stop();
super.dispose();
}
/// Kills the [_isolate] if it is running.
void _stop() {
if (isRunning) {
_state = BackgroundUseCaseState.idle;
if (_isolate != null) {
logger.info('Killing background isolate.');
_isolate!.kill(priority: Isolate.immediate);
_isolate = null;
}
}
}
/// Handles [BackgroundUseCaseMessage]s sent from the [_isolate].
/// The message could either be data or an error. Data and errors are forwarded to
/// the observer to be handled by the user.
void _handleMessage(dynamic message) {
assert(message is BackgroundUseCaseMessage,
'''All data and errors sent from the isolate in the static method provided by the user must be
wrapped inside a `BackgroundUseCaseMessage` object.''');
var msg = message as BackgroundUseCaseMessage;
if (msg.data != null) {
assert(msg.data is T);
_subject.add(msg.data);
} else if (msg.error != null) {
_subject.addError(msg.error!);
_subject.close();
}
if (msg.done!) {
_subject.close();
}
}
}
| 0 |
mirrored_repositories/PraxisFlutter/clean_architecture/lib | mirrored_repositories/PraxisFlutter/clean_architecture/lib/src/usecase.dart | import 'package:rxdart/rxdart.dart';
import 'package:logging/logging.dart';
import 'dart:async';
/// The abstract [UseCase] to be implemented by all usecases.
/// [T] Is the type to be returned by the [UseCase] to the [Presenter]
/// [Params] Is the object passed to the usecase containing all the needed parameters
/// for the [UseCase]
///
/// The [UseCase] represents a business-level process. It should be written purely
/// in `Dart` and `MUST NOT` include any `Flutter` code whatsoever. The `UseCase` is a part
/// of the `Domain` module of the application in the `Clean Architecture`.
///
/// Dependencies used by the [UseCase] must be injected by the [Presenter]. The [UseCase]
/// is essentially an `Stream` managing class. When the [execute()] function is triggered
/// by the [UseCase], an `Stream` is built using the `buildUseCaseStream()` method, subscribed to
/// by the [Observer] passed, and passed any required [params]. The [StreamSubscription] is then added
/// to a [CompositeSubscription]. This is later disposed when `dispose()` is called.
///
/// When extended, the extending class should override [buildUseCaseStream()], where the behavior and functionality
/// of the [UseCase] are defined. This method will return the `Stream` to be subscribed to, and will fire events to
/// the `Observer` in the [Presenter].
///
/// Get a list of `User` example:
///
/// ```dart
/// // In this case, no parameters were needed. Hence, void. Otherwise, change to appropriate.
/// // Typically, a GetUsersUseCaseParams class is defined and wrapped around the parameters
/// class GetUsersUseCase extends UseCase<List<User>, void> {
/// final UsersRepository _usersRepository; // some dependency to be injected
/// // the functionality is hidden behind this
/// // abstract class defined in the Domain module
/// // It should be implemented inside the Data or Device
/// // module and passed polymorphically.
///
/// GetUsersUseCase(this._usersRepository);
///
/// @override
/// // Since the parameter type is void, `_` ignores the parameter. Change according to the type
/// // used in the template.
/// Future<Stream<GetSponsorsUseCaseResponse>> buildUseCaseStream(_) async {
/// final StreamController<GetSponsorsUseCaseResponse> controller = StreamController();
/// try {
/// // get users
/// List<User> users = await _usersRepository.getAllUsers();
/// // Adding it triggers the .onNext() in the `Observer`
/// // It is usually better to wrap the reponse inside a respose object.
/// controller.add(users);
/// logger.finest('GetUsersUseCase successful.');
/// controller.close();
/// } catch (e) {
/// print(e);
/// logger.severe('GetUsersUseCase unsuccessful.');
/// // Trigger .onError
/// controller.addError(e);
/// }
/// return Stream(controller.stream);
/// }
/// }
///
/// ```
///
/// The dependencies injected into the [UseCase] `MUST` be in the form of `abstract` classes only, in order
/// to act as interfaces. These `abstract` classes are known as `Repositories`. The [UseCase] `MUST NOT` accept
/// anything as a dependency in the form of a class that contains any implemented code according to the `Clean Architecture`.
///
/// The `abstract` repositories are defined in the `Domain` module and implemented in either `Device` or `Data` modules.
/// They are then injected polymorphically into the [UseCase]. The repositories should be injected inwards from the
/// outermost layer `View -> Controller -> Presenter -> UseCase`.
///
/// For example, the below is a an `abstract` repository defined in the `Domain` module.
/// ```dart
///
/// abstract class AuthenticationRepository {
/// Future<void> register(
/// {@required String firstName,
/// @required String lastName,
/// @required String email,
/// @required String password});
///
/// /// Authenticates a user using his [username] and [password]
/// Future<void> authenticate(
/// {@required String email, @required String password});
///
/// /// Returns whether the [User] is authenticated.
/// Future<bool> isAuthenticated();
///
/// /// Returns the current authenticated [User].
/// Future<User> getCurrentUser();
///
/// /// Resets the password of a [User]
/// Future<void> forgotPassword(String email);
///
/// /// Logs out the [User]
/// Future<void> logout();
/// }
/// ```
abstract class UseCase<T, Params> {
/// This contains all the subscriptions to the [Stream]
late CompositeSubscription _disposables;
late Logger _logger;
Logger get logger => _logger;
UseCase() {
_disposables = CompositeSubscription();
_logger = Logger(runtimeType.toString());
}
/// Builds the [Stream] to be subscribed to. [Params] is required
/// by the [UseCase] to retrieve the appropraite data from the repository
Future<Stream<T?>> buildUseCaseStream(Params? params);
/// Subscribes to the [Observerable] with the [Observer] callback functions.
void perform(
void onData(T? event)?, Function? onError, void onDone()?,
[Params? params]) async {
final StreamSubscription subscription = (await buildUseCaseStream(params))
.listen(onData, onDone: onDone, onError: onError);
_addSubscription(subscription);
}
/// Disposes (unsubscribes) from the [Stream]
void dispose() {
if (!_disposables.isDisposed) {
logger.info('Disposing $runtimeType');
_disposables.dispose();
}
}
/// Adds a [StreamSubscription] i.e. the subscription to the
/// [Stream] to the [CompositeSubscription] list of subscriptions.
void _addSubscription(StreamSubscription subscription) {
if (_disposables.isDisposed) {
_disposables = CompositeSubscription();
}
_disposables.add(subscription);
}
}
/// A special type of [UseCase] that does not return any value.
/// This [UseCase] only performs a task and reports either success or failure.
/// A good candidate for such a [UseCase] would be logout or login.
/// ```dart
/// // A `UseCase` for logging out a `User`
/// class LogoutUseCase extends CompletableUseCase<void> {
///
/// AuthenticationRepository _authenticationRepository;///
/// LogoutUseCase(this._authenticationRepository);
///
/// @override
/// Future<Stream<User>> buildUseCaseStream(void ignore) async {
/// final StreamController<User> controller = StreamController();
/// try {
/// await _authenticationRepository.logout();
/// controller.close();
/// } catch (e) {
/// controller.addError(e);
/// }
/// return Stream(controller.stream);
/// }
/// }
///
/// ```
abstract class CompletableUseCase<Params> extends UseCase<void, Params?> {
@override
Future<Stream<void>> buildUseCaseStream(Params? params);
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_flutter_domain | mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/praxis_flutter_domain.dart | library praxis_flutter_domain;
export 'package:praxis_flutter_domain/entities/login_request.dart';
/// A Calculator.
class Calculator {
/// Returns [value] plus 1.
int addOne(int value) => value + 1;
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_flutter_domain | mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/validator.dart | abstract class Validator{
bool isValid();
} | 0 |
mirrored_repositories/PraxisFlutter/praxis_flutter_domain | mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/validations.dart | extension EmailValidation on String{
bool isValidEmail() {
return RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(this);
}
}
class EmailValidationException implements Exception {
}
class PasswordTooShortException implements Exception {
}
class InvalidRequestException implements Exception{
} | 0 |
mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib | mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/mapper/ui_model_mapper.dart | abstract class UiModelMapper<Dom, UI> {
UI mapToPresentation(Dom model);
Dom mapToDomain(UI modelItem);
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib | mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/use_cases/login_use_case.dart | import 'dart:async';
import 'package:clean_architecture/clean_architecture.dart';
import 'package:praxis_flutter_domain/entities/login_request.dart';
import 'package:praxis_flutter_domain/entities/login_result.dart';
import 'package:praxis_flutter_domain/repositories/login_repo.dart';
import 'package:praxis_flutter_domain/validations.dart';
class LoginUseCase extends UseCase<LoginResult, LoginRequest> {
final LoginRepo _loginRepo;
LoginUseCase(this._loginRepo);
@override
Future<Stream<LoginResult?>> buildUseCaseStream(LoginRequest? params) async {
final controller = StreamController<LoginResult>();
try {
if (params != null) {
params.isValid();
final loginResult =
await _loginRepo.login(params.email, params.password);
// Adding it triggers the .onNext() in the `Observer`
controller.add(loginResult);
logger.finest('LoginResult successful.');
controller.close();
} else {
logger.severe('LoginRequest is null.');
controller.addError(InvalidRequestException());
}
} catch (e) {
logger.severe('LoginResult unsuccessful.');
controller.addError(e);
}
return controller.stream;
}
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib | mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/use_cases/get_five_random_jokes_usecase.dart | import 'dart:async';
import 'package:clean_architecture/clean_architecture.dart';
import 'package:clean_architecture/src/usecase.dart';
import 'package:praxis_flutter_domain/entities/api_response.dart';
import 'package:praxis_flutter_domain/entities/jokes/dm_joke_list.dart';
import 'package:praxis_flutter_domain/repositories/jokes/jokes_repository.dart';
class GetFiveRandomJokesUseCase
extends UseCase<GetJokeListUseCaseResponse, void> {
final JokesRepository jokesRepository;
GetFiveRandomJokesUseCase(this.jokesRepository);
@override
Future<Stream<GetJokeListUseCaseResponse>> buildUseCaseStream(
void params) async {
final controller = StreamController<GetJokeListUseCaseResponse>();
try {
final jokeList = await jokesRepository.getFiveRandomJokes();
// Adding it triggers the .onNext() in the `Observer`
controller.add(GetJokeListUseCaseResponse(jokeList));
logger.finest('GetFiveRandomJokesUseCase successful.');
controller.close();
} catch (e) {
logger.severe('GetUserUseCase unsuccessful.');
controller.addError(e);
}
return controller.stream;
}
}
class GetJokeListUseCaseResponse {
final ApiResponse<JokesListWithType> jokeList;
GetJokeListUseCaseResponse(this.jokeList);
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib | mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/entities/login_request.dart | import 'package:praxis_flutter_domain/validator.dart';
import 'package:praxis_flutter_domain/validations.dart';
class LoginRequest implements Validator {
String email;
String password;
LoginRequest(this.email, this.password);
@override
bool isValid() {
if (!email.isValidEmail()) {
throw EmailValidationException();
}
if (password.length < 6) {
throw PasswordTooShortException();
}
return true;
}
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib | mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/entities/login_result.dart | import 'package:equatable/equatable.dart';
class LoginResult extends Equatable {
final String jwt;
final String refreshToken;
const LoginResult(this.jwt, this.refreshToken);
@override
List<Object?> get props => [jwt, refreshToken];
} | 0 |
mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib | mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/entities/api_response.dart | abstract class ApiResponse<T> {}
class Success<T> extends ApiResponse<T> {
T? data;
Success({required this.data});
}
class Failure<T> extends ApiResponse<T> {
Exception error;
Failure({required this.error});
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/entities | mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/entities/jokes/dm_joke.dart | class Joke{
final String id;
final String value;
Joke(this.id, this.value);
} | 0 |
mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/entities | mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/entities/jokes/dm_joke_list.dart | import 'package:praxis_flutter_domain/entities/jokes/dm_joke.dart';
import 'package:praxis_flutter_domain/mapper/ui_model_mapper.dart';
class JokesListWithType {
final List<Joke> jokeList;
JokesListWithType(this.jokeList);
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib | mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/repositories/login_repo.dart | import 'package:praxis_flutter_domain/entities/login_result.dart';
abstract class LoginRepo {
Future<LoginResult> login(String username, String password);
}
| 0 |
mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/repositories | mirrored_repositories/PraxisFlutter/praxis_flutter_domain/lib/repositories/jokes/jokes_repository.dart | import 'dart:async';
import 'package:praxis_flutter_domain/entities/api_response.dart';
import 'package:praxis_flutter_domain/entities/jokes/dm_joke_list.dart';
abstract class JokesRepository {
Future<ApiResponse<JokesListWithType>> getFiveRandomJokes();
} | 0 |
mirrored_repositories/PraxisFlutter | mirrored_repositories/PraxisFlutter/test_driver/integration_test.dart | import 'package:integration_test/integration_test_driver.dart';
Future<void> main() => integrationDriver(); | 0 |
mirrored_repositories/flutter/flutter_app | mirrored_repositories/flutter/flutter_app/lib/main.dart | import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => MyAppState(),
child: MaterialApp(
title: 'Name App',
theme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange),
),
home: MyHomePage(),
),
);
}
}
class MyAppState extends ChangeNotifier {
var current = WordPair.random();
void getNext() {
current = WordPair.random();
notifyListeners();
}
// ↓ Add the code below.
var favorites = <WordPair>[];
void toggleFavorite() {
if (favorites.contains(current)) {
favorites.remove(current);
} else {
favorites.add(current);
}
notifyListeners();
}
void deleteFavorites(WordPair item) {
favorites.remove(item);
//更新界面
notifyListeners();
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var selectedIndex = 0;
@override
Widget build(BuildContext context) {
Widget page;
switch (selectedIndex) {
case 0:
page = GeneratorPage();
break;
case 1:
page = FavoritesPage();
break;
default:
throw UnimplementedError('no widget for $selectedIndex');
}
return LayoutBuilder(builder: (context, constraints) {
return Scaffold(
body: Row(
children: [
SafeArea(
child: NavigationRail(
extended: constraints.maxWidth >= 600, // ← Here.
destinations: [
NavigationRailDestination(
icon: Icon(Icons.home),
label: Text('Home'),
),
NavigationRailDestination(
icon: Icon(Icons.favorite),
label: Text('Favorites'),
),
],
selectedIndex: selectedIndex,
onDestinationSelected: (value) {
setState(() {
selectedIndex = value;
});
print('selected: $value');
},
),
),
Expanded(
child: Container(
color: Theme.of(context).colorScheme.primaryContainer,
child: page,
),
),
],
),
);
});
}
}
// 添加喜欢数据界面
class GeneratorPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
var appState = context.watch<MyAppState>();
var pair = appState.current;
IconData icon;
if (appState.favorites.contains(pair)) {
icon = Icons.favorite;
} else {
icon = Icons.favorite_border;
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
BigCard(pair: pair),
SizedBox(height: 10),
Row(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton.icon(
onPressed: () {
appState.toggleFavorite();
},
icon: Icon(icon),
label: Text('Like'),
),
SizedBox(width: 10),
ElevatedButton(
onPressed: () {
appState.getNext();
},
child: Text('Next'),
),
],
),
],
),
);
}
}
//喜欢列表界面
class FavoritesPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
var appState = context.watch<MyAppState>();
if (appState.favorites.isEmpty) {
return Center(
child: Text('No favorites yet.'),
);
}
return ListView(
children: [
Padding(
padding: const EdgeInsets.all(20),
child: Text('You have '
'${appState.favorites.length} favorites:'),
),
for (var pair in appState.favorites)
Row(
children: [
Expanded(
child: ListTile(
leading: Icon(Icons.favorite),
title: Text(pair.asLowerCase),
),
),
ElevatedButton(
onPressed: () {
appState.deleteFavorites(pair);
},
child: Text('Delete'),
),
],
)
],
);
}
}
class BigCard extends StatelessWidget {
const BigCard({
super.key,
required this.pair,
});
final WordPair pair;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final style = theme.textTheme.displayMedium!.copyWith(
color: theme.colorScheme.onPrimary,
);
return Card(
color: Color(0xFF00FF00),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(pair.asLowerCase, style: style),
),
);
}
}
| 0 |
mirrored_repositories/flutter/flutter_app | mirrored_repositories/flutter/flutter_app/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
// expect(find.text('0'), findsOneWidget);
// expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
// await tester.tap(find.byIcon(Icons.add));
// await tester.pump();
// Verify that our counter has incremented.
// expect(find.text('0'), findsNothing);
// expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/Educational-App-UI | mirrored_repositories/Educational-App-UI/lib/main.dart | // ignore_for_file: prefer_const_constructors
import 'package:educational_app/screens/introScreen.dart';
import 'package:flutter/material.dart';
void main(List<String> args) {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: IntroScreen(),
),
);
}
}
| 0 |
mirrored_repositories/Educational-App-UI/lib | mirrored_repositories/Educational-App-UI/lib/elements/items.dart | // ignore_for_file: unused_import, unused_local_variable
import 'package:flutter/material.dart';
class TutorialsName {
String language;
String iconpath;
Color boxColor;
TutorialsName({
required this.language,
required this.iconpath,
required this.boxColor,
});
static List<TutorialsName> getTutorialsName() {
List<TutorialsName> tutorialname = [];
tutorialname.add(TutorialsName(
language: "C",
iconpath: 'images/c.png',
boxColor: Colors.yellowAccent));
tutorialname.add(TutorialsName(
language: "MySQL",
iconpath: 'images/mysql.png',
boxColor: Colors.redAccent));
tutorialname.add(TutorialsName(
language: "JavaScript",
iconpath: 'images/java-script.png',
boxColor: Colors.greenAccent));
return tutorialname;
}
}
| 0 |
mirrored_repositories/Educational-App-UI/lib | mirrored_repositories/Educational-App-UI/lib/screens/introScreen.dart | // ignore_for_file: file_names, prefer_const_constructors, avoid_unnecessary_containers, unused_field, prefer_final_fields
import 'package:educational_app/screens/homeScreen.dart';
import 'package:flutter/material.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
class IntroScreen extends StatefulWidget {
const IntroScreen({super.key});
@override
State<IntroScreen> createState() => _IntroScreenState();
}
class _IntroScreenState extends State<IntroScreen> {
PageController _controller = PageController();
bool onLastPage = false;
@override
Widget build(BuildContext context) {
return Stack(
children: [
PageView(
controller: _controller,
onPageChanged: (index) {
setState(() {
onLastPage = (index == 2);
});
},
children: [
Container(
color: Colors.yellowAccent,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
// ignore: prefer_const_literals_to_create_immutables
children: [
Image.asset('images/introscreen.png'),
Text(
"Be a Developer",
style: TextStyle(
fontSize: 15,
letterSpacing: 2.5,
),
),
Text(
"Everything is All About Coding",
style: TextStyle(
fontSize: 20,
letterSpacing: 2.5,
fontWeight: FontWeight.w600,
),
),
],
),
),
Container(
color: Colors.teal,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('images/introscreen.png'),
Text(
"Be a Developer",
style: TextStyle(
fontSize: 15,
letterSpacing: 2.5,
),
),
Text(
"Everything is All About Coding",
style: TextStyle(
fontSize: 20,
letterSpacing: 2.5,
fontWeight: FontWeight.w600,
),
),
],
),
),
Container(
color: Colors.red,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('images/introscreen.png'),
Text(
"Be a Developer",
style: TextStyle(
fontSize: 15,
letterSpacing: 2.5,
),
),
Text(
"Everything is All About Coding",
style: TextStyle(
fontSize: 20,
letterSpacing: 2.5,
fontWeight: FontWeight.w600,
),
),
],
),
),
],
),
Container(
alignment: Alignment(0, 0.85),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
GestureDetector(
onTap: () {
_controller.jumpToPage(2);
},
child: Text(
'Skip',
style: TextStyle(
fontSize: 15,
letterSpacing: 2.5,
fontWeight: FontWeight.w600,
),
),
),
SmoothPageIndicator(
controller: _controller,
count: 3,
effect: JumpingDotEffect(
activeDotColor: Colors.black,
dotColor: Colors.white,
dotHeight: 5,
),
),
onLastPage
? GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
));
},
child: Text(
"Done",
style: TextStyle(
letterSpacing: 2.5,
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
)
: GestureDetector(
onTap: () {
_controller.nextPage(
duration: Duration(
seconds: 1,
),
curve: Curves.easeIn);
},
child: Text(
"Next",
style: TextStyle(
letterSpacing: 2.5,
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
),
]))
],
);
}
}
| 0 |
mirrored_repositories/Educational-App-UI/lib | mirrored_repositories/Educational-App-UI/lib/screens/seemore.dart | // ignore_for_file: prefer_const_constructors, unused_element, avoid_print, prefer_const_literals_to_create_immutables, avoid_unnecessary_containers, unused_import
import 'package:educational_app/screens/dashboard.dart';
import 'package:educational_app/elements/items.dart';
import 'package:educational_app/screens/homeScreen.dart';
import 'package:flutter/material.dart';
import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:google_nav_bar/google_nav_bar.dart';
class SeeMore extends StatefulWidget {
const SeeMore({super.key});
@override
State<SeeMore> createState() => _SeeMoreState();
}
class _SeeMoreState extends State<SeeMore> {
List<TutorialsName> tutorialname = [];
void _getTutorialsName() {
tutorialname = TutorialsName.getTutorialsName();
}
@override
Widget build(BuildContext context) {
_getTutorialsName();
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SafeArea(
child: Scaffold(
body: Stack(
children: [
Column(
children: [
ListView.separated(
itemBuilder: (context, index) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color:
tutorialname[index].boxColor.withOpacity(0.3),
),
child: Column(
children: [
Container(
height: 80,
width: 80,
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.circle,
),
)
],
),
);
},
separatorBuilder: (context, index) => SizedBox(
height: 10,
),
itemCount: tutorialname.length)
],
)
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Educational-App-UI/lib | mirrored_repositories/Educational-App-UI/lib/screens/homeScreen.dart | // ignore_for_file: prefer_const_constructors, duplicate_ignore, sized_box_for_whitespace, avoid_unnecessary_containers, prefer_const_literals_to_create_immutables, unused_import
import 'package:educational_app/screens/dashboard.dart';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
// ignore: prefer_const_constructors
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.grey.shade200,
body: SafeArea(
child: Stack(children: [
Center(
child: Column(
children: [
SizedBox(
height: 10,
),
Container(
height: 150,
width: 150,
child: Image.asset("images/introscreen.png"),
),
SizedBox(
height: 10,
),
Text(
'Welcome Back you have been missed',
style: TextStyle(
fontSize: 20,
letterSpacing: 1.1,
),
),
SizedBox(
height: 30,
),
Container(
padding: EdgeInsets.all(10),
child: Column(
children: [
Container(
decoration: BoxDecoration(
border: Border.all(
width: 1,
color: Colors.white,
),
borderRadius: BorderRadius.circular(10)),
child: TextField(
decoration: InputDecoration(
border: InputBorder.none,
prefixIcon: Icon(Icons.email),
hintText: 'username or email',
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey),
),
fillColor: Colors.grey.shade200,
),
)),
SizedBox(
height: 20,
),
Container(
decoration: BoxDecoration(
border: Border.all(
width: 1,
color: Colors.white,
),
borderRadius: BorderRadius.circular(10)),
child: TextField(
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'password',
prefixIcon: Icon(Icons.password_outlined),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey)),
fillColor: Colors.grey.shade200,
),
)),
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
GestureDetector(
onTap: () {},
child: Text(
'Forgot Password?',
style: TextStyle(
fontSize: 12,
),
)),
SizedBox(
height: 15,
)
]),
],
),
),
SizedBox(
height: 15,
),
TextButton(
style: ButtonStyle(),
onPressed: () {
setState(() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DashBoardPage(),
));
});
},
child: Text(
'Sign In',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
))
],
),
),
]),
),
),
);
}
}
| 0 |
mirrored_repositories/Educational-App-UI/lib | mirrored_repositories/Educational-App-UI/lib/screens/dashboard.dart | // ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables, duplicate_ignore, sized_box_for_whitespace, avoid_unnecessary_containers, unused_element, non_constant_identifier_names, avoid_print
import 'package:educational_app/screens/seemore.dart';
import 'package:flutter/material.dart';
class DashBoardPage extends StatefulWidget {
const DashBoardPage({super.key});
@override
State<DashBoardPage> createState() => _DashBoardPageState();
}
class _DashBoardPageState extends State<DashBoardPage> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'DashBoard',
style: TextStyle(
color: Colors.black,
),
),
IconButton(
onPressed: () {},
icon: Icon(Icons.search),
color: Colors.black,
)
],
),
backgroundColor: Colors.grey[300],
elevation: 0.0,
),
// ignore: prefer_const_literals_to_create_immutablesb
body: Stack(children: [
ListView(children: [
Column(
children: [
SizedBox(
height: 10,
),
Padding(
padding: EdgeInsets.all(10),
child: Container(
height: 150,
width: 400,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'images/dashboardim.png',
),
fit: BoxFit.fill,
),
borderRadius: BorderRadius.circular(5),
boxShadow: [
BoxShadow(
blurRadius: 6,
offset: Offset(1, 2),
)
]),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
IconButton(
onPressed: () {},
icon: Icon(
Icons.menu_book,
size: 30,
),
),
SizedBox(
height: 70,
),
Padding(
padding: EdgeInsets.only(left: 10, top: 10),
child: GestureDetector(
onTap: () {
setState(() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SeeMore(),
));
});
},
child: Text(
'See More>',
style: TextStyle(
fontWeight: FontWeight.bold,
),
)),
)
],
),
),
),
SizedBox(
height: 15,
),
Padding(
padding: EdgeInsets.only(left: 15),
child: Row(children: [
Text(
"Options",
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
SizedBox(
width: 10,
),
Image.asset(
'images/menu.gif',
height: 20,
width: 20,
)
]),
),
SizedBox(
height: 15,
),
options_menu(),
SizedBox(
height: 10,
),
Column(children: [
tutorials_text(),
]),
SizedBox(
height: 20,
),
tutorials(),
],
),
]),
]),
drawerScrimColor: Colors.greenAccent,
// ignore: prefer_const_literals_to_create_immutables
bottomNavigationBar: BottomNavigationBar(items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.settings), label: 'Settings'),
BottomNavigationBarItem(icon: Icon(Icons.menu), label: 'Menu'),
]),
));
}
SingleChildScrollView tutorials() {
return SingleChildScrollView(
child: Padding(
padding: EdgeInsets.only(left: 15),
child: Column(
children: [
GestureDetector(
onTap: () {
print("Tapped");
},
child: Container(
child: Row(
children: [
Image.asset(
'images/mysql.png',
cacheHeight: 50,
cacheWidth: 50,
),
SizedBox(width: 20),
Container(
width: 300,
child: ListTile(
title: Text('MySQL'),
subtitle: Text('MySQL is used for Database'),
trailing: Icon(Icons.more_horiz_rounded),
),
)
],
),
),
),
GestureDetector(
onTap: () {
print("Tapped");
},
child: Container(
child: Row(
children: [
Image.asset(
'images/java-script.png',
cacheHeight: 50,
cacheWidth: 50,
),
SizedBox(width: 20),
Container(
width: 300,
child: ListTile(
title: Text('JS'),
subtitle: Text('Java-Script'),
trailing: Icon(Icons.more_horiz_rounded),
),
),
],
),
),
),
GestureDetector(
onTap: () {
print("Tapped");
},
child: Container(
child: Row(
children: [
Image.asset(
'images/java-script.png',
cacheHeight: 50,
cacheWidth: 50,
),
SizedBox(width: 20),
Container(
width: 300,
child: ListTile(
title: Text('JS'),
subtitle: Text('Java-Script'),
trailing: Icon(Icons.more_horiz_rounded),
),
),
],
),
),
),
GestureDetector(
onTap: () {
print("Tapped");
},
child: Container(
child: Row(
children: [
Image.asset(
'images/java-script.png',
cacheHeight: 50,
cacheWidth: 50,
),
SizedBox(width: 20),
Container(
width: 300,
child: ListTile(
title: Text('JS'),
subtitle: Text('Java-Script'),
trailing: Icon(Icons.more_horiz_rounded),
),
),
],
),
),
),
],
),
),
);
}
Padding tutorials_text() {
return Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: Container(
child: Row(children: [
Text(
'Popular Tutorials',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
SizedBox(
width: 10,
),
Image.asset(
'images/play.gif',
height: 30,
width: 30,
)
]),
),
);
}
Padding options_menu() {
return Padding(
padding: EdgeInsets.only(
left: 10,
right: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
height: 90,
width: 70,
child: Column(
children: [
Image.asset(
'images/display-code.png',
cacheHeight: 40,
cacheWidth: 40,
),
Text(
'Code',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
),
)
],
),
),
SizedBox(
width: 35,
),
Container(
height: 90,
width: 70,
child: Column(
children: [
Image.asset(
'images/download.png',
cacheHeight: 40,
cacheWidth: 40,
),
Text(
'Download',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
),
)
],
),
),
SizedBox(
width: 35,
),
Container(
height: 90,
width: 70,
child: Column(
children: [
Image.asset(
'images/stats.png',
cacheHeight: 40,
cacheWidth: 40,
),
Text(
'Process',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
),
)
],
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/Educational-App-UI | mirrored_repositories/Educational-App-UI/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:educational_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-delivery-mvp | mirrored_repositories/flutter-delivery-mvp/lib/main.dart | import 'package:flutter/material.dart';
import 'package:tobbund/screens/splash.dart';
import 'package:provider/provider.dart';
import 'package:tobbund/controller/new_declerations_provider.dart';
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider<NewDeclarationProvider>(
create: (_) => NewDeclarationProvider(),
lazy: false,
),
],
child: MyApp(),
),
);
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'TOBB UND',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return SplashScreen();
}
}
| 0 |
mirrored_repositories/flutter-delivery-mvp/lib | mirrored_repositories/flutter-delivery-mvp/lib/repository/UserRepository.dart | import 'package:tobbund/model/user.dart';
class UserRepository{
static final UserRepository _instance = UserRepository._internal();
UserRepository._internal();
factory UserRepository() => _instance;
User _user;
set user(User value) => this._user = value;
User get user => _user;
} | 0 |
mirrored_repositories/flutter-delivery-mvp/lib | mirrored_repositories/flutter-delivery-mvp/lib/repository/data.dart | import 'package:tobbund/model/user.dart';
User user; | 0 |