repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/News-app-flutter-bloc/lib/bloc | mirrored_repositories/News-app-flutter-bloc/lib/bloc/navbar_main/navbar_main_state.dart | part of 'navbar_main_bloc.dart';
@immutable
class NavbarMainState extends Equatable {
final NavbarItem item;
const NavbarMainState(this.item);
@override
List<Object?> get props => [item];
}
| 0 |
mirrored_repositories/News-app-flutter-bloc/lib/bloc | mirrored_repositories/News-app-flutter-bloc/lib/bloc/navbar_main/navbar_main_bloc.dart |
import 'package:bloc/bloc.dart';
import 'package:dispatcher/enums/nav_bar_item.dart';
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';
part 'navbar_main_event.dart';
part 'navbar_main_state.dart';
class NavbarMainBloc extends Bloc<NavbarMainEvent, NavbarMainState> {
NavbarMainBloc() : super(const NavbarMainState(NavbarItem.home)) {
on<NavbarItemPressed>((event, emit) {
emit(NavbarMainState(event.tappedItem));
});
}
}
| 0 |
mirrored_repositories/News-app-flutter-bloc/lib/bloc | mirrored_repositories/News-app-flutter-bloc/lib/bloc/home/home_bloc.dart | import 'dart:developer';
import 'package:bloc/bloc.dart';
import 'package:dispatcher/repository/articles_repository.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:meta/meta.dart';
import '../../model/article.dart';
part 'home_event.dart';
part 'home_state.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState> {
static const pageSize = 20;
final ArticlesRepository articleRepository;
int _pageNum = 1;
bool _isSearchExhausted = false;
bool _isFetching = false;
final List<Article> _articles = [];
HomeBloc({required this.articleRepository}) : super(HomeInitial()) {
log("HomeBloc init..");
on<FetchArticles>(_onFetchArticles);
}
_onFetchArticles(FetchArticles event, Emitter<HomeState> emit) async {
if (!_isSearchExhausted && !_isFetching) {
_isFetching = true;
emit(_pageNum <= 1
? Loading()
: ArticlesLoaded(articles: _articles, query: event.searchKey, isFetchingMore: true));
final articlesToAdd = await articleRepository.getPageTopHeadlines(_pageNum, event.searchKey);
if (articlesToAdd.length < pageSize) {
_isSearchExhausted = true;
}
_articles.addAll(articlesToAdd);
emit(ArticlesLoaded(articles: _articles, query: event.searchKey, isFetchingMore: false));
_pageNum++;
_isFetching = false;
}
}
}
| 0 |
mirrored_repositories/News-app-flutter-bloc/lib/bloc | mirrored_repositories/News-app-flutter-bloc/lib/bloc/home/home_state.dart | part of 'home_bloc.dart';
@immutable
abstract class HomeState extends Equatable {}
class HomeInitial extends HomeState {
@override
List<Object?> get props => [];
}
class ArticlesLoaded extends HomeState {
ArticlesLoaded({
required this.articles,
required this.query,
required this.isFetchingMore,
});
final List<Article> articles;
final String? query;
bool isFetchingMore;
@override
List<Object?> get props => [articles, query, isFetchingMore];
}
class Loading extends HomeState {
@override
List<Object?> get props => [];
}
class Error extends HomeState {
Error({required this.message});
final String message;
@override
List<Object?> get props => [message];
} | 0 |
mirrored_repositories/News-app-flutter-bloc/lib/bloc | mirrored_repositories/News-app-flutter-bloc/lib/bloc/home/home_event.dart | part of 'home_bloc.dart';
@immutable
abstract class HomeEvent {}
class FetchArticles extends HomeEvent {
FetchArticles({this.searchKey = ""});
final String? searchKey;
}
| 0 |
mirrored_repositories/News-app-flutter-bloc/lib | mirrored_repositories/News-app-flutter-bloc/lib/model/article.dart | import 'package:dispatcher/api/articles/dto/article_dto.dart';
import 'package:intl/intl.dart';
class Article {
const Article({
required this.imageUrl,
required this.title,
required this.author,
required this.description,
required this.publishedAt,
this.isFavorite = false
});
final String imageUrl;
final String title;
final String author;
final String description;
final DateTime publishedAt;
final bool isFavorite;
factory Article.fromDto(ArticleDto dto) {
return Article(
imageUrl: dto.urlToImage ?? '',
title: dto.title ?? '',
author: dto.author ?? 'Unknown author',
description: dto.description ?? '',
publishedAt: DateFormat('yyyy-mm-dd').parse(dto.publishedAt ?? '')
);
}
} | 0 |
mirrored_repositories/News-app-flutter-bloc/lib | mirrored_repositories/News-app-flutter-bloc/lib/enums/nav_bar_item.dart | import 'package:flutter/material.dart';
enum NavbarItem {
home('Home', Colors.greenAccent, Icons.home),
favorites('Favorites', Colors.pinkAccent, Icons.star_border),
profile('Profile', Colors.indigoAccent, Icons.account_circle);
const NavbarItem(this.title, this.color, this.icon);
final String title;
final Color color;
final IconData icon;
} | 0 |
mirrored_repositories/News-app-flutter-bloc/lib/api | mirrored_repositories/News-app-flutter-bloc/lib/api/articles/articles_api.dart | import 'package:dispatcher/api/articles/responses/get_everything_response.dart';
import 'package:dispatcher/bloc/home/home_bloc.dart';
import 'package:dispatcher/constants/constants.dart';
import 'package:flutter/cupertino.dart';
import '../../network/dio_client.dart';
class ArticlesApi {
static const _everything = 'everything';
static const _topHeadlines = 'top-headlines';
late final DioClient dioClient = DioClient.instance;
ArticlesApi();
Future<GetEverythingResponse> getEverything() async {
try {
await Future.delayed(const Duration(seconds: DioClient.testDelaySec));
final response = await dioClient.get(
_everything,
queryParameters: {'apiKey': Constants.apiKey, 'q': ''}
);
return response as GetEverythingResponse;
} catch (e) {
rethrow;
}
}
Future<GetEverythingResponse> getTopHeadlines(int pageNum, String? query) async {
try {
await Future.delayed(const Duration(seconds: DioClient.testDelaySec));
final response = await dioClient.get(_topHeadlines, queryParameters: {
'apiKey': Constants.apiKey,
'country': 'us',
'page': pageNum,
'q': query,
'pageSize': HomeBloc.pageSize,
});
return GetEverythingResponse.fromJson(response.data);
} catch (e) {
debugPrint("ArticlesApi: Exception - $e");
rethrow;
}
}
} | 0 |
mirrored_repositories/News-app-flutter-bloc/lib/api/articles | mirrored_repositories/News-app-flutter-bloc/lib/api/articles/responses/get_everything_response.dart | import '../dto/article_dto.dart';
class GetEverythingResponse {
final String? status;
final int? totalResults;
final List<ArticleDto> articles;
GetEverythingResponse({this.status, this.totalResults, required this.articles});
factory GetEverythingResponse.fromJson(Map<String, dynamic> json) {
var articlesResult = <ArticleDto>[];
if (json['articles'] != null) {
json['articles'].forEach((v) {
articlesResult.add(ArticleDto.fromJson(v));
});
}
return GetEverythingResponse(
status: json['status'],
totalResults: json['totalResults'],
articles: articlesResult
);
}
}
| 0 |
mirrored_repositories/News-app-flutter-bloc/lib/api/articles | mirrored_repositories/News-app-flutter-bloc/lib/api/articles/dto/article_dto.dart | import 'Source_dto.dart';
class ArticleDto {
Source? source;
String? author;
String? title;
String? description;
String? url;
String? urlToImage;
String? publishedAt;
String? content;
ArticleDto(
{this.source,
this.author,
this.title,
this.description,
this.url,
this.urlToImage,
this.publishedAt,
this.content});
ArticleDto.fromJson(Map<String, dynamic> json) {
source = json['source'] != null ? Source.fromJson(json['source']) : null;
author = json['author'];
title = json['title'];
description = json['description'];
url = json['url'];
urlToImage = json['urlToImage'];
publishedAt = json['publishedAt'];
content = json['content'];
}
} | 0 |
mirrored_repositories/News-app-flutter-bloc/lib/api/articles | mirrored_repositories/News-app-flutter-bloc/lib/api/articles/dto/Source_dto.dart |
class Source {
String? id;
String? name;
Source({this.id, this.name});
Source.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
} | 0 |
mirrored_repositories/News-app-flutter-bloc/lib/ui | mirrored_repositories/News-app-flutter-bloc/lib/ui/widgets/favorite_article_card.dart | import 'package:flutter/material.dart';
import '../../model/article.dart';
class FavoriteArticleCard extends StatelessWidget {
static const cardRadius = 5.0;
static const imageHeight = 100.0;
final Article article;
const FavoriteArticleCard({super.key, required this.article});
@override
Widget build(BuildContext context) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(cardRadius)),
child: Container(
height: 120,
padding: const EdgeInsets.all(6.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
_articleImageView(),
Expanded(
child: Container(
margin: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(article.title,
maxLines: 3,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
)),
_chipList()
],
),
),
),
],
),
),
);
}
ClipRRect _articleImageView() {
return ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(cardRadius)),
child: Image.network(
article.imageUrl,
errorBuilder:
(BuildContext context, Object exception, StackTrace? stackTrace) {
return Image.asset(
'images/no_image.jpeg',
height: imageHeight,
width: imageHeight,
);
},
height: imageHeight,
width: imageHeight,
fit: BoxFit.fill,
loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) {
return child;
}
return SizedBox(
height: imageHeight,
width: imageHeight,
child: Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes!
: null,
),
),
);
},
),
);
}
_chipList() {
return Wrap(
spacing: 6.0,
runSpacing: 6.0,
children: <Widget>[
_buildChip('Crypto'),
_buildChip('+3'),
],
);
}
Widget _buildChip(String label) {
return Chip(
label: Text(
label,
style: const TextStyle(
color: Color(0xFF5A5A89),
fontSize: 12,
fontWeight: FontWeight.w500
),
),
backgroundColor: const Color(0XFFD9DBE9),
padding: const EdgeInsets.symmetric(horizontal: 8.0),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
);
}
}
| 0 |
mirrored_repositories/News-app-flutter-bloc/lib/ui | mirrored_repositories/News-app-flutter-bloc/lib/ui/widgets/article_card.dart |
import 'package:flutter/material.dart';
import '../../model/article.dart';
class ArticleCard extends StatelessWidget {
static const cardRadius = 20.0;
static const separateHeight = 12.0;
final Article article;
const ArticleCard({super.key, required this.article});
@override
Widget build(BuildContext context) {
return Card(
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(cardRadius)),
child: Column(
children: [
_articleImageView(),
const SizedBox(height: 30),
Container(
padding: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(article.publishedAt.toString(),
style: _textStyleDateAndAuthor()),
const SizedBox(height: separateHeight),
Text(article.title,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
)),
const SizedBox(height: separateHeight),
Text(article.author, style: _textStyleDateAndAuthor()),
const SizedBox(height: separateHeight),
Text(article.description,
style: const TextStyle(
fontSize: 14, fontWeight: FontWeight.w400)),
],
),
),
],
),
);
}
ClipRRect _articleImageView() {
return ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(cardRadius),
topRight: Radius.circular(cardRadius)),
child: Image.network(
article.imageUrl,
errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
return Image.asset(
'images/no_image.jpeg',
height: 150,
width: double.infinity,
);
},
height: 150,
width: double.infinity,
fit: BoxFit.fill,
loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) {
return child;
}
return Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes!
: null,
),
);
},
),
);
}
TextStyle _textStyleDateAndAuthor() {
return TextStyle(
color: const Color(0xff5A5A89).withOpacity(0.7),
fontSize: 14,
fontWeight: FontWeight.w400);
}
}
| 0 |
mirrored_repositories/News-app-flutter-bloc/lib/ui/widgets | mirrored_repositories/News-app-flutter-bloc/lib/ui/widgets/app_bars/main_app_bar.dart | import 'package:dispatcher/constants/constants.dart';
import 'package:flutter/material.dart';
import '../../../constants/app_colors.dart';
class MainAppBar extends StatelessWidget implements PreferredSizeWidget {
const MainAppBar({
super.key,
required this.title,
});
final String title;
@override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: AppColors.appBackground,
elevation: Constants.appBarElevation,
title: Row(
children: [
SizedBox(
height: 31,
width: 31,
child: Image.asset("images/LOGO.png"),
),
Text(title),
],
),
actions: [
IconButton(
icon: const Icon(Icons.search_outlined),
color: AppColors.iconColor,
onPressed: () => {},
),
IconButton(
icon: const Icon(Icons.notifications),
color: AppColors.iconColor,
onPressed: () => {},
),
],
);
}
@override
Size get preferredSize => const Size.fromHeight(Constants.appBarHeight);
} | 0 |
mirrored_repositories/News-app-flutter-bloc/lib/ui/widgets | mirrored_repositories/News-app-flutter-bloc/lib/ui/widgets/app_bars/back_app_bar.dart | import 'package:dispatcher/constants/constants.dart';
import 'package:flutter/material.dart';
import '../../../constants/app_colors.dart';
class BackAppBar extends StatelessWidget implements PreferredSizeWidget {
const BackAppBar({
super.key,
});
@override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: AppColors.appBackground,
elevation: Constants.appBarElevation,
title: const Text(
'Back',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400
),
),
);
}
@override
Size get preferredSize => const Size.fromHeight(Constants.appBarHeight);
} | 0 |
mirrored_repositories/News-app-flutter-bloc/lib/ui | mirrored_repositories/News-app-flutter-bloc/lib/ui/pages/navbar_main_page.dart | import 'dart:developer';
import 'package:dispatcher/bloc/home/home_bloc.dart';
import 'package:dispatcher/repository/articles_repository.dart';
import 'package:dispatcher/ui/pages/favorites/favorites_page.dart';
import 'package:dispatcher/ui/pages/home/home_page.dart';
import 'package:dispatcher/ui/pages/profile/profile_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/navbar_main/navbar_main_bloc.dart';
import '../../constants/app_colors.dart';
import '../../enums/nav_bar_item.dart';
class NavbarMainPage extends StatelessWidget {
final PageController _pageController = PageController();
final _navbarPages = [
const HomePage(),
const FavoritePage(),
const ProfilePage()
];
final List<NavigationDestination> _navDestinations = [
NavigationDestination(
icon: Icon(NavbarItem.home.icon, color: AppColors.iconColor),
label: NavbarItem.home.title
),
NavigationDestination(
icon: Icon(NavbarItem.favorites.icon, color: AppColors.iconColor),
label: NavbarItem.favorites.title
),
NavigationDestination(
icon: Icon(NavbarItem.profile.icon, color: AppColors.iconColor),
label: NavbarItem.profile.title
),
];
NavbarMainPage({super.key});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => NavbarMainBloc(),
),
BlocProvider(
create: (context) =>
HomeBloc(
articleRepository: context.read<ArticlesRepository>()
),
),
],
child: _navBarMainView(),
);
}
Scaffold _navBarMainView() {
return Scaffold(
body: BlocListener<NavbarMainBloc, NavbarMainState>(
listener: (context, state) {
_pageController.jumpToPage(state.item.index);
},
child: PageView(
controller: _pageController,
onPageChanged: _onPageChanged,
physics: const NeverScrollableScrollPhysics(),
children: _navbarPages,
),
),
bottomNavigationBar: _bottomNavigationBarView(),
);
}
Widget _bottomNavigationBarView() {
return BlocBuilder<NavbarMainBloc, NavbarMainState>(
builder: (context, state) {
return NavigationBarTheme(
data: NavigationBarThemeData(
backgroundColor: AppColors.appBackground,
indicatorColor: Colors.amber[800],
),
child: NavigationBar(
height: 64,
destinations: _navDestinations,
labelBehavior: NavigationDestinationLabelBehavior.alwaysHide,
selectedIndex: state.item.index,
onDestinationSelected: (index) =>
context.read<NavbarMainBloc>().add(
NavbarItemPressed(NavbarItem.values.elementAt(index))),
),
);
},
);
}
void _onPageChanged(int value) {
log("_onPageChanged: page $value");
}
}
| 0 |
mirrored_repositories/News-app-flutter-bloc/lib/ui/pages | mirrored_repositories/News-app-flutter-bloc/lib/ui/pages/favorites/favorites_page.dart | import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import '../../../bloc/home/home_bloc.dart';
import '../../../constants/app_colors.dart';
import '../../../enums/nav_bar_item.dart';
import '../../widgets/favorite_article_card.dart';
import '../../widgets/app_bars/main_app_bar.dart';
class FavoritePage extends StatefulWidget {
const FavoritePage({super.key});
@override
State<StatefulWidget> createState() => FavoritePageState();
}
class FavoritePageState extends State<FavoritePage>
with AutomaticKeepAliveClientMixin {
final _scrollController = ScrollController();
FavoritePageState() {
log("FavoritePageState: init..");
}
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
backgroundColor: AppColors.surfaceBg,
appBar: MainAppBar(title: NavbarItem.favorites.title),
body: _favoritesArticlesView(),
);
}
Widget _favoritesArticlesView() {
return BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) {
log("favorite_page: state = $state");
if (state is HomeInitial) {
context.read<HomeBloc>().add(FetchArticles());
}
if (state is ArticlesLoaded) {
return ListView.separated(
padding: const EdgeInsets.all(16),
itemCount: state.articles.length,
itemBuilder: (context, position) {
return FavoriteArticleCard(article: state.articles[position]);
},
separatorBuilder: (BuildContext context, int index) {
return const SizedBox(height: 4);
},
controller: _scrollController
..addListener(() {
_onScroll(context);
}),
);
}
return const SpinKitWave(
color: AppColors.appBackground,
);
},
);
}
void _onScroll(BuildContext context) {
final fetchingTh = 0.95 * _scrollController.position.maxScrollExtent;
final currentScroll = _scrollController.position.pixels;
if (currentScroll >= fetchingTh) {
log("FavoritePage: End of scroll..");
context.read<HomeBloc>().add(FetchArticles());
}
}
@override
void dispose() {
super.dispose();
_scrollController.dispose();
}
@override
bool get wantKeepAlive => true;
}
| 0 |
mirrored_repositories/News-app-flutter-bloc/lib/ui/pages | mirrored_repositories/News-app-flutter-bloc/lib/ui/pages/profile/profile_page.dart | import 'package:flutter/material.dart';
import '../../../enums/nav_bar_item.dart';
import '../../widgets/app_bars/main_app_bar.dart';
class ProfilePage extends StatelessWidget {
const ProfilePage({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: MainAppBar(
title: NavbarItem.profile.title
),
body: Center(
child: Text(
NavbarItem.profile.title,
style: const TextStyle(fontSize: 72),
)),
);
} | 0 |
mirrored_repositories/News-app-flutter-bloc/lib/ui/pages | mirrored_repositories/News-app-flutter-bloc/lib/ui/pages/home/home_page.dart | import 'dart:developer';
import 'package:dispatcher/model/article.dart';
import 'package:dispatcher/repository/articles_repository.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../bloc/home/home_bloc.dart';
import '../../../constants/app_colors.dart';
import '../../../enums/nav_bar_item.dart';
import '../../widgets/article_card.dart';
import '../../widgets/app_bars/main_app_bar.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import '../article_details/article_detail_page.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<StatefulWidget> createState() => HomaPageState();
}
class HomaPageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
final _scrollController = ScrollController();
HomaPageState() {
log("HomaPageState: init..");
}
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
backgroundColor: AppColors.surfaceBg,
appBar: MainAppBar(
title: NavbarItem.home.title
),
body: _homeArticlesView(),
);
}
Widget _homeArticlesView() {
return BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) {
log("home_page: state = $state");
if (state is HomeInitial) {
context.read<HomeBloc>().add(FetchArticles());
}
else if (state is Loading) {
return const SpinKitWave(color: AppColors.appBackground,);
}
else if (state is ArticlesLoaded) {
log("home_page: ArticlesLoaded - ${state.articles.length} articles, isFetchingMore = ${state.isFetchingMore}");
return getLArticlesListView(state.articles, state.isFetchingMore, context);
}
return const Text("Something went wrong!");
},
);
}
Widget getLArticlesListView(List<Article> articles, bool isFetchingMore, BuildContext context) {
final itemCount = (isFetchingMore) ? articles.length+1 : articles.length;
return ListView.separated(
padding: const EdgeInsets.all(16),
itemCount: itemCount,
itemBuilder: (context, position) {
if (position >= articles.length) {
return const Center(
child: SizedBox(
height: 50,
width: 50,
child: CircularProgressIndicator(),
),
); }
return InkWell(
child: ArticleCard(article: articles[position]),
onTap: () {
log("getLArticlesListView: InkWell onTap()..");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ArticleDetailsPage(article: articles[position])
)
);
}
);
},
separatorBuilder: (BuildContext context, int index) {
return const SizedBox(height: 16);
},
controller: _scrollController
..addListener(() {_onScroll(context);}),
);
}
void _onScroll(BuildContext context) {
final fetchingTh = 0.9 * _scrollController.position.maxScrollExtent;
final currentScroll = _scrollController.position.pixels;
if (currentScroll >= fetchingTh ) {
context.read<HomeBloc>().add(FetchArticles());
}
}
@override
void dispose() {
super.dispose();
_scrollController.dispose();
}
@override
bool get wantKeepAlive => true;
}
| 0 |
mirrored_repositories/News-app-flutter-bloc/lib/ui/pages | mirrored_repositories/News-app-flutter-bloc/lib/ui/pages/article_details/article_detail_page.dart | import 'package:dispatcher/model/article.dart';
import 'package:dispatcher/ui/widgets/app_bars/back_app_bar.dart';
import 'package:flutter/material.dart';
class ArticleDetailsPage extends StatelessWidget {
static const separateHeight = 15.0;
final Article article;
const ArticleDetailsPage({super.key, required this.article});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const BackAppBar(),
body: _articleDetailsView(),
);
}
Widget _articleDetailsView() {
return Column(
children: [
_articleImageView(),
const SizedBox(height: 30),
Container(
padding: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(article.publishedAt.toString(),
style: _textStyleDateAndAuthor()),
const SizedBox(height: separateHeight),
Text(article.title,
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
)),
const SizedBox(height: separateHeight),
Text(article.author, style: _textStyleDateAndAuthor()),
const SizedBox(height: separateHeight),
Text(article.description,
style: const TextStyle(
fontSize: 16, fontWeight: FontWeight.w400)),
],
),
),
],
);
}
Widget _articleImageView() {
return Image.network(
article.imageUrl,
errorBuilder:
(BuildContext context, Object exception, StackTrace? stackTrace) {
return Image.asset(
'images/no_image.jpeg',
height: 150,
width: double.infinity,
);
},
height: 150,
width: double.infinity,
fit: BoxFit.fill,
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) {
return child;
}
return Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes!
: null,
),
);
},
);
}
TextStyle _textStyleDateAndAuthor() {
return TextStyle(
color: const Color(0xff5A5A89).withOpacity(0.7),
fontSize: 16,
fontWeight: FontWeight.w400);
}
}
| 0 |
mirrored_repositories/News-app-flutter-bloc | mirrored_repositories/News-app-flutter-bloc/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:dispatcher/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_bill | mirrored_repositories/flutter_bill/lib/main.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bill/bill/bill_list.dart';
Future<void> main() async {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new 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 press Run > Flutter Hot Reload in IntelliJ). Notice that the
// counter didn't reset back to zero; the application is not restarted.
primarySwatch: Colors.blue,
),
home: new BillListPage(title: '票据管理'),
);
}
}
| 0 |
mirrored_repositories/flutter_bill/lib | mirrored_repositories/flutter_bill/lib/view/picture_selector.dart | import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:image_picker/image_picker.dart';
//图片选择组件
class PictureSelector extends StatefulWidget {
final List<File> images;
final bool preview;
PictureSelector({this.images, this.preview = false});
@override
State<StatefulWidget> createState() {
return _PictureSelectorState();
}
String getSelectedImages() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < images.length; i++) {
if (images[0].path.isNotEmpty) {
buffer.write(images[i].path);
buffer.write(",");
}
}
if (buffer.isNotEmpty) {
return buffer.toString().substring(0, buffer.length - 1);
} else {
return null;
}
}
}
class _PictureSelectorState extends State<PictureSelector> {
@override
Widget build(BuildContext context) {
if (widget.images.isEmpty) {
widget.images.add(new File(""));
}
return new GridView.count(
//子布局需要的是准确的高度
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
padding: EdgeInsets.only(left: 15.0, right: 15.0),
crossAxisCount: 4,
crossAxisSpacing: 5.0,
mainAxisSpacing: 5.0,
children: _buildList(),
);
}
Widget _generateImage(File image) {
if (!widget.preview) {
//编辑模式
if (image.path.isEmpty) {
return new GestureDetector(
onTap: () {
_getImage();
},
child: new Center(
child: new Icon(Icons.add_circle_outline,
color: Theme.of(context).primaryColor),
));
} else {
return new GestureDetector(
onTap: () {},
child: Stack(
children: <Widget>[
ConstrainedBox(
constraints: BoxConstraints.expand(height: 130.0),
child: Padding(
padding: EdgeInsets.only(right: 10.0, top: 10.0),
child: new Image.file(
image,
fit: BoxFit.cover,
width: 5.0,
height: 5.0,
)),
),
new GestureDetector(
child: Align(
child: Icon(
Icons.remove_circle_outline,
color: Theme.of(context).primaryColor,
),
alignment: Alignment.topRight,
),
onTap: () {
setState(() {
widget.images.remove(image);
});
},
),
],
));
}
} else {
//预览模式
return new GestureDetector(
onTap: () {},
child: Stack(
children: <Widget>[
ConstrainedBox(
constraints: BoxConstraints.expand(height: 130.0),
child: Padding(
padding: EdgeInsets.only(right: 10.0, top: 10.0),
child: new Image.file(
image,
fit: BoxFit.cover,
width: 5.0,
height: 5.0,
)),
),
],
));
}
}
Future _getImage() async {
var pickImage = await ImagePicker.pickImage(source: ImageSource.gallery);
if (pickImage != null) {
setState(() {
widget.images.insert(widget.images.length - 1, pickImage);
});
}
}
List<Widget> _buildList() {
List<Widget> widgets = new List();
for (int i = 0; i < widget.images.length; i++) {
widgets.add(_generateImage(widget.images[i]));
}
return widgets;
}
}
| 0 |
mirrored_repositories/flutter_bill/lib | mirrored_repositories/flutter_bill/lib/generated/i18n.dart |
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
// ignore_for_file: non_constant_identifier_names
// ignore_for_file: camel_case_types
// ignore_for_file: prefer_single_quotes
//This file is automatically generated. DO NOT EDIT, all your changes would be lost.
class S implements WidgetsLocalizations {
const S();
static const GeneratedLocalizationsDelegate delegate =
const GeneratedLocalizationsDelegate();
static S of(BuildContext context) =>
Localizations.of<S>(context, WidgetsLocalizations);
@override
TextDirection get textDirection => TextDirection.ltr;
}
class en extends S {
const en();
}
class GeneratedLocalizationsDelegate extends LocalizationsDelegate<WidgetsLocalizations> {
const GeneratedLocalizationsDelegate();
List<Locale> get supportedLocales {
return const <Locale>[
const Locale("en", ""),
];
}
LocaleResolutionCallback resolution({Locale fallback}) {
return (Locale locale, Iterable<Locale> supported) {
final Locale languageLocale = new Locale(locale.languageCode, "");
if (supported.contains(locale))
return locale;
else if (supported.contains(languageLocale))
return languageLocale;
else {
final Locale fallbackLocale = fallback ?? supported.first;
return fallbackLocale;
}
};
}
@override
Future<WidgetsLocalizations> load(Locale locale) {
final String lang = getLang(locale);
switch (lang) {
case "en":
return new SynchronousFuture<WidgetsLocalizations>(const en());
default:
return new SynchronousFuture<WidgetsLocalizations>(const S());
}
}
@override
bool isSupported(Locale locale) => supportedLocales.contains(locale);
@override
bool shouldReload(GeneratedLocalizationsDelegate old) => false;
}
String getLang(Locale l) => l.countryCode != null && l.countryCode.isEmpty
? l.languageCode
: l.toString();
| 0 |
mirrored_repositories/flutter_bill/lib | mirrored_repositories/flutter_bill/lib/sql/category.dart | import 'dart:async';
import 'package:flutter_bill/sql/bill.dart';
import 'package:path/path.dart' show join;
import 'package:sqflite/sqflite.dart';
final String tableBillCategory = "Category";
final String columnId = "id";
final String columnTitle = "title";
class Category {
String categoryId;
String title;
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
columnTitle: title,
};
if (categoryId != null) {
map[columnId] = categoryId;
}
return map;
}
Category({this.title});
Category.fromMap(Map<String, dynamic> map) {
categoryId = map[columnId];
title = map[columnTitle];
}
}
class CategoryProvider {
Database db;
static Future createTable(Database db) async {
String sql = '''create table $tableBillCategory(
$columnId text primary key,
$columnTitle text not null)''';
await db.execute(sql);
}
Future open() async {
var databasesPath = await getDatabasesPath();
db = await openDatabase(
join(databasesPath, "db.db"),
version: 1,
onCreate: (Database db, int version) async {
BillProvider.createTable(db);
CategoryProvider.createTable(db);
},
);
}
Future<List<Category>> getCategories() async {
List<Map> rawQuery = await db.rawQuery("Select * from $tableBillCategory");
List<Category> list = new List();
rawQuery.forEach((Map map) {
var bill = Category.fromMap(map);
list.add(bill);
});
return list;
}
Future insert(Category category) async {
category.categoryId = DateTime.now().millisecond.toString();
return db.insert(tableBillCategory, category.toMap());
}
Future<Category> getCategory(String categoryId) async {
List<Map> map = await db.query(tableBillCategory,
columns: [columnId, columnTitle],
where: "$columnId = ?",
whereArgs: [categoryId]);
if (map.length > 0) {
return new Category.fromMap(map.first);
} else {
return null;
}
}
Future<int> delete(String categoryId) async {
return db.delete(tableBillCategory,
where: "$columnId = ?", whereArgs: [categoryId]);
}
Future<int> update(Category category) async {
return await db.update(tableBillCategory, category.toMap(),
where: "$columnId = ?", whereArgs: [category.categoryId]);
}
Future close() async => db.close();
}
| 0 |
mirrored_repositories/flutter_bill/lib | mirrored_repositories/flutter_bill/lib/sql/bill.dart | import 'dart:async';
import 'package:flutter_bill/sql/category.dart';
import 'package:path/path.dart' show join;
import 'package:sqflite/sqflite.dart';
final String tableBill = "Bill";
final String columnId = "id";
final String columnTitle = "title";
final String columnRemark = "remark";
final String columnCategory = "category";
final String columnContact = "contact";
final String columnPhone = "phone";
final String columnImages = "images";
class Bill {
String billId;
String title;
String remark;
String categoryId;
String categoryName;
String contact;
String phone;
String images;
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
columnTitle: title,
columnRemark: remark,
columnContact: contact,
columnPhone: phone,
columnImages: images,
columnCategory: categoryId,
};
if (billId != null) {
map[columnId] = billId;
}
return map;
}
Bill();
Bill.fromMap(Map<String, dynamic> map) {
billId = map[columnId];
title = map[columnTitle];
remark = map[columnRemark];
contact = map[columnContact];
phone = map[columnPhone];
images = map[columnImages];
categoryId = map[columnCategory];
}
}
class BillProvider {
Database db;
static Future createTable(Database db) async {
String sql = '''create table $tableBill(
$columnId text primary key,
$columnTitle text not null,
$columnRemark text,
$columnContact text,
$columnPhone text,
$columnCategory text,
$columnImages text not null)''';
await db.execute(sql);
}
Future open() async {
var databasesPath = await getDatabasesPath();
db = await openDatabase(
join(databasesPath, "db.db"),
version: 1,
onCreate: (Database db, int version) async {
BillProvider.createTable(db);
CategoryProvider.createTable(db);
},
);
}
Future<List<Bill>> getBills() async {
List<Map> rawQuery = await db.rawQuery("Select * from $tableBill");
List<Bill> list = new List();
rawQuery.forEach((Map map) {
var bill = Bill.fromMap(map);
list.add(bill);
});
return list;
}
Future<List<Bill>> getBillsWithLabel(String labelId) async {
List<Map> map = await db.query(tableBill,
distinct: false,
columns: [
columnImages,
columnCategory,
columnPhone,
columnContact,
columnRemark,
columnId,
columnTitle
],
where: "$columnCategory = ?",
whereArgs: [labelId]);
List<Bill> list = new List();
map.forEach((Map map) {
var bill = Bill.fromMap(map);
list.add(bill);
});
return list;
}
Future insert(Bill bill) async {
bill.billId = DateTime.now().millisecond.toString();
return db.insert(tableBill, bill.toMap());
}
Future<Bill> getBill(String billId) async {
List<Map> map = await db.query(tableBill,
columns: [
columnImages,
columnCategory,
columnPhone,
columnContact,
columnRemark,
columnId,
columnTitle
],
where: "$columnId = ?",
whereArgs: [billId]);
if (map.length > 0) {
return new Bill.fromMap(map.first);
} else {
return null;
}
}
Future<int> delete(String billId) async {
return db.delete(tableBill, where: "$columnId = ?", whereArgs: [billId]);
}
Future<int> deleteByLabel(String categoryId) async {
return db.delete(tableBill,
where: "$columnCategory= ?", whereArgs: [categoryId]);
}
Future<int> update(Bill bill) async {
return await db.update(tableBill, bill.toMap(),
where: "$columnId = ?", whereArgs: [bill.billId]);
}
Future close() async => db.close();
}
| 0 |
mirrored_repositories/flutter_bill/lib | mirrored_repositories/flutter_bill/lib/bill/detail_bill.dart | import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bill/bill/update_bill.dart';
import 'package:flutter_bill/sql/bill.dart';
import 'package:flutter_bill/sql/category.dart';
import 'package:flutter_bill/view/picture_selector.dart';
import 'package:sqflite/sqflite.dart';
class DetailBillPage extends StatefulWidget {
final String title;
final String billId;
DetailBillPage({Key key, this.title, this.billId}) : super(key: key);
@override
State<StatefulWidget> createState() {
return new _DetailBillPageState();
}
}
class _DetailBillPageState extends State<DetailBillPage> {
Bill _bill = new Bill();
var billProvider = BillProvider();
BuildContext context;
@override
void initState() {
super.initState();
getBillDetail();
}
@override
Widget build(BuildContext context) {
this.context = context;
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title ?? widget.title),
actions: <Widget>[
IconButton(
icon: Icon(Icons.mode_edit),
tooltip: "edit bill",
onPressed: _modifyBill,
),
IconButton(
icon: Icon(Icons.delete),
tooltip: "delete bill",
onPressed: _deleteBill,
)
],
),
body: new ListView(
children: <Widget>[
Container(
padding: const EdgeInsets.all(8.0),
margin: const EdgeInsets.only(bottom: 16.0),
child: new Row(
children: <Widget>[
Container(
padding: EdgeInsets.only(right: 15.0),
child: Text(_bill.title ?? "暂无")),
Container(
padding: EdgeInsets.only(left: 5.0, right: 5.0),
decoration: BoxDecoration(
border: Border.all(
width: 1.0, color: Theme.of(context).primaryColor),
borderRadius: BorderRadius.all(Radius.circular(5.0)),
),
child: Text(
_bill.categoryName ?? "其它",
style: TextStyle(color: Theme.of(context).primaryColor),
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new Row(
children: <Widget>[
Container(
child: Icon(Icons.event_note,
color: Theme.of(context).primaryColor),
padding: const EdgeInsets.only(right: 15.0),
),
Text(_bill.remark ?? "暂无")
],
),
),
Divider(
height: 1.0,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new Row(
children: <Widget>[
Container(
child: Icon(
Icons.perm_contact_calendar,
color: Theme.of(context).primaryColor,
),
padding: const EdgeInsets.only(right: 15.0),
),
Text(_bill.contact ?? "暂无")
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new Row(
children: <Widget>[
Container(
child:
Icon(Icons.phone, color: Theme.of(context).primaryColor),
padding: const EdgeInsets.only(right: 15.0),
),
Text(_bill.phone ?? "暂无")
],
),
),
Divider(
height: 1.0,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("票据文件"),
),
PictureSelector(
preview: true,
images: _bill.images.isEmpty
? new List()
: _bill.images.split(",").map((String image) {
return new File(image);
}).toList(),
),
],
),
);
}
// ignore: missing_return
void _deleteBill() {
print("delete bill");
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return new AlertDialog(
title: Text("删除票据"),
content: Text("确定删除票据,删除后数据将丢失!"),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: Text("取消")),
FlatButton(
onPressed: () =>
billProvider.delete(widget.billId).then((int) {
if (int > 0) Navigator.pop(context, true);
}).whenComplete(() {
Navigator.pop(context);
}),
child: Text("确定")),
],
);
});
}
void getBillDetail() async {
Sqflite.setDebugModeOn(true);
billProvider.open().then((db) {
return billProvider.getBill(widget.billId).then((Bill bill) {
var category = CategoryProvider();
category.open().then((db) {
return category
.getCategory(bill.categoryId)
.then((Category category) {
bill.categoryName = category.title;
setState(() {
setState(() {
_bill = bill;
});
});
});
});
setState(() {
_bill = bill;
});
});
});
}
void _modifyBill() async {
print("edit bill");
Bill result = await Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => EditBillPage(
title: "编辑票据",
bill: _bill,
)));
if (result != null) {
setState(() {
_bill = result;
});
}
}
}
| 0 |
mirrored_repositories/flutter_bill/lib | mirrored_repositories/flutter_bill/lib/bill/update_bill.dart | import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bill/bill/category/category_list.dart';
import 'package:flutter_bill/sql/bill.dart';
import 'package:flutter_bill/sql/category.dart';
import 'package:flutter_bill/view/picture_selector.dart';
import 'package:sqflite/sqflite.dart';
class EditBillPage extends StatefulWidget {
final String title;
final Bill bill;
EditBillPage({Key key, this.title, this.bill}) : super(key: key);
@override
State<StatefulWidget> createState() {
return new _EditBillPageState();
}
}
class _EditBillPageState extends State<EditBillPage> {
Category _selectedCategory;
CategoryProvider provider;
var titleEditController = TextEditingController();
var remarkController = TextEditingController();
var contactController = TextEditingController();
var phoneController = TextEditingController();
var pictureSelector = PictureSelector(
images: new List(),
);
var context;
var billProvider = BillProvider();
@override
void initState() {
super.initState();
if (widget.bill != null) {
titleEditController = TextEditingController(text: widget.bill.title);
remarkController = TextEditingController(text: widget.bill.remark);
contactController = TextEditingController(text: widget.bill.contact);
phoneController = TextEditingController(text: widget.bill.phone);
pictureSelector = PictureSelector(
images: widget.bill.images.split(",").map((String image) {
return new File(image);
}).toList(),
preview: false,
);
provider = CategoryProvider();
provider.open().then((db) {
provider.getCategory(widget.bill.categoryId).then((Category category) {
setState(() {
_selectedCategory = category;
});
});
});
}
_selectedCategory = Category();
initDb();
}
@override
Widget build(BuildContext context) {
this.context = context;
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(15.0),
child: GestureDetector(
onTap: _selectCategory,
child: new Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(child: Text("选择分类")),
Text(_selectedCategory.title ?? "请选择"),
Icon(Icons.keyboard_arrow_right)
],
),
),
),
Divider(),
Padding(
padding: const EdgeInsets.only(left: 15.0, right: 15.0),
child: TextField(
maxLengthEnforced: false,
maxLength: 50,
controller: titleEditController,
decoration: new InputDecoration(
labelText: "标题",
hintText: "输入标题",
),
),
),
Divider(),
Padding(
padding: const EdgeInsets.only(left: 15.0, right: 15.0),
child: TextField(
maxLengthEnforced: true,
maxLength: 500,
controller: remarkController,
decoration: new InputDecoration(
labelText: "备注",
hintText: "输入备注",
),
),
),
Divider(),
Padding(
padding: const EdgeInsets.only(left: 15.0, right: 15.0),
child: TextField(
maxLength: 15,
maxLengthEnforced: false, //是否显示错误信息
controller: contactController,
decoration:
new InputDecoration(labelText: "联系人", hintText: "输入联系人"),
),
),
Divider(),
Padding(
padding: const EdgeInsets.only(left: 15.0, right: 15.0),
child: TextField(
maxLength: 12,
controller: phoneController,
keyboardType: TextInputType.phone,
decoration: new InputDecoration(
labelText: "联系方式",
hintText: "输入联系方式",
),
),
),
Divider(),
Padding(
padding: const EdgeInsets.only(
top: 10.0, left: 15.0, right: 15.0, bottom: 10.0),
child: Text("票据文件"),
),
pictureSelector,
Container(
margin: EdgeInsets.all(15.0),
child:
RaisedButton(onPressed: _uploadBill, child: new Text("上传票据")),
),
],
),
);
}
void initDb() async {
Sqflite.setDebugModeOn(true);
await billProvider.open();
}
void _uploadBill() async {
if (widget.bill != null) {
widget.bill.title = titleEditController.text;
widget.bill.remark = remarkController.text;
widget.bill.contact = contactController.text;
widget.bill.phone = phoneController.text;
widget.bill.images = pictureSelector.getSelectedImages();
widget.bill.categoryId = _selectedCategory.categoryId;
widget.bill.categoryName = _selectedCategory.title;
var update = await billProvider.update(widget.bill);
if (update != null) {
print("修改票据成功~");
Navigator.pop(context, widget.bill);
}
} else {
var bill = new Bill();
bill.title = titleEditController.text;
bill.remark = remarkController.text;
bill.contact = contactController.text;
bill.phone = phoneController.text;
bill.images = pictureSelector.getSelectedImages();
bill.categoryId = _selectedCategory.categoryId;
var insert = await billProvider.insert(bill);
if (insert != null) {
print("上传票据成功~");
Navigator.pop(context, true);
}
}
}
void _selectCategory() async {
var result = await Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => CategoryListPage(
title: "选择分类",
)));
setState(() {
_selectedCategory = result ?? Category();
});
}
}
| 0 |
mirrored_repositories/flutter_bill/lib | mirrored_repositories/flutter_bill/lib/bill/bill_list.dart | import 'dart:io';
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bill/bill/detail_bill.dart';
import 'package:flutter_bill/bill/update_bill.dart';
import 'package:flutter_bill/sql/bill.dart';
import 'package:flutter_bill/sql/category.dart';
import 'package:sqflite/sqflite.dart';
class BillListPage extends StatefulWidget {
BillListPage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<BillListPage> {
List<Bill> mList = new List();
var _billProvider = BillProvider();
var _categoryProvider = CategoryProvider();
var path;
void _addBill() async {
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EditBillPage(
title: "添加票据",
)));
if (result != null) {
getList();
}
}
void initDb() async {
Sqflite.setDebugModeOn(true);
getList();
}
@override
void initState() {
super.initState();
initDb();
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return new Scaffold(
appBar: new AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: new Text(widget.title),
),
body: new RefreshIndicator(
onRefresh: () async {
mList.clear();
return getList();
},
child: new ListView.builder(
physics: AlwaysScrollableScrollPhysics(),
itemCount: max(1, mList.length),
itemBuilder: (BuildContext context, int index) {
if (mList.isNotEmpty) {
return generateItem(index);
} else {
return emptyView();
}
}),
),
floatingActionButton: new FloatingActionButton(
onPressed: _addBill,
tooltip: 'add bill',
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Widget generateItem(int index) {
return GestureDetector(
behavior: HitTestBehavior.translucent, //点击事件透传
onTap: () async {
var result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailBillPage(
title: "票据详情", billId: mList[index].billId)));
if (result ?? false) {
getList();
}
},
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.all(8.0),
child: new Column(
children: <Widget>[
new Row(
children: <Widget>[
Expanded(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
child: Text(mList[index].title),
padding: const EdgeInsets.only(bottom: 8.0),
),
Text(mList[index].categoryName)
],
),
),
Image.file(
File(mList[index]
.images
.substring(0, mList[index].images.indexOf(","))),
width: 40.0,
fit: BoxFit.cover,
height: 40.0,
)
],
),
],
)),
Divider()
],
),
);
}
void getList() async {
mList.clear();
_categoryProvider.open().then((db) {
_categoryProvider.getCategories().then((List<Category> categories) {
categories.map((Category category) {
_billProvider.open().then((db) {
_billProvider
.getBillsWithLabel(category.categoryId)
.then((List<Bill> data) {
setState(() {
mList.addAll(data.map((Bill bill) {
return bill..categoryName = category.title;
}).toList());
});
});
});
}).toList();
});
});
}
}
Widget emptyView() {
return new Container(
padding: const EdgeInsets.all(8.0),
child: Text("暂无数据"),
);
}
| 0 |
mirrored_repositories/flutter_bill/lib/bill | mirrored_repositories/flutter_bill/lib/bill/category/category_list.dart | import 'dart:async';
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bill/sql/bill.dart';
import 'package:flutter_bill/sql/category.dart';
import 'package:sqflite/sqflite.dart';
class CategoryListPage extends StatefulWidget {
CategoryListPage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_CategoryListPageState createState() => new _CategoryListPageState();
}
class _CategoryListPageState extends State<CategoryListPage> {
List<Category> mList = new List();
var _labelProvider = CategoryProvider();
var _billProvider = BillProvider();
var textEditingController = TextEditingController();
void _addCategory() async {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text("新增分类"),
content: TextField(
controller: textEditingController,
decoration: InputDecoration(hintText: "请输入分类名"),
),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: Text("取消")),
FlatButton(
onPressed: () async {
Navigator.pop(context);
await _labelProvider.insert(
new Category(title: textEditingController.text));
getList();
},
child: Text("确定"))
],
).build(context);
});
}
void initDb() async {
Sqflite.setDebugModeOn(true);
getList();
}
@override
void initState() {
super.initState();
initDb();
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return new Scaffold(
appBar: new AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: new Text(widget.title),
),
body: new RefreshIndicator(
onRefresh: () async {
mList.clear();
_labelProvider.open().then((db) {
_labelProvider.getCategories().then((List<Category> data) {
setState(() {
mList = data;
});
return data;
});
});
},
child: new ListView.builder(
physics: AlwaysScrollableScrollPhysics(),
itemCount: max(1, mList.length),
itemBuilder: (BuildContext context, int index) {
if (mList.isNotEmpty) {
return generateItem(index);
} else {
return emptyView();
}
}),
),
floatingActionButton: new FloatingActionButton(
onPressed: _addCategory,
tooltip: 'add category',
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Widget generateItem(int index) {
return GestureDetector(
behavior: HitTestBehavior.translucent, //点击事件透传
onTap: () async {
Navigator.pop(context, mList[index]);
},
child: Container(
padding: const EdgeInsets.only(left: 15.0, right: 15.0),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
new Expanded(child: Text(mList[index].title)),
IconButton(
icon: Icon(
Icons.edit,
color: Theme.of(context).primaryColor,
),
onPressed: () async {
await _showEditLabelDialog(index);
}),
IconButton(
icon: Icon(Icons.delete,
color: Theme.of(context).primaryColor),
onPressed: () async {
await _showDeleteLabelDialog(index);
},
)
],
),
new Divider(),
],
),
));
}
Future _showDeleteLabelDialog(int index) async {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return new AlertDialog(
title: Text("删除标签"),
content: Text("该标签下的所有票据数据将被删除,是否确认?"),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: Text("取消"),
),
FlatButton(
onPressed: () async {
await _deleteLabel(index);
},
child: Text("删除"),
)
],
);
});
}
Future _deleteLabel(int index) async {
Navigator.pop(context);
await _labelProvider.delete(mList[index].categoryId);
_billProvider.open().then((db) {
_billProvider.deleteByLabel(mList[index].categoryId);
});
getList();
}
Future _showEditLabelDialog(int index) async {
textEditingController.text = mList[index].title;
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text("修改分类"),
content: TextField(
controller: textEditingController,
decoration: InputDecoration(hintText: "请输入分类名"),
),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: Text("取消")),
FlatButton(
onPressed: () async {
await _editLabel(context, index);
},
child: Text("修改"))
],
).build(context);
});
}
Future _editLabel(BuildContext context, int index) async {
Navigator.pop(context);
await _labelProvider
.update(mList[index]..title = textEditingController.text);
getList();
}
void getList() async {
_labelProvider.open().then((db) {
_labelProvider.getCategories().then((List<Category> data) {
setState(() {
mList = data;
});
});
});
}
}
Widget emptyView() {
return new Container(
padding: const EdgeInsets.all(8.0),
child: Text("暂无数据"),
);
}
| 0 |
mirrored_repositories/flutter_bill | mirrored_repositories/flutter_bill/test/widget_test.dart | // This is a basic Flutter widget test.
// To perform an interaction with a widget in your test, use the WidgetTester utility that Flutter
// provides. For example, you can send tap and scroll gestures. You can also use WidgetTester to
// find child widgets in the widget tree, read text, and verify that the values of widget properties
// are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_bill/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(new 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/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/data/restaurant_data_store.dart | import 'package:restaurant_app/data/local/favorite_dao.dart';
import 'package:restaurant_app/data/model/favorite_entity.dart';
import 'package:restaurant_app/data/model/request/customer_review_request.dart';
import 'package:restaurant_app/data/model/response/customer_reviews_item.dart';
import 'package:restaurant_app/data/model/response/detail_restaurant_item.dart';
import 'package:restaurant_app/data/model/response/restaurant_item.dart';
import 'package:restaurant_app/data/remote/restaurant_api.dart';
import 'package:restaurant_app/data/restaurant_repository.dart';
import 'model/response/restaurant_response.dart';
class RestaurantDataSource extends RestaurantRepository {
final RestaurantApi _restaurantApi;
final FavoriteDao _favoriteDao;
RestaurantDataSource(this._restaurantApi, this._favoriteDao);
@override
Future<List<CustomerReviewsItem>> addCustomerReview(
CustomerReviewRequest customerReviewRequest,
) {
return _restaurantApi
.addCustomerReview('12345', customerReviewRequest)
.then((value) => value.customerReviews ?? List.empty());
}
@override
Future<DetailRestaurantItem> getDetailRestaurant(String id) {
return _restaurantApi
.getDetailRestaurant(id)
.then((value) => value.restaurant);
}
@override
Future<List<RestaurantItem>> getRestaurantData() {
return _restaurantApi
.getRestaurantData()
.then((value) => value.restaurants);
}
@override
Future<List<RestaurantItem>> searchRestaurants(String query) {
return _restaurantApi
.searchRestaurants(query)
.then((value) => value.restaurants);
}
@override
Future addToFavorite(FavoriteEntity favoriteEntity) {
return _favoriteDao.addToFavorite(favoriteEntity);
}
@override
Future checkFavoriteById(String id) {
return _favoriteDao.checkFavoriteById(id: id);
}
@override
Future deleteFavorite(String id) {
return _favoriteDao.deleteFavorite(id);
}
@override
Future getFavorites() {
return _favoriteDao.getFavorites();
}
@override
Future<RestaurantResponse> getRestaurantsNotification() {
return _restaurantApi.getRestaurantData().then((value) => value);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/data/restaurant_repository.dart | import 'package:restaurant_app/data/model/favorite_entity.dart';
import 'package:restaurant_app/data/model/request/customer_review_request.dart';
import 'package:restaurant_app/data/model/response/restaurant_item.dart';
import 'package:restaurant_app/data/model/response/restaurant_response.dart';
import 'model/response/customer_reviews_item.dart';
import 'model/response/detail_restaurant_item.dart';
abstract class RestaurantRepository {
Future<List<CustomerReviewsItem>> addCustomerReview(
CustomerReviewRequest customerReviewRequest,
);
Future<List<RestaurantItem>> getRestaurantData();
Future<DetailRestaurantItem> getDetailRestaurant(String id);
Future<List<RestaurantItem>> searchRestaurants(String query);
Future getFavorites();
Future<RestaurantResponse> getRestaurantsNotification();
Future addToFavorite(FavoriteEntity favoriteEntity);
Future deleteFavorite(String id);
Future checkFavoriteById(String id);
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data | mirrored_repositories/Restaurant-Flutter/lib/data/remote/restaurant_api_client.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'restaurant_api_client.dart';
// **************************************************************************
// RetrofitGenerator
// **************************************************************************
class _RestaurantApiClient implements RestaurantApiClient {
_RestaurantApiClient(this._dio, {this.baseUrl}) {
baseUrl ??= 'https://restaurant-api.dicoding.dev/';
}
final Dio _dio;
String? baseUrl;
@override
Future<AddCustomerReviewsResponse> addCustomerReview(
authToken, customerReviewRequest) async {
const _extra = <String, dynamic>{};
final queryParameters = <String, dynamic>{};
final _data = <String, dynamic>{};
_data.addAll(customerReviewRequest.toJson());
final _result = await _dio.fetch<Map<String, dynamic>>(
_setStreamType<AddCustomerReviewsResponse>(Options(
method: 'POST',
headers: <String, dynamic>{r'X-Auth-Token': authToken},
extra: _extra,
contentType: 'application/x-www-form-urlencoded')
.compose(_dio.options, 'review',
queryParameters: queryParameters, data: _data)
.copyWith(baseUrl: baseUrl ?? _dio.options.baseUrl)));
final value = AddCustomerReviewsResponse.fromJson(_result.data!);
return value;
}
@override
Future<RestaurantResponse> getRestaurantData() async {
const _extra = <String, dynamic>{};
final queryParameters = <String, dynamic>{};
final _data = <String, dynamic>{};
final _result = await _dio.fetch<Map<String, dynamic>>(
_setStreamType<RestaurantResponse>(
Options(method: 'GET', headers: <String, dynamic>{}, extra: _extra)
.compose(_dio.options, 'list',
queryParameters: queryParameters, data: _data)
.copyWith(baseUrl: baseUrl ?? _dio.options.baseUrl)));
final value = RestaurantResponse.fromJson(_result.data!);
return value;
}
@override
Future<DetailRestaurantResponse> getDetailRestaurant(id) async {
const _extra = <String, dynamic>{};
final queryParameters = <String, dynamic>{};
final _data = <String, dynamic>{};
final _result = await _dio.fetch<Map<String, dynamic>>(
_setStreamType<DetailRestaurantResponse>(
Options(method: 'GET', headers: <String, dynamic>{}, extra: _extra)
.compose(_dio.options, 'detail/$id',
queryParameters: queryParameters, data: _data)
.copyWith(baseUrl: baseUrl ?? _dio.options.baseUrl)));
final value = DetailRestaurantResponse.fromJson(_result.data!);
return value;
}
@override
Future<SearchRestaurantResponse> searchRestaurants(query) async {
const _extra = <String, dynamic>{};
final queryParameters = <String, dynamic>{r'q': query};
final _data = <String, dynamic>{};
final _result = await _dio.fetch<Map<String, dynamic>>(
_setStreamType<SearchRestaurantResponse>(
Options(method: 'GET', headers: <String, dynamic>{}, extra: _extra)
.compose(_dio.options, 'search',
queryParameters: queryParameters, data: _data)
.copyWith(baseUrl: baseUrl ?? _dio.options.baseUrl)));
final value = SearchRestaurantResponse.fromJson(_result.data!);
return value;
}
RequestOptions _setStreamType<T>(RequestOptions requestOptions) {
if (T != dynamic &&
!(requestOptions.responseType == ResponseType.bytes ||
requestOptions.responseType == ResponseType.stream)) {
if (T == String) {
requestOptions.responseType = ResponseType.plain;
} else {
requestOptions.responseType = ResponseType.json;
}
}
return requestOptions;
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data | mirrored_repositories/Restaurant-Flutter/lib/data/remote/restaurant_api_client.dart | import 'package:dio/dio.dart';
import 'package:restaurant_app/data/model/request/customer_review_request.dart';
import 'package:restaurant_app/data/model/response/add_customer_reviews_response.dart';
import 'package:restaurant_app/data/model/response/detail_restaurant_response.dart';
import 'package:restaurant_app/data/model/response/restaurant_response.dart';
import 'package:restaurant_app/data/model/response/search_restaurant_response.dart';
import 'package:restaurant_app/di/injector.dart';
import 'package:retrofit/retrofit.dart';
part 'restaurant_api_client.g.dart';
@RestApi(baseUrl: baseUrl)
abstract class RestaurantApiClient {
factory RestaurantApiClient(Dio dio, {String baseUrl}) = _RestaurantApiClient;
@POST('review')
@FormUrlEncoded()
Future<AddCustomerReviewsResponse> addCustomerReview(
@Header('X-Auth-Token') String authToken,
@Body() CustomerReviewRequest customerReviewRequest,
);
@GET('list')
Future<RestaurantResponse> getRestaurantData();
@GET('detail/{id}')
Future<DetailRestaurantResponse> getDetailRestaurant(
@Path('id') String id,
);
@GET('search')
Future<SearchRestaurantResponse> searchRestaurants(
@Query('q') String query,
);
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data | mirrored_repositories/Restaurant-Flutter/lib/data/remote/restaurant_api.dart | import 'package:restaurant_app/data/model/request/customer_review_request.dart';
import 'package:restaurant_app/data/model/response/add_customer_reviews_response.dart';
import 'package:restaurant_app/data/model/response/detail_restaurant_response.dart';
import 'package:restaurant_app/data/model/response/restaurant_response.dart';
import 'package:restaurant_app/data/model/response/search_restaurant_response.dart';
import 'package:restaurant_app/data/remote/restaurant_api_client.dart';
class RestaurantApi implements RestaurantApiClient {
final RestaurantApiClient _apiClient;
RestaurantApi(this._apiClient);
@override
Future<AddCustomerReviewsResponse> addCustomerReview(
String authToken, CustomerReviewRequest customerReviewRequest) {
return _apiClient.addCustomerReview(authToken, customerReviewRequest);
}
@override
Future<DetailRestaurantResponse> getDetailRestaurant(String id) {
return _apiClient.getDetailRestaurant(id);
}
@override
Future<RestaurantResponse> getRestaurantData() {
return _apiClient.getRestaurantData();
}
@override
Future<SearchRestaurantResponse> searchRestaurants(String query) {
return _apiClient.searchRestaurants(query);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data | mirrored_repositories/Restaurant-Flutter/lib/data/database/database_provider.dart | import 'package:sqflite/sqflite.dart';
final favoriteTable = 'favorite';
class DatabaseHelper {
static DatabaseHelper? _instance;
static Database? _database;
DatabaseHelper._internal() {
_instance = this;
}
factory DatabaseHelper() => _instance ?? DatabaseHelper._internal();
Future<Database> _initializeDb() async {
var path = await getDatabasesPath();
var db = openDatabase(
'$path/restaurant.db',
onCreate: (db, version) async {
await db.execute("CREATE TABLE $favoriteTable ("
"id TEXT PRIMARY KEY,"
"name TEXT, "
"description TEXT, "
"image TEXT, "
"city TEXT, "
"rating TEXT "
")");
},
version: 1,
);
return db;
}
Future<Database?> get database async {
if (_database == null) {
_database = await _initializeDb();
}
return _database;
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data | mirrored_repositories/Restaurant-Flutter/lib/data/model/favorite_entity.dart | class FavoriteEntity {
String? id, name, description, image, city, rating;
FavoriteEntity({
required this.id,
required this.name,
required this.description,
required this.image,
required this.city,
required this.rating,
});
factory FavoriteEntity.fromDatabaseJson(Map<String, dynamic> data) =>
FavoriteEntity(
id: data['id'] ?? 0,
name: data['name'] ?? '',
description: data['description'] ?? '',
image: data['image'] ?? '',
city: data['city'] ?? '',
rating: data['rating'] ?? '',
);
Map<String, dynamic> toDatabaseJson() {
var map = {
"id": this.id,
"name": this.name,
"description": this.description,
"image": this.image,
"city": this.city,
"rating": this.rating
};
if (map['id'] != null) map['id'] = this.id ?? '';
return map;
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/restaurant_response.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'restaurant_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
RestaurantResponse _$RestaurantResponseFromJson(Map<String, dynamic> json) {
return RestaurantResponse(
error: json['error'] as bool?,
message: json['message'] as String?,
count: json['count'] as int?,
restaurants: (json['restaurants'] as List<dynamic>)
.map((e) => RestaurantItem.fromJson(e as Map<String, dynamic>))
.toList(),
);
}
Map<String, dynamic> _$RestaurantResponseToJson(RestaurantResponse instance) =>
<String, dynamic>{
'error': instance.error,
'message': instance.message,
'count': instance.count,
'restaurants': instance.restaurants,
};
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/menu_response.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'menu_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
MenuResponse _$MenuResponseFromJson(Map<String, dynamic> json) {
return MenuResponse(
foods: (json['foods'] as List<dynamic>?)
?.map((e) => SharedNameItem.fromJson(e as Map<String, dynamic>))
.toList(),
drinks: (json['drinks'] as List<dynamic>?)
?.map((e) => SharedNameItem.fromJson(e as Map<String, dynamic>))
.toList(),
);
}
Map<String, dynamic> _$MenuResponseToJson(MenuResponse instance) =>
<String, dynamic>{
'foods': instance.foods,
'drinks': instance.drinks,
};
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/detail_restaurant_item.dart | import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:restaurant_app/data/model/response/customer_reviews_item.dart';
import 'package:restaurant_app/data/model/response/shared_name_item.dart';
import 'package:restaurant_app/data/model/response/menu_response.dart';
part 'detail_restaurant_item.g.dart';
@JsonSerializable()
class DetailRestaurantItem extends Equatable {
@JsonKey(name: 'id')
final String? id;
@JsonKey(name: 'name')
final String? name;
@JsonKey(name: 'description')
final String? description;
@JsonKey(name: 'pictureId')
final String? pictureId;
@JsonKey(name: 'city')
final String? city;
@JsonKey(name: 'address')
final String? address;
@JsonKey(name: 'categories')
final List<SharedNameItem>? categories;
@JsonKey(name: 'customerReviews')
final List<CustomerReviewsItem>? customerReviews;
@JsonKey(name: 'rating')
final double? rating;
@JsonKey(name: 'menus')
final MenuResponse menuResponse;
DetailRestaurantItem(
{this.id,
this.name,
this.description,
this.pictureId,
this.city,
this.address,
this.rating,
required this.menuResponse,
this.categories,
this.customerReviews});
@override
List<Object?> get props => [
id,
name,
description,
pictureId,
city,
address,
rating,
menuResponse,
categories,
customerReviews,
];
factory DetailRestaurantItem.fromJson(Map<String, dynamic> json) =>
_$DetailRestaurantItemFromJson(json);
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/restaurant_item.dart | import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
part 'restaurant_item.g.dart';
@JsonSerializable()
class RestaurantItem extends Equatable {
@JsonKey(name: 'id')
final String? id;
@JsonKey(name: 'name')
final String? name;
@JsonKey(name: 'description')
final String? description;
@JsonKey(name: 'pictureId')
final String? pictureId;
@JsonKey(name: 'city')
final String? city;
@JsonKey(name: 'rating')
final double? rating;
RestaurantItem({
this.id,
this.name,
this.description,
this.pictureId,
this.city,
this.rating,
});
@override
List<Object?> get props => [
id,
name,
description,
pictureId,
city,
rating,
];
factory RestaurantItem.fromJson(Map<String, dynamic> json) =>
_$RestaurantItemFromJson(json);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"description": description,
"pictureId": pictureId,
"city": city,
"rating": rating
};
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/shared_name_item.dart | import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
part 'shared_name_item.g.dart';
@JsonSerializable()
class SharedNameItem extends Equatable {
@JsonKey(name: 'name')
final String name;
SharedNameItem({required this.name});
@override
List<Object?> get props => [name];
factory SharedNameItem.fromJson(Map<String, dynamic> json) =>
_$SharedNameItemFromJson(json);
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/customer_reviews_item.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'customer_reviews_item.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
CustomerReviewsItem _$CustomerReviewsItemFromJson(Map<String, dynamic> json) {
return CustomerReviewsItem(
name: json['name'] as String?,
review: json['review'] as String?,
date: json['date'] as String?,
);
}
Map<String, dynamic> _$CustomerReviewsItemToJson(
CustomerReviewsItem instance) =>
<String, dynamic>{
'name': instance.name,
'review': instance.review,
'date': instance.date,
};
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/menu_response.dart | import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:restaurant_app/data/model/response/shared_name_item.dart';
part 'menu_response.g.dart';
@JsonSerializable()
class MenuResponse extends Equatable {
@JsonKey(name: 'foods')
final List<SharedNameItem>? foods;
@JsonKey(name: 'drinks')
final List<SharedNameItem>? drinks;
MenuResponse({required this.foods, required this.drinks});
@override
List<Object?> get props => [foods, drinks];
factory MenuResponse.fromJson(Map<String, dynamic> json) =>
_$MenuResponseFromJson(json);
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/restaurant_item.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'restaurant_item.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
RestaurantItem _$RestaurantItemFromJson(Map<String, dynamic> json) {
return RestaurantItem(
id: json['id'] as String?,
name: json['name'] as String?,
description: json['description'] as String?,
pictureId: json['pictureId'] as String?,
city: json['city'] as String?,
rating: (json['rating'] as num?)?.toDouble(),
);
}
Map<String, dynamic> _$RestaurantItemToJson(RestaurantItem instance) =>
<String, dynamic>{
'id': instance.id,
'name': instance.name,
'description': instance.description,
'pictureId': instance.pictureId,
'city': instance.city,
'rating': instance.rating,
};
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/restaurant_response.dart | import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:restaurant_app/data/model/response/restaurant_item.dart';
part 'restaurant_response.g.dart';
@JsonSerializable()
class RestaurantResponse extends Equatable {
@JsonKey(name: 'error')
final bool? error;
@JsonKey(name: 'message')
final String? message;
@JsonKey(name: 'count')
final int? count;
@JsonKey(name: 'restaurants')
final List<RestaurantItem> restaurants;
RestaurantResponse({
this.error,
this.message,
this.count,
required this.restaurants,
});
@override
List<Object?> get props => [
error,
message,
count,
restaurants,
];
factory RestaurantResponse.fromJson(Map<String, dynamic> json) =>
_$RestaurantResponseFromJson(json);
Map<String, dynamic> toJson() => {
"error": error,
"message": message,
"count": count,
"restaurants": List<dynamic>.from(restaurants.map((x) => x.toJson())),
};
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/detail_restaurant_response.dart | import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:restaurant_app/data/model/response/detail_restaurant_item.dart';
part 'detail_restaurant_response.g.dart';
@JsonSerializable()
class DetailRestaurantResponse extends Equatable {
@JsonKey(name: 'error')
final bool? error;
@JsonKey(name: 'message')
final String? message;
@JsonKey(name: 'restaurant')
final DetailRestaurantItem restaurant;
DetailRestaurantResponse({
this.error,
this.message,
required this.restaurant,
});
@override
List<Object?> get props => [
error,
message,
restaurant,
];
factory DetailRestaurantResponse.fromJson(Map<String, dynamic> json) =>
_$DetailRestaurantResponseFromJson(json);
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/detail_restaurant_item.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'detail_restaurant_item.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
DetailRestaurantItem _$DetailRestaurantItemFromJson(Map<String, dynamic> json) {
return DetailRestaurantItem(
id: json['id'] as String?,
name: json['name'] as String?,
description: json['description'] as String?,
pictureId: json['pictureId'] as String?,
city: json['city'] as String?,
address: json['address'] as String?,
rating: (json['rating'] as num?)?.toDouble(),
menuResponse: MenuResponse.fromJson(json['menus'] as Map<String, dynamic>),
categories: (json['categories'] as List<dynamic>?)
?.map((e) => SharedNameItem.fromJson(e as Map<String, dynamic>))
.toList(),
customerReviews: (json['customerReviews'] as List<dynamic>?)
?.map((e) => CustomerReviewsItem.fromJson(e as Map<String, dynamic>))
.toList(),
);
}
Map<String, dynamic> _$DetailRestaurantItemToJson(
DetailRestaurantItem instance) =>
<String, dynamic>{
'id': instance.id,
'name': instance.name,
'description': instance.description,
'pictureId': instance.pictureId,
'city': instance.city,
'address': instance.address,
'categories': instance.categories,
'customerReviews': instance.customerReviews,
'rating': instance.rating,
'menus': instance.menuResponse,
};
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/search_restaurant_response.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'search_restaurant_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
SearchRestaurantResponse _$SearchRestaurantResponseFromJson(
Map<String, dynamic> json) {
return SearchRestaurantResponse(
error: json['error'] as bool?,
founded: json['founded'] as int?,
restaurants: (json['restaurants'] as List<dynamic>)
.map((e) => RestaurantItem.fromJson(e as Map<String, dynamic>))
.toList(),
);
}
Map<String, dynamic> _$SearchRestaurantResponseToJson(
SearchRestaurantResponse instance) =>
<String, dynamic>{
'error': instance.error,
'founded': instance.founded,
'restaurants': instance.restaurants,
};
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/search_restaurant_response.dart | import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:restaurant_app/data/model/response/restaurant_item.dart';
part 'search_restaurant_response.g.dart';
@JsonSerializable()
class SearchRestaurantResponse extends Equatable {
@JsonKey(name: 'error')
final bool? error;
@JsonKey(name: 'founded')
final int? founded;
@JsonKey(name: 'restaurants')
final List<RestaurantItem> restaurants;
SearchRestaurantResponse({
this.error,
this.founded,
required this.restaurants,
});
@override
List<Object?> get props => [
error,
founded,
restaurants,
];
factory SearchRestaurantResponse.fromJson(Map<String, dynamic> json) =>
_$SearchRestaurantResponseFromJson(json);
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/add_customer_reviews_response.dart | import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'customer_reviews_item.dart';
part 'add_customer_reviews_response.g.dart';
@JsonSerializable()
class AddCustomerReviewsResponse extends Equatable {
@JsonKey(name: 'error')
final bool? error;
@JsonKey(name: 'message')
final String? message;
@JsonKey(name: 'customerReviews')
final List<CustomerReviewsItem>? customerReviews;
AddCustomerReviewsResponse({
this.error,
this.message,
this.customerReviews,
});
@override
List<Object?> get props => [
error,
message,
customerReviews,
];
factory AddCustomerReviewsResponse.fromJson(Map<String, dynamic> json) =>
_$AddCustomerReviewsResponseFromJson(json);
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/add_customer_reviews_response.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'add_customer_reviews_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
AddCustomerReviewsResponse _$AddCustomerReviewsResponseFromJson(
Map<String, dynamic> json) {
return AddCustomerReviewsResponse(
error: json['error'] as bool?,
message: json['message'] as String?,
customerReviews: (json['customerReviews'] as List<dynamic>?)
?.map((e) => CustomerReviewsItem.fromJson(e as Map<String, dynamic>))
.toList(),
);
}
Map<String, dynamic> _$AddCustomerReviewsResponseToJson(
AddCustomerReviewsResponse instance) =>
<String, dynamic>{
'error': instance.error,
'message': instance.message,
'customerReviews': instance.customerReviews,
};
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/customer_reviews_item.dart | import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
part 'customer_reviews_item.g.dart';
@JsonSerializable()
class CustomerReviewsItem extends Equatable {
@JsonKey(name: 'name')
final String? name;
@JsonKey(name: 'review')
final String? review;
@JsonKey(name: 'date')
final String? date;
CustomerReviewsItem({this.name, this.review, this.date});
@override
List<Object?> get props => [
name,
review,
date,
];
factory CustomerReviewsItem.fromJson(Map<String, dynamic> json) =>
_$CustomerReviewsItemFromJson(json);
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/detail_restaurant_response.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'detail_restaurant_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
DetailRestaurantResponse _$DetailRestaurantResponseFromJson(
Map<String, dynamic> json) {
return DetailRestaurantResponse(
error: json['error'] as bool?,
message: json['message'] as String?,
restaurant: DetailRestaurantItem.fromJson(
json['restaurant'] as Map<String, dynamic>),
);
}
Map<String, dynamic> _$DetailRestaurantResponseToJson(
DetailRestaurantResponse instance) =>
<String, dynamic>{
'error': instance.error,
'message': instance.message,
'restaurant': instance.restaurant,
};
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/response/shared_name_item.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'shared_name_item.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
SharedNameItem _$SharedNameItemFromJson(Map<String, dynamic> json) {
return SharedNameItem(
name: json['name'] as String,
);
}
Map<String, dynamic> _$SharedNameItemToJson(SharedNameItem instance) =>
<String, dynamic>{
'name': instance.name,
};
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/request/customer_review_request.dart | import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
part 'customer_review_request.g.dart';
@JsonSerializable()
class CustomerReviewRequest extends Equatable {
@JsonKey(name: 'name')
final String name;
@JsonKey(name: 'review')
final String review;
@JsonKey(name: 'id')
final String id;
CustomerReviewRequest({
required this.name,
required this.review,
required this.id,
});
@override
List<Object?> get props => [
name,
review,
id,
];
factory CustomerReviewRequest.fromJson(Map<String, dynamic> json) =>
_$CustomerReviewRequestFromJson(json);
Map<String, dynamic> toJson() => _$CustomerReviewRequestToJson(this);
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data/model | mirrored_repositories/Restaurant-Flutter/lib/data/model/request/customer_review_request.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'customer_review_request.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
CustomerReviewRequest _$CustomerReviewRequestFromJson(
Map<String, dynamic> json) {
return CustomerReviewRequest(
name: json['name'] as String,
review: json['review'] as String,
id: json['id'] as String,
);
}
Map<String, dynamic> _$CustomerReviewRequestToJson(
CustomerReviewRequest instance) =>
<String, dynamic>{
'name': instance.name,
'review': instance.review,
'id': instance.id,
};
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/data | mirrored_repositories/Restaurant-Flutter/lib/data/local/favorite_dao.dart | import 'package:restaurant_app/data/database/database_provider.dart';
import 'package:restaurant_app/data/model/favorite_entity.dart';
class FavoriteDao {
final dbProvider = DatabaseHelper();
Future<int> addToFavorite(FavoriteEntity favoriteEntity) async {
final db = await dbProvider.database;
var result = db!.insert(favoriteTable, favoriteEntity.toDatabaseJson());
return result;
}
Future<List<FavoriteEntity>> getFavorites({String? query}) async {
final db = await dbProvider.database;
late List<Map<String, dynamic>> result;
if (query != null && query != '') {
if (query.isNotEmpty)
result = await db!.query(favoriteTable,
where: 'name LIKE ?', whereArgs: ["%$query%"]);
} else {
result = await db!.query(favoriteTable, orderBy: 'id DESC');
}
List<FavoriteEntity> favorites = result.isNotEmpty
? result.map((item) => FavoriteEntity.fromDatabaseJson(item)).toList()
: [];
return favorites;
}
Future<int> deleteFavorite(String id) async {
final db = await dbProvider.database;
var result = db!.delete(favoriteTable, where: 'id = ?', whereArgs: [id]);
return result;
}
Future<FavoriteEntity> checkFavoriteById({required String id}) async {
final db = await dbProvider.database;
var result =
await db!.query(favoriteTable, where: 'id = ?', whereArgs: [id]);
List<FavoriteEntity> favorite = result.isNotEmpty
? result.map((data) => FavoriteEntity.fromDatabaseJson(data)).toList()
: [];
FavoriteEntity favoriteEntity = favorite[0];
return favoriteEntity;
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/bloc/bloc_observer.dart | import 'package:flutter_bloc/flutter_bloc.dart';
class BlocObserverApp extends BlocObserver {
@override
void onEvent(Bloc bloc, Object? event) {
print(event);
super.onEvent(bloc, event);
}
@override
void onTransition(Bloc bloc, Transition transition) {
print(transition);
super.onTransition(bloc, transition);
}
@override
void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
print(error);
super.onError(bloc, error, stackTrace);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/restaurant_state.dart | import 'package:equatable/equatable.dart';
import 'package:restaurant_app/bloc/restaurant/model/detail_restaurant.dart';
import 'package:restaurant_app/bloc/restaurant/model/restaurant.dart';
part 'state/add_customer_review_state.dart';
part 'state/add_to_favorite_state.dart';
part 'state/check_favorite_state.dart';
part 'state/delete_favorite_state.dart';
part 'state/fetch_favorites_state.dart';
part 'state/fetch_restaurant_detail_state.dart';
part 'state/fetch_restaurants_state.dart';
part 'state/search_restaurant_state.dart';
abstract class RestaurantState extends Equatable {
const RestaurantState() : super();
}
class RestaurantInitialState extends RestaurantState {
const RestaurantInitialState() : super();
@override
List<Object?> get props => [];
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/restaurant_event.dart | import 'package:equatable/equatable.dart';
import 'package:restaurant_app/data/model/request/customer_review_request.dart';
import 'model/restaurant.dart';
abstract class RestaurantEvent extends Equatable {
const RestaurantEvent();
}
class AddedCustomerReviewsEvent extends RestaurantEvent {
final CustomerReviewRequest customerReviewRequest;
const AddedCustomerReviewsEvent({
required this.customerReviewRequest,
});
@override
List<Object?> get props => [customerReviewRequest];
}
class FetchedRestaurantsEvent extends RestaurantEvent {
const FetchedRestaurantsEvent();
@override
List<Object?> get props => [];
}
class FetchedRestaurantDetailEvent extends RestaurantEvent {
final String id;
const FetchedRestaurantDetailEvent({required this.id});
@override
List<Object?> get props => [id];
}
class SearchRestaurantEvent extends RestaurantEvent {
final String query;
const SearchRestaurantEvent({required this.query});
@override
List<Object?> get props => [query];
}
class AddToFavoriteEvent extends RestaurantEvent {
final Restaurant restaurant;
const AddToFavoriteEvent({required this.restaurant});
@override
List<Object?> get props => [restaurant];
}
class FetchedFavoritesEvent extends RestaurantEvent {
const FetchedFavoritesEvent();
@override
List<Object?> get props => [];
}
class CheckFavoriteEvent extends RestaurantEvent {
final String id;
const CheckFavoriteEvent({required this.id});
@override
List<Object?> get props => [id];
}
class DeleteFavoriteEvent extends RestaurantEvent {
final String id;
const DeleteFavoriteEvent({required this.id});
@override
List<Object?> get props => [id];
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/restaurant.dart | export './restaurant_bloc.dart';
export './restaurant_event.dart';
export './restaurant_state.dart'; | 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/restaurant_bloc.dart | import 'package:dio/dio.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:restaurant_app/bloc/restaurant/restaurant.dart';
import 'package:restaurant_app/data/model/favorite_entity.dart';
import 'package:restaurant_app/data/restaurant_repository.dart';
import 'package:restaurant_app/utils/error_handler.dart';
import 'mapper/restaurant_mapper.dart';
import 'model/detail_restaurant.dart';
import 'model/restaurant.dart';
class RestaurantBloc extends Bloc<RestaurantEvent, RestaurantState> {
final RestaurantRepository _restaurantRepository;
RestaurantBloc(this._restaurantRepository) : super(RestaurantInitialState());
@override
Stream<RestaurantState> mapEventToState(RestaurantEvent event) async* {
if (event is FetchedRestaurantsEvent) {
yield* _mapRestaurantsEventToState(event);
} else if (event is FetchedRestaurantDetailEvent) {
yield* _mapRestaurantDetailEventToState(event);
} else if (event is AddedCustomerReviewsEvent) {
yield* _mapAddCustomerReviewEventToState(event);
} else if (event is SearchRestaurantEvent) {
yield* _mapSearchRestaurantEventToState(event);
} else if (event is FetchedFavoritesEvent) {
yield* _mapFetchFavoriteEventToState(event);
} else if (event is AddToFavoriteEvent) {
yield* _mapAddToFavoriteEventToState(event);
} else if (event is DeleteFavoriteEvent) {
yield* _mapDeleteFavoriteEventToState(event);
} else if (event is CheckFavoriteEvent) {
yield* _mapCheckFavoriteEventToState(event);
}
}
Stream<RestaurantState> _mapAddCustomerReviewEventToState(
AddedCustomerReviewsEvent event) async* {
yield AddCustomerReviewLoadingState();
try {
await _restaurantRepository
.addCustomerReview(event.customerReviewRequest);
yield AddCustomerReviewSuccessState();
} on DioError catch (error) {
var errorMessage = handleError(error);
print(errorMessage);
yield AddCustomerReviewErrorState(errorMessage);
} on Error {
yield AddCustomerReviewErrorState("Unknown Error");
}
}
Stream<RestaurantState> _mapRestaurantsEventToState(
FetchedRestaurantsEvent event) async* {
yield FetchRestaurantsLoadingState();
try {
var restaurantsItem = await _restaurantRepository.getRestaurantData();
List<Restaurant> restaurants =
restaurantsItem.map((item) => mapRestaurants(item)).toList();
yield FetchRestaurantsSuccessState(restaurants);
} on DioError catch (error) {
var errorMessage = handleError(error);
print(errorMessage);
yield FetchRestaurantsErrorState(errorMessage);
} on Error {
yield FetchRestaurantsErrorState("Unknown Error");
}
}
Stream<RestaurantState> _mapRestaurantDetailEventToState(
FetchedRestaurantDetailEvent event) async* {
yield FetchRestaurantDetailLoadingState();
try {
var detailRestaurantItem =
await _restaurantRepository.getDetailRestaurant(event.id);
DetailRestaurant detailRestaurant =
mapRestaurantDetail(detailRestaurantItem);
yield FetchRestaurantDetailSuccessState(detailRestaurant);
} on DioError catch (error) {
var errorMessage = handleError(error);
print(errorMessage);
yield FetchRestaurantDetailErrorState(errorMessage);
} on Error {
yield FetchRestaurantDetailErrorState("Unknown Error");
}
}
Stream<RestaurantState> _mapSearchRestaurantEventToState(
SearchRestaurantEvent event) async* {
yield SearchRestaurantLoadingState();
try {
var restaurantsItem =
await _restaurantRepository.searchRestaurants(event.query);
List<Restaurant> restaurants =
restaurantsItem.map((item) => mapRestaurants(item)).toList();
if (restaurants.isNotEmpty) {
yield SearchRestaurantSuccessState(restaurants);
} else {
yield SearchRestaurantEmptyState('Data tidak ditemukan');
}
} on DioError catch (error) {
var errorMessage = handleError(error);
print(errorMessage);
yield SearchRestaurantErrorState(errorMessage);
} on Error {
yield SearchRestaurantErrorState("Unknown Error");
}
}
Stream<RestaurantState> _mapAddToFavoriteEventToState(
AddToFavoriteEvent event) async* {
yield AddToFavoriteLoadingState();
try {
await _restaurantRepository
.addToFavorite(mapFavoriteEntity(event.restaurant));
yield AddToFavoriteSuccessState(true);
} catch (e) {
yield AddToFavoriteErrorState(e.toString());
}
}
Stream<RestaurantState> _mapDeleteFavoriteEventToState(
DeleteFavoriteEvent event) async* {
yield DeleteFavoriteLoadingState();
try {
await _restaurantRepository.deleteFavorite(event.id);
yield DeleteFavoriteSuccessState(false);
} catch (e) {
yield DeleteFavoriteErrorState(e.toString());
}
}
Stream<RestaurantState> _mapCheckFavoriteEventToState(
CheckFavoriteEvent event) async* {
yield CheckFavoriteLoadingState();
try {
await _restaurantRepository.checkFavoriteById(event.id);
yield FavoredState(isFavorite: true);
} catch (e) {
yield UnfavorableState(e.toString(), false);
}
}
Stream<RestaurantState> _mapFetchFavoriteEventToState(
FetchedFavoritesEvent event) async* {
yield FetchFavoritesLoadingState();
try {
List<FavoriteEntity> favorites =
await _restaurantRepository.getFavorites();
if (favorites.isEmpty) {
yield FetchFavoritesEmptyState("Favorites Not Found");
} else {
yield FetchFavoritesSuccessState(
favorites.map((e) => mapFavoriteToItem(e)).toList());
}
} catch (e) {
yield FetchFavoritesErrorState(e.toString());
}
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/mapper/restaurant_mapper.dart | import 'package:restaurant_app/bloc/restaurant/model/customer_reviews.dart';
import 'package:restaurant_app/bloc/restaurant/model/detail_restaurant.dart';
import 'package:restaurant_app/bloc/restaurant/model/menu.dart';
import 'package:restaurant_app/bloc/restaurant/model/restaurant.dart';
import 'package:restaurant_app/bloc/restaurant/model/shared_name.dart';
import 'package:restaurant_app/data/model/favorite_entity.dart';
import 'package:restaurant_app/data/model/response/customer_reviews_item.dart';
import 'package:restaurant_app/data/model/response/detail_restaurant_item.dart';
import 'package:restaurant_app/data/model/response/menu_response.dart';
import 'package:restaurant_app/data/model/response/restaurant_item.dart';
import 'package:restaurant_app/data/model/response/shared_name_item.dart';
Restaurant mapRestaurants(RestaurantItem restaurantItem) {
return Restaurant(
id: restaurantItem.id ?? '',
city: restaurantItem.city ?? '',
pictureId: restaurantItem.pictureId ?? '',
rating: restaurantItem.rating ?? 0.0,
name: restaurantItem.name ?? '',
description: restaurantItem.description ?? '',
);
}
DetailRestaurant mapRestaurantDetail(
DetailRestaurantItem detailRestaurantItem) {
return DetailRestaurant(
description: detailRestaurantItem.description ?? '',
name: detailRestaurantItem.name ?? '',
categories: detailRestaurantItem.categories
?.map((e) => mapSharedName(e))
.toList() ??
List.empty(),
city: detailRestaurantItem.city ?? '',
address: detailRestaurantItem.address ?? '',
id: detailRestaurantItem.id ?? '',
pictureId: detailRestaurantItem.pictureId ?? '',
customerReviews: detailRestaurantItem.customerReviews
?.map((e) => mapCustomerReviews(e))
.toList() ??
List.empty(),
menu: mapMenuResponse(detailRestaurantItem.menuResponse),
rating: detailRestaurantItem.rating ?? 0.0,
);
}
Menu mapMenuResponse(MenuResponse menuResponse) {
return Menu(
foods: menuResponse.foods?.map((data) => mapSharedName(data)).toList() ??
List.empty(),
drinks: menuResponse.drinks?.map((data) => mapSharedName(data)).toList() ??
List.empty(),
);
}
SharedName mapSharedName(SharedNameItem sharedNameItem) {
return SharedName(
name: sharedNameItem.name,
);
}
CustomerReviews mapCustomerReviews(CustomerReviewsItem customerReviewsItem) {
return CustomerReviews(
name: customerReviewsItem.name ?? '',
review: customerReviewsItem.review ?? '',
date: customerReviewsItem.date ?? '',
);
}
FavoriteEntity mapFavoriteEntity(Restaurant restaurant) {
return FavoriteEntity(
id: restaurant.id,
city: restaurant.city,
image: restaurant.pictureId,
rating: restaurant.rating.toString(),
name: restaurant.name,
description: restaurant.description,
);
}
Restaurant mapFavoriteToItem(FavoriteEntity favoriteEntity) {
return Restaurant(
id: favoriteEntity.id ?? '',
city: favoriteEntity.city ?? '',
pictureId: favoriteEntity.image ?? '',
rating: double.parse(favoriteEntity.rating ?? ''),
name: favoriteEntity.name ?? '',
description: favoriteEntity.description ?? '',
);
}
Restaurant mapDetailToRestaurantItem(DetailRestaurant detailRestaurant) {
return Restaurant(
id: detailRestaurant.id,
city: detailRestaurant.city,
pictureId: detailRestaurant.pictureId,
rating: detailRestaurant.rating,
name: detailRestaurant.name,
description: detailRestaurant.description,
);
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/model/customer_reviews.dart | class CustomerReviews {
final String name;
final String review;
final String date;
CustomerReviews({
required this.name,
required this.review,
required this.date,
});
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/model/menu.dart | import 'package:restaurant_app/bloc/restaurant/model/shared_name.dart';
class Menu {
final List<SharedName> foods;
final List<SharedName> drinks;
Menu({
required this.foods,
required this.drinks,
});
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/model/detail_restaurant.dart |
import 'package:restaurant_app/bloc/restaurant/model/shared_name.dart';
import 'customer_reviews.dart';
import 'menu.dart';
class DetailRestaurant {
final String id;
final String name;
final String description;
final String pictureId;
final String city;
final String address;
final List<SharedName> categories;
final List<CustomerReviews> customerReviews;
final double rating;
final Menu menu;
DetailRestaurant(
{required this.id,
required this.name,
required this.description,
required this.pictureId,
required this.city,
required this.address,
required this.rating,
required this.menu,
required this.categories,
required this.customerReviews});
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/model/shared_name.dart | class SharedName {
final String name;
SharedName({required this.name});
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/model/restaurant.dart | class Restaurant {
final String id;
final String name;
final String description;
final String pictureId;
final String city;
final double rating;
Restaurant({
required this.id,
required this.name,
required this.description,
required this.pictureId,
required this.city,
required this.rating,
});
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/state/fetch_restaurant_detail_state.dart | part of '../restaurant_state.dart';
class FetchRestaurantDetailLoadingState extends RestaurantState {
const FetchRestaurantDetailLoadingState() : super();
@override
List<Object> get props => [];
}
class FetchRestaurantDetailErrorState extends RestaurantState {
final String message;
FetchRestaurantDetailErrorState(this.message);
@override
List<Object> get props => [message];
}
class FetchRestaurantDetailSuccessState extends RestaurantState {
final DetailRestaurant detailRestaurant;
FetchRestaurantDetailSuccessState(this.detailRestaurant) : super();
@override
List<Object> get props => [detailRestaurant];
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/state/delete_favorite_state.dart | part of '../restaurant_state.dart';
class DeleteFavoriteLoadingState extends RestaurantState {
const DeleteFavoriteLoadingState() : super();
@override
List<Object> get props => [];
}
class DeleteFavoriteErrorState extends RestaurantState {
final String message;
DeleteFavoriteErrorState(this.message);
@override
List<Object> get props => [message];
}
class DeleteFavoriteSuccessState extends RestaurantState {
final bool isFavorite;
DeleteFavoriteSuccessState(this.isFavorite) : super();
@override
List<Object> get props => [isFavorite];
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/state/fetch_restaurants_state.dart | part of '../restaurant_state.dart';
class FetchRestaurantsLoadingState extends RestaurantState {
const FetchRestaurantsLoadingState() : super();
@override
List<Object> get props => [];
}
class FetchRestaurantsErrorState extends RestaurantState {
final String message;
FetchRestaurantsErrorState(this.message);
@override
List<Object> get props => [message];
}
class FetchRestaurantsSuccessState extends RestaurantState {
final List<Restaurant> restaurants;
FetchRestaurantsSuccessState(this.restaurants) : super();
@override
List<Object> get props => [];
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/state/check_favorite_state.dart | part of '../restaurant_state.dart';
class CheckFavoriteLoadingState extends RestaurantState {
const CheckFavoriteLoadingState() : super();
@override
List<Object> get props => [];
}
class UnfavorableState extends RestaurantState {
final String message;
final bool isFavorite;
UnfavorableState(this.message, this.isFavorite);
@override
List<Object> get props => [message, isFavorite];
}
class FavoredState extends RestaurantState {
final bool isFavorite;
FavoredState({
required this.isFavorite,
}) : super();
@override
List<Object> get props => [isFavorite];
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/state/search_restaurant_state.dart | part of '../restaurant_state.dart';
class SearchRestaurantLoadingState extends RestaurantState {
const SearchRestaurantLoadingState() : super();
@override
List<Object> get props => [];
}
class SearchRestaurantErrorState extends RestaurantState {
final String message;
SearchRestaurantErrorState(this.message);
@override
List<Object> get props => [message];
}
class SearchRestaurantSuccessState extends RestaurantState {
final List<Restaurant> restaurants;
SearchRestaurantSuccessState(this.restaurants) : super();
@override
List<Object> get props => [];
}
class SearchRestaurantEmptyState extends RestaurantState {
final String message;
SearchRestaurantEmptyState(this.message);
@override
List<Object> get props => [message];
} | 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/state/add_customer_review_state.dart | part of '../restaurant_state.dart';
class AddCustomerReviewLoadingState extends RestaurantState {
const AddCustomerReviewLoadingState() : super();
@override
List<Object> get props => [];
}
class AddCustomerReviewErrorState extends RestaurantState {
final String message;
AddCustomerReviewErrorState(this.message);
@override
List<Object> get props => [message];
}
class AddCustomerReviewSuccessState extends RestaurantState {
AddCustomerReviewSuccessState() : super();
@override
List<Object> get props => [];
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/state/add_to_favorite_state.dart | part of '../restaurant_state.dart';
class AddToFavoriteLoadingState extends RestaurantState {
const AddToFavoriteLoadingState() : super();
@override
List<Object> get props => [];
}
class AddToFavoriteErrorState extends RestaurantState {
final String message;
AddToFavoriteErrorState(this.message);
@override
List<Object> get props => [message];
}
class AddToFavoriteSuccessState extends RestaurantState {
final bool isFavorite;
AddToFavoriteSuccessState(this.isFavorite) : super();
@override
List<Object> get props => [isFavorite];
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant | mirrored_repositories/Restaurant-Flutter/lib/bloc/restaurant/state/fetch_favorites_state.dart | part of '../restaurant_state.dart';
class FetchFavoritesLoadingState extends RestaurantState {
const FetchFavoritesLoadingState() : super();
@override
List<Object> get props => [];
}
class FetchFavoritesErrorState extends RestaurantState {
final String message;
FetchFavoritesErrorState(this.message);
@override
List<Object> get props => [message];
}
class FetchFavoritesSuccessState extends RestaurantState {
final List<Restaurant> restaurants;
FetchFavoritesSuccessState(this.restaurants) : super();
@override
List<Object> get props => [];
}
class FetchFavoritesEmptyState extends RestaurantState {
final String emptyMessage;
FetchFavoritesEmptyState(this.emptyMessage) : super();
@override
List<Object> get props => [];
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc | mirrored_repositories/Restaurant-Flutter/lib/bloc/scheduler/scheduler_bloc.dart | import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:restaurant_app/bloc/scheduler/scheduler.dart';
import 'package:restaurant_app/utils/background_service.dart';
import 'package:restaurant_app/utils/date_time_helper.dart';
import 'package:restaurant_app/utils/preference_helper.dart';
class SchedulerBloc extends Bloc<SchedulerEvent, SchedulerState> {
final PreferencesHelper preferencesHelper;
SchedulerBloc(this.preferencesHelper) : super(SchedulerInitialState());
@override
Stream<SchedulerState> mapEventToState(SchedulerEvent event) async* {
if (event is ScheduledRestaurantsEvent) {
yield* _mapSchedulerRestaurantsEventToState(event);
} else if (event is PreferenceDailyReminderEvent) {
yield* _mapSchedulerPreferencesEventToState(event);
}
}
Stream<SchedulerState> _mapSchedulerRestaurantsEventToState(
ScheduledRestaurantsEvent event) async* {
var _isScheduled = event.value;
if (_isScheduled) {
preferencesHelper.setDailyReminder(_isScheduled);
await AndroidAlarmManager.periodic(
Duration(hours: 24),
1,
BackgroundService.callback,
startAt: DateTimeHelper.format(),
exact: true,
wakeup: true,
);
yield SchedulerRestaurantEnableState();
} else {
preferencesHelper.setDailyReminder(_isScheduled);
await AndroidAlarmManager.cancel(1);
yield SchedulerRestaurantDisableState();
}
}
Stream<SchedulerState> _mapSchedulerPreferencesEventToState(
PreferenceDailyReminderEvent event) async* {
var isDailyReminderActive = await preferencesHelper.isDailyReminderActive;
if (isDailyReminderActive) {
yield SchedulerPreferencesEnabledState(isDailyReminderActive);
} else {
yield SchedulerPreferencesDisabledState(isDailyReminderActive);
}
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc | mirrored_repositories/Restaurant-Flutter/lib/bloc/scheduler/scheduler_state.dart | import 'package:equatable/equatable.dart';
abstract class SchedulerState extends Equatable {
const SchedulerState() : super();
}
class SchedulerInitialState extends SchedulerState {
const SchedulerInitialState() : super();
@override
List<Object?> get props => [];
}
class SchedulerRestaurantEnableState extends SchedulerState {
SchedulerRestaurantEnableState();
@override
List<Object> get props => [];
}
class SchedulerRestaurantDisableState extends SchedulerState {
SchedulerRestaurantDisableState();
@override
List<Object> get props => [];
}
class SchedulerPreferencesEnabledState extends SchedulerState {
final bool status;
SchedulerPreferencesEnabledState(this.status);
@override
List<Object> get props => [status];
}
class SchedulerPreferencesDisabledState extends SchedulerState {
final bool status;
SchedulerPreferencesDisabledState(this.status);
@override
List<Object> get props => [status];
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc | mirrored_repositories/Restaurant-Flutter/lib/bloc/scheduler/scheduler_event.dart | import 'package:equatable/equatable.dart';
abstract class SchedulerEvent extends Equatable {
const SchedulerEvent();
}
class ScheduledRestaurantsEvent extends SchedulerEvent {
final bool value;
const ScheduledRestaurantsEvent({
required this.value,
});
@override
List<Object?> get props => [value];
}
class PreferenceDailyReminderEvent extends SchedulerEvent {
const PreferenceDailyReminderEvent();
@override
List<Object?> get props => [];
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/bloc | mirrored_repositories/Restaurant-Flutter/lib/bloc/scheduler/scheduler.dart | export './scheduler_bloc.dart';
export './scheduler_event.dart';
export './scheduler_state.dart'; | 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/navigator/routes.dart | import 'package:flutter/material.dart';
import 'package:restaurant_app/ui/detail/detail_restaurant_page.dart';
import 'package:restaurant_app/ui/main/main_page.dart';
import 'package:restaurant_app/ui/review/add_review_page.dart';
import 'package:restaurant_app/ui/search/search_page.dart';
class Routes {
static Route<dynamic>? generateRoute(RouteSettings settings) {
switch (settings.name) {
case DetailRestaurantPage.routeName:
final args = settings.arguments as String;
return MaterialPageRoute(
builder: (_) => DetailRestaurantPage(
id: args,
),
);
case AddReviewPage.routeName:
final args = settings.arguments as String;
return MaterialPageRoute(
builder: (_) => AddReviewPage(
id: args,
),
);
case MainApp.routeName:
return MaterialPageRoute(builder: (_) => MainApp());
case SearchPage.routeName:
return MaterialPageRoute(builder: (_) => SearchPage());
default:
return null;
}
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/navigator/navigation_helper.dart | import 'package:flutter/material.dart';
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
class Navigation {
static navigateWithData(String routeName, Object arguments) {
navigatorKey.currentState?.pushNamed(routeName, arguments: arguments);
}
static back() => navigatorKey.currentState?.pop();
} | 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/di/injector.dart | import 'package:dio/dio.dart';
import 'package:get_it/get_it.dart';
import 'package:restaurant_app/data/local/favorite_dao.dart';
import 'package:restaurant_app/di/restaurant_module.dart';
import 'package:restaurant_app/utils/preference_helper.dart';
import 'package:shared_preferences/shared_preferences.dart';
GetIt locator = GetIt.instance;
const String baseUrl = 'https://restaurant-api.dicoding.dev/';
void injectModules() async {
BaseOptions options = new BaseOptions(
connectTimeout: 60000, receiveTimeout: 60000, followRedirects: false);
Dio _dio = Dio(options);
FavoriteDao _favoriteDao = FavoriteDao();
locator.registerSingleton(_dio);
locator.registerSingleton(_favoriteDao);
locator.registerSingleton(
PreferencesHelper(sharedPreferences: SharedPreferences.getInstance()));
injectRestaurantModuleModule();
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/di/restaurant_module.dart | import 'package:restaurant_app/bloc/restaurant/restaurant_bloc.dart';
import 'package:restaurant_app/bloc/scheduler/scheduler.dart';
import 'package:restaurant_app/data/remote/restaurant_api.dart';
import 'package:restaurant_app/data/remote/restaurant_api_client.dart';
import 'package:restaurant_app/data/restaurant_data_store.dart';
import 'package:restaurant_app/data/restaurant_repository.dart';
import 'package:restaurant_app/di/injector.dart';
void injectRestaurantModuleModule() {
locator.registerSingleton(RestaurantApiClient(locator.get()));
locator.registerSingleton(RestaurantApi(locator.get()));
locator.registerSingleton<RestaurantRepository>(
RestaurantDataSource(locator.get(), locator.get()));
locator.registerSingleton(RestaurantBloc(locator.get()));
locator.registerSingleton(SchedulerBloc(locator.get()));
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/utils/date_time_helper.dart | import 'package:intl/intl.dart';
class DateTimeHelper {
static DateTime format() {
/// Date and Time Format
final now = DateTime.now();
final dateFormat = DateFormat('y/M/d');
final timeSpecific = "11:00:00";
final completeFormat = DateFormat('y/M/d H:m:s');
/// Today Format
final todayDate = dateFormat.format(now);
final todayDateAndTime = "$todayDate $timeSpecific";
var resultToday = completeFormat.parseStrict(todayDateAndTime);
/// Tomorrow Format
var formatted = resultToday.add(Duration(days: 1));
final tomorrowDate = dateFormat.format(formatted);
final tomorrowDateAndTime = "$tomorrowDate $timeSpecific";
var resultTomorrow = completeFormat.parseStrict(tomorrowDateAndTime);
return now.isAfter(resultToday) ? resultTomorrow : resultToday;
}
} | 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/utils/assets.dart | const String MEDIUM_IMAGE_URL =
'https://restaurant-api.dicoding.dev/images/medium/';
const String LARGE_IMAGE_URL =
'https://restaurant-api.dicoding.dev/images/large/';
const String APP_ICON = 'assets/images/dicoding_logo.jpeg';
const String USER_ICON = 'assets/images/ic_user.svg';
const String FOODS_ICON = 'assets/images/ic_foods.jpg';
const String DRINKS_ICON = 'assets/images/ic_drinks.jpg';
| 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/utils/styles.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'colors.dart';
final TextTheme myTextTheme = TextTheme(
headline1: GoogleFonts.libreFranklin(
fontSize: 92, fontWeight: FontWeight.w300, letterSpacing: -1.5),
headline2: GoogleFonts.libreFranklin(
fontSize: 57, fontWeight: FontWeight.w300, letterSpacing: -0.5),
headline3:
GoogleFonts.libreFranklin(fontSize: 46, fontWeight: FontWeight.w400),
headline4: GoogleFonts.libreFranklin(
fontSize: 32, fontWeight: FontWeight.w400, letterSpacing: 0.25),
headline5: GoogleFonts.libreFranklin(
fontSize: 23, fontWeight: FontWeight.w400, color: whiteColor),
headline6: GoogleFonts.libreFranklin(
fontSize: 19,
fontWeight: FontWeight.w500,
letterSpacing: 0.15,
color: whiteColor),
subtitle1: GoogleFonts.libreFranklin(
fontSize: 16, fontWeight: FontWeight.bold, letterSpacing: 0.15),
subtitle2: GoogleFonts.libreFranklin(
fontSize: 13, fontWeight: FontWeight.bold, letterSpacing: 0.1),
bodyText1: GoogleFonts.libreFranklin(
fontSize: 14,
fontWeight: FontWeight.w400,
letterSpacing: 0.5,
color: Colors.grey[600]),
bodyText2: GoogleFonts.libreFranklin(
fontSize: 12,
fontWeight: FontWeight.w400,
letterSpacing: 0.25,
color: Colors.grey[600]),
button: GoogleFonts.libreFranklin(
fontSize: 14, fontWeight: FontWeight.w500, letterSpacing: 1.25),
caption: GoogleFonts.libreFranklin(
fontSize: 12, fontWeight: FontWeight.w400, letterSpacing: 0.4),
overline: GoogleFonts.libreFranklin(
fontSize: 10, fontWeight: FontWeight.w400, letterSpacing: 1.5),
);
InputDecorationTheme inputDecorationTheme() {
OutlineInputBorder outlineInputBorder = OutlineInputBorder(
borderSide: BorderSide(color: colorSolitude),
borderRadius: BorderRadius.circular(10),
gapPadding: 10);
OutlineInputBorder focusedOutlineInputBorder = OutlineInputBorder(
borderSide: BorderSide(color: colorSecondary),
borderRadius: BorderRadius.circular(10),
gapPadding: 10);
OutlineInputBorder disabledOutlineInputBorder = OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(10),
gapPadding: 10);
return InputDecorationTheme(
contentPadding: EdgeInsets.symmetric(vertical: 15, horizontal: 16),
filled: true,
fillColor: colorSolitude,
enabledBorder: outlineInputBorder,
focusedBorder: focusedOutlineInputBorder,
disabledBorder: disabledOutlineInputBorder,
border: outlineInputBorder);
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/utils/error_handler.dart | import 'package:dio/dio.dart';
String handleError(DioError error) {
String errorDescription = '';
if (error is DioError) {
DioError dioError = error;
switch (dioError.type) {
case DioErrorType.cancel:
errorDescription = "Request to API server was cancelled";
break;
case DioErrorType.connectTimeout:
errorDescription = "Connection timeout with API server";
break;
case DioErrorType.receiveTimeout:
errorDescription = "Receive timeout in connection with API server";
break;
case DioErrorType.response:
errorDescription = error.response?.data;
break;
case DioErrorType.sendTimeout:
errorDescription = "Send timeout in connection with API server";
break;
default:
errorDescription = "Send timeout in connection with API server";
break;
}
} else {
errorDescription = "Unexpected error occured";
}
return errorDescription;
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/utils/background_service.dart | import 'dart:isolate';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:restaurant_app/data/model/response/restaurant_response.dart';
import 'package:restaurant_app/data/remote/restaurant_api.dart';
import 'package:restaurant_app/data/remote/restaurant_api_client.dart';
import 'package:restaurant_app/ui/main.dart';
import 'notification_helper.dart';
final ReceivePort port = ReceivePort();
class BackgroundService {
static String _isolateName = 'isolate';
static SendPort? _uiSendPort;
BackgroundService();
void initializeIsolate() {
IsolateNameServer.registerPortWithName(
port.sendPort,
_isolateName,
);
}
static Future callback() async {
final Dio dio = Dio();
final RestaurantApiClient restaurantApiClient = RestaurantApiClient(dio);
final RestaurantApi restaurantApi = RestaurantApi(restaurantApiClient);
final NotificationHelper _notificationHelper = NotificationHelper();
RestaurantResponse restaurantsResponse =
await restaurantApi.getRestaurantData();
await _notificationHelper.showNotification(
flutterLocalNotificationsPlugin, restaurantsResponse);
_uiSendPort ??= IsolateNameServer.lookupPortByName(_isolateName);
_uiSendPort?.send(null);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/utils/preference_helper.dart | import 'package:shared_preferences/shared_preferences.dart';
class PreferencesHelper {
final Future<SharedPreferences> sharedPreferences;
PreferencesHelper({required this.sharedPreferences});
static const DAILY_REMINDER = 'DAILY_REMINDER';
Future<bool> get isDailyReminderActive async {
final prefs = await sharedPreferences;
return prefs.getBool(DAILY_REMINDER) ?? false;
}
void setDailyReminder(bool value) async {
final prefs = await sharedPreferences;
prefs.setBool(DAILY_REMINDER, value);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/utils/notification_helper.dart | import 'dart:convert';
import 'dart:math';
import 'package:flutter_local_notifications/flutter_local_notifications.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/navigator/navigation_helper.dart';
import 'package:rxdart/subjects.dart';
final selectNotificationSubject = BehaviorSubject<String>();
class NotificationHelper {
static NotificationHelper? _instance;
NotificationHelper._internal() {
_instance = this;
}
factory NotificationHelper() => _instance ?? NotificationHelper._internal();
Future<void> initNotifications(
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async {
var initializationSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
var initializationSettingsIOS = IOSInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
);
var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String? payload) async {
if (payload != null) {
print('notification payload: ' + payload);
}
selectNotificationSubject.add(payload ?? 'empty payload');
});
}
Future<void> showNotification(
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin,
RestaurantResponse restaurantResponse) async {
var _channelId = "1";
var _channelName = "channel_01";
var _channelDescription = "restaurant app channel";
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
_channelId, _channelName, _channelDescription,
importance: Importance.max,
priority: Priority.high,
ticker: 'ticker',
styleInformation: DefaultStyleInformation(true, true));
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iOSPlatformChannelSpecifics);
final _random = new Random();
var randomRestaurant = restaurantResponse
.restaurants[_random.nextInt(restaurantResponse.restaurants.length)];
var titleNotification = "<b>Cafe Recommendation</b>";
var titleNews = randomRestaurant.name;
await flutterLocalNotificationsPlugin.show(
0, titleNotification, titleNews, platformChannelSpecifics,
payload: json.encode(randomRestaurant.toJson()));
}
void configureSelectNotificationSubject(String route) {
selectNotificationSubject.stream.listen(
(String payload) async {
var data = RestaurantItem.fromJson(json.decode(payload));
Navigation.navigateWithData(route, data.id.toString());
},
);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/utils/colors.dart | import 'package:flutter/material.dart';
final Color whiteColor = Color(0xFFFFFFFF);
final Color primaryColor = Color(0xFF03257E);
const colorSecondary = Color(0xFF399AC2);
const colorSolitude = Color(0xFFF4F6FA);
| 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/utils/validation_helper.dart | String? validationFieldMinMaxRequired(
{required String value,
String? fieldName,
int minValue = 1,
required int maxValue}) {
if (value.length == 0) {
return "$fieldName is required";
} else if (value.length < minValue) {
return 'Minimum $minValue character';
} else if (value.length > maxValue) {
return 'Maximum $maxValue character';
} else {
return null;
}
} | 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/utils/dialog_utils.dart | import 'package:flutter/material.dart';
import 'package:restaurant_app/ui/shared/loading_dialog.dart';
void showLoading(BuildContext context) {
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) => LoadingDialog(),
);
}
void hideLoading(BuildContext context){
Navigator.pop(context);
} | 0 |
mirrored_repositories/Restaurant-Flutter/lib | mirrored_repositories/Restaurant-Flutter/lib/ui/main.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:restaurant_app/bloc/bloc_observer.dart';
import 'package:restaurant_app/bloc/restaurant/restaurant.dart';
import 'package:restaurant_app/bloc/scheduler/scheduler.dart';
import 'package:restaurant_app/data/remote/restaurant_api_client.dart';
import 'package:restaurant_app/di/injector.dart';
import 'package:restaurant_app/navigator/navigation_helper.dart';
import 'package:restaurant_app/navigator/routes.dart';
import 'package:restaurant_app/ui/splash/splash_screen.dart';
import 'package:restaurant_app/utils/background_service.dart';
import 'package:restaurant_app/utils/notification_helper.dart';
import 'package:restaurant_app/utils/styles.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:android_alarm_manager/android_alarm_manager.dart';
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
injectModules();
Bloc.observer = BlocObserverApp();
final NotificationHelper _notificationHelper = NotificationHelper();
final BackgroundService _service = BackgroundService();
_service.initializeIsolate();
if (Platform.isAndroid) {
await AndroidAlarmManager.initialize();
}
await _notificationHelper.initNotifications(flutterLocalNotificationsPlugin);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final RestaurantBloc _restaurantBloc = locator.get();
final SchedulerBloc _schedulerBloc = locator.get();
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(
create: (BuildContext context) {
return _restaurantBloc;
},
),
BlocProvider(
create: (BuildContext context) {
return _schedulerBloc;
},
)
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Restaurant App',
onGenerateRoute: Routes.generateRoute,
theme: ThemeData(
primarySwatch: Colors.blue,
textTheme: myTextTheme,
inputDecorationTheme: inputDecorationTheme()),
navigatorKey: navigatorKey,
home: SplashScreen(),
),
);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/main/home_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 HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
_fetchRestaurant(context);
return BlocBuilder<RestaurantBloc, RestaurantState>(
buildWhen: (previousState, state) {
return state is FetchRestaurantsErrorState ||
state is FetchRestaurantsLoadingState ||
state is FetchRestaurantsSuccessState;
},
builder: (context, state) {
if (state is FetchRestaurantsSuccessState) {
List<Restaurant> restaurants = state.restaurants;
return _buildHomePage(restaurants: restaurants);
} else if (state is FetchRestaurantsLoadingState) {
return Padding(
padding: EdgeInsets.only(top: 100),
child: Center(
child: CircularProgressIndicator(),
),
);
} else if (state is FetchRestaurantsErrorState) {
return Center(
child: Center(
child: Text(state.message),
),
);
} else {
return Padding(
padding: EdgeInsets.only(top: 100),
child: Center(
child: CircularProgressIndicator(),
),
);
}
},
);
}
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],
);
},
);
}
_fetchRestaurant(BuildContext context) {
context.read<RestaurantBloc>().add(FetchedRestaurantsEvent());
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/main/main_page.dart | import 'package:curved_navigation_bar/curved_navigation_bar.dart';
import 'package:flutter/material.dart';
import 'package:restaurant_app/ui/detail/detail_restaurant_page.dart';
import 'package:restaurant_app/ui/favorite/favorites_page.dart';
import 'package:restaurant_app/ui/search/search_page.dart';
import 'package:restaurant_app/ui/settings/settings_page.dart';
import 'package:restaurant_app/utils/colors.dart';
import 'package:restaurant_app/utils/notification_helper.dart';
import 'home_page.dart';
class MainApp extends StatefulWidget {
const MainApp({Key? key}) : super(key: key);
static const String routeName = '/main_page';
@override
_MainAppState createState() => _MainAppState();
}
class _MainAppState extends State<MainApp> {
final FavoritesPage _favorite = FavoritesPage();
final SettingsPage _settings = SettingsPage();
final NotificationHelper _notificationHelper = NotificationHelper();
Widget _showPages = HomePage();
Widget _pageChooser(int page) {
switch (page) {
case 0:
return HomePage();
case 1:
return _favorite;
case 2:
return _settings;
default:
return new Container(
child: Text(
'Page Not Found',
style: TextStyle(fontSize: 30.0),
),
);
}
}
@override
void initState() {
super.initState();
_notificationHelper
.configureSelectNotificationSubject(DetailRestaurantPage.routeName);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
titleSpacing: 16,
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Restaurant App',
style: Theme.of(context).textTheme.headline6,
),
SizedBox(
height: 4,
),
Text(
'Recommendation Restaurants for you!',
style: TextStyle(
color: whiteColor,
fontSize: 11,
fontWeight: FontWeight.w400),
),
],
),
brightness: Brightness.dark,
backgroundColor: primaryColor,
actions: [
IconButton(
onPressed: () {
Navigator.of(context).pushNamed(SearchPage.routeName);
},
icon: Icon(
Icons.search,
color: whiteColor,
),
),
],
),
bottomNavigationBar: CurvedNavigationBar(
backgroundColor: Colors.transparent,
color: primaryColor,
items: <Widget>[
Icon(
Icons.restaurant,
size: 30,
color: Colors.white,
),
Icon(
Icons.favorite,
size: 30,
color: Colors.white,
),
Icon(
Icons.settings,
size: 30,
color: Colors.white,
),
],
onTap: (index) {
setState(() {
_showPages = _pageChooser(index);
});
},
),
body: _showPages);
}
}
| 0 |
mirrored_repositories/Restaurant-Flutter/lib/ui | mirrored_repositories/Restaurant-Flutter/lib/ui/shared/container_restaurants.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:restaurant_app/bloc/restaurant/model/restaurant.dart';
import 'package:restaurant_app/ui/detail/detail_restaurant_page.dart';
import 'package:restaurant_app/utils/assets.dart';
import 'package:restaurant_app/utils/colors.dart';
import 'custom_error_image.dart';
import 'custom_loading_indicator.dart';
class ContainerRestaurants extends StatefulWidget {
final Restaurant data;
const ContainerRestaurants({
Key? key,
required this.data,
}) : super(key: key);
@override
_ContainerRestaurantsState createState() => _ContainerRestaurantsState();
}
class _ContainerRestaurantsState extends State<ContainerRestaurants> {
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.fromLTRB(16, 12, 16, 8),
decoration: BoxDecoration(
color: whiteColor,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0, 2), // changes position of shadow
),
],
),
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(8),
onTap: () {
Navigator.of(context).pushNamed(
DetailRestaurantPage.routeName,
arguments: widget.data.id,
);
},
child: Row(
children: [
Container(
margin: EdgeInsets.fromLTRB(8, 8, 8, 8),
height: 80,
width: 80,
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Hero(
tag: widget.data.pictureId,
child: CachedNetworkImage(
fit: BoxFit.cover,
imageUrl: MEDIUM_IMAGE_URL + widget.data.pictureId,
placeholder: (context, url) => CustomLoadingIndicator(),
errorWidget: (context, url, error) => CustomErrorImage(),
),
),
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(widget.data.name,
style: Theme.of(context).textTheme.subtitle2),
SizedBox(
height: 8,
),
Row(
children: [
Icon(
Icons.location_pin,
color: Colors.grey[600],
size: 20,
),
SizedBox(
width: 4,
),
Text(widget.data.city,
style: Theme.of(context).textTheme.bodyText2)
],
),
SizedBox(
height: 4,
),
Row(
children: [
Icon(
Icons.star,
color: Colors.amberAccent,
size: 20,
),
SizedBox(
width: 4,
),
Text(widget.data.rating.toString(),
style: Theme.of(context).textTheme.bodyText2)
],
)
],
),
)
],
),
),
),
);
}
}
| 0 |