repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/MHM-Flutter-UI-UX-Tutorial/Flutter Neumorphic Button with Lottie Animations
|
mirrored_repositories/MHM-Flutter-UI-UX-Tutorial/Flutter Neumorphic Button with Lottie Animations/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:neu_clock/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/fluttertutorial
|
mirrored_repositories/fluttertutorial/lib/PeopleListView.dart
|
import 'package:flutter/material.dart';
class PeopleListView extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return ListView(
children: <Widget>[
ListTile(
leading: Icon(Icons.map),
title: Text('Map')
),
ListTile(
leading: Icon(Icons.photo_album),
title: Text('Album'),
),
ListTile(
leading: Icon(Icons.phone),
title: Text('Phone')
),
ListTile(
leading: Icon(Icons.photo_camera),
title: Text('Camera')
)
],
);
}
}
| 0
|
mirrored_repositories/fluttertutorial
|
mirrored_repositories/fluttertutorial/lib/Post.dart
|
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body']
);
}
}
| 0
|
mirrored_repositories/fluttertutorial
|
mirrored_repositories/fluttertutorial/lib/listpost.dart
|
import 'package:flutter/material.dart';
import 'Post.dart';
class ListViewPosts extends StatelessWidget{
final List<Post> posts;
ListViewPosts({Key key, this.posts}) : super(key: key);
@override
Widget build(BuildContext context) {
// TODO: implement build
return Container(
child: ListView.builder(
itemCount: posts.length,
padding: const EdgeInsets.all(15.0),
itemBuilder: (context, position) {
return Column(
children: <Widget>[
],
);
}),
);
}
}
| 0
|
mirrored_repositories/fluttertutorial
|
mirrored_repositories/fluttertutorial/lib/main.dart
|
import 'package:flutter/material.dart';
import './PeopleListView.dart';
void main () => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('Welcome to Flutter')
),
body: PeopleListView(),
),
);
}
}
| 0
|
mirrored_repositories/fluttertutorial
|
mirrored_repositories/fluttertutorial/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:fluttertutorial/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/Flutter_StreamingApp_UI
|
mirrored_repositories/Flutter_StreamingApp_UI/lib/theme.dart
|
import 'package:flutter/material.dart';
class CustomTheme {
static Color mPrimaryColor = Color(0xff6f16c9);
static Color mAccentColor = Color(0xff0c0314);
static ThemeData theme() {
return ThemeData(
primaryColor: mPrimaryColor,
accentColor: Color(0xff0c0314),
backgroundColor: Color(0xff0c0314),
textTheme: TextTheme(
headline1: TextStyle(color: Colors.white, fontSize: 18),
headline2: TextStyle(color: mPrimaryColor, fontWeight: FontWeight.bold,fontSize: 24),
headline3: TextStyle(color: Colors.white,fontSize: 20,fontWeight: FontWeight.bold),
headline4: TextStyle(color: Colors.white,fontSize: 16),
caption: TextStyle(color: Colors.white,fontSize: 15,letterSpacing: 0.9,fontWeight: FontWeight.bold),
button: TextStyle(
color: Colors.white, fontSize: 16, letterSpacing: 1)));
}
}
class CustomButtonColor extends MaterialStateColor {
const CustomButtonColor() : super(_defaultColor);
static const int _defaultColor = 0xff6f16c9;
static const int _pressedColor = 0xff5810a1;
@override
Color resolve(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return const Color(_pressedColor);
}
return const Color(_defaultColor);
}
}
| 0
|
mirrored_repositories/Flutter_StreamingApp_UI
|
mirrored_repositories/Flutter_StreamingApp_UI/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_streaming_ui/screens/getStarted.dart';
import 'package:flutter_streaming_ui/theme.dart';
main() => runApp(App());
class App extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Streaming App',
theme: CustomTheme.theme(),
home: StartScreen(),
);
}
}
| 0
|
mirrored_repositories/Flutter_StreamingApp_UI/lib
|
mirrored_repositories/Flutter_StreamingApp_UI/lib/screens/home.dart
|
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:flutter_streaming_ui/theme.dart';
class Home extends StatelessWidget {
Home({Key? key}) : super(key: key);
List categories = [
"Action",
"Drama",
"Crime",
"Thriller",
"Isekai",
"Adventure",
"Comedy",
"Sport"
];
List videoTitle = [
"One Piece",
"Fairy Tail",
"kemtsu no yaiba",
"Code Geass"
];
List images = ['1.png', '2.jpg', '3.jpg', '4.jpg'];
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
body: Container(
width: size.width,
height: size.height,
color: Theme.of(context).backgroundColor,
child: Padding(
padding: const EdgeInsets.only(top: 20, left: 30),
child: SafeArea(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: EdgeInsets.only(left: 15),
decoration: BoxDecoration(
color: CustomTheme.mPrimaryColor,
borderRadius: BorderRadius.circular(12)),
width: size.width * 0.65,
child: TextField(
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
errorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
hintText: "Search anime",
hintStyle: TextStyle(color: Colors.white),
icon: Icon(
Icons.search,
color: Colors.white,
)),
enabled: true,
),
),
Container(
margin: EdgeInsets.only(right: 30),
height: size.height * 0.066,
width: size.height * 0.066,
decoration: BoxDecoration(
color: CustomTheme.mPrimaryColor,
borderRadius: BorderRadius.circular(12)),
child: Icon(
Icons.bookmark_border,
color: Colors.white,
),
)
],
),
SizedBox(height: 10),
Container(
// color: Colors.red,
width: size.width,
height: size.height * 0.045,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: categories.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.fromLTRB(0, 8, 16, 8),
child: Text(
categories[index],
style: Theme.of(context).textTheme.caption,
),
);
}),
),
SizedBox(height: 10),
Text(
"Update",
style: Theme.of(context).textTheme.headline2,
),
Container(
// color: Colors.red,
width: size.width,
height: size.height * 0.35,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: videoTitle.length,
itemBuilder: (context, index) {
return Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding:
const EdgeInsets.only(top: 15, bottom: 8),
child: Text(videoTitle[index],
style:
Theme.of(context).textTheme.headline3),
),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
"Episode 2414",
style:
Theme.of(context).textTheme.headline4,
),
SizedBox(
width: size.width * 0.32,
),
Text("Read on Manga",
style:
Theme.of(context).textTheme.headline4)
],
),
SizedBox(height: 15),
Container(
decoration: BoxDecoration(
// color: Colors.white,
borderRadius: BorderRadius.circular(12)),
margin: EdgeInsets.only(right: 15),
width: size.width * 0.855,
child: CustomVideoPlayer(),
),
],
),
);
}),
),
SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"New release",
style: Theme.of(context).textTheme.headline2,
),
Padding(
padding: const EdgeInsets.only(right: 30),
child: Text(
"see also",
style: Theme.of(context).textTheme.caption,
),
)
],
),
SizedBox(
height: 10,
),
Container(
width: size.width,
height: size.height * 0.25,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: videoTitle.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(right: 10),
child: Container(
decoration: BoxDecoration(
color: Colors.black38,
image: DecorationImage(
colorFilter: new ColorFilter.mode(
Colors.black.withOpacity(0.6),
BlendMode.dstATop),
fit: BoxFit.cover,
image:
AssetImage("images/${images[index]}")),
borderRadius: BorderRadius.circular(20)),
width: size.width * 0.4,
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(left: 8),
child: Text(
videoTitle[index],
style:
Theme.of(context).textTheme.caption,
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Icon(
Icons.star,
color: Colors.yellow[700],
),
Text(
"(4.5)",
style: TextStyle(color: Colors.white),
),
SizedBox(
width: 20,
),
Icon(
Icons.remove_red_eye,
color: Colors.white,
),
Text(
"(4.5)",
style: TextStyle(color: Colors.white),
)
],
),
)
]),
),
);
}),
),
SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Popular Anime",
style: Theme.of(context).textTheme.headline2,
),
Padding(
padding: const EdgeInsets.only(right: 30),
child: Text(
"see also",
style: Theme.of(context).textTheme.caption,
),
)
],
),
SizedBox(
height: 10,
),
Container(
width: size.width,
height: size.height * 0.1,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: videoTitle.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(right: 10),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
decoration: BoxDecoration(
color: Colors.black38,
image: DecorationImage(
colorFilter: new ColorFilter.mode(
Colors.black.withOpacity(0.6),
BlendMode.dstATop),
fit: BoxFit.cover,
image: AssetImage(
"images/${images[index]}")),
borderRadius: BorderRadius.circular(20)),
width: size.height * 0.1,
),
Padding(
padding:
const EdgeInsets.only(left: 5, top: 15),
child: Container(
width: size.width * 0.4,
child: Text(
videoTitle[index],
style:
Theme.of(context).textTheme.caption,
)),
)
]),
);
}),
),
SizedBox(
height: 50,
)
],
),
)),
),
),
bottomNavigationBar: CustomBottomNavigation(size),
);
}
}
class CustomBottomNavigation extends StatelessWidget {
Size size = new Size(100, 100);
CustomBottomNavigation(this.size);
@override
Widget build(BuildContext context) {
return Container(
color: CustomTheme.mPrimaryColor,
height: size.height * 0.07,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
decoration: BoxDecoration(
color: CustomTheme.mAccentColor,
borderRadius: BorderRadius.circular(15),
),
padding: EdgeInsets.only(right: 13),
child: Row(
children: [
IconButton(
onPressed: () {},
icon: Icon(
Icons.home_outlined,
color: CustomTheme.mPrimaryColor,
size: 28,
)),
Text("Home", style: Theme.of(context).textTheme.caption)
],
)),
IconButton(
onPressed: () {},
icon: Icon(
Icons.play_arrow_outlined,
color: Colors.white,
size: 30,
)),
IconButton(
onPressed: () {},
icon: Icon(
Icons.notifications_outlined,
color: Colors.white,
size: 30,
)),
IconButton(
onPressed: () {},
icon: Icon(
Icons.settings_outlined,
color: Colors.white,
size: 30,
)),
],
),
),
);
}
}
class CustomVideoPlayer extends StatefulWidget {
const CustomVideoPlayer({Key? key}) : super(key: key);
@override
_VideoPlayerState createState() => _VideoPlayerState();
}
class _VideoPlayerState extends State<CustomVideoPlayer> {
// final String url = "http://getvideo.watch/index.php?output=yt/M_OauHnAFc8/128%7e%7e1%7e%7eAttack_on_Titan_Season_4_Final_Season_-_Official_Trailer_uuid-60eae0c9314b6.mp4";
late VideoPlayerController controller;
@override
void initState() {
super.initState();
controller = VideoPlayerController.asset('assets/video.mp4')
..addListener(() => setState(() {}))
..initialize().then((value) => controller.initialize());
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return controller.value.isInitialized
? Container(
decoration: BoxDecoration(borderRadius: BorderRadius.circular(20)),
child: Stack(children: [
AspectRatio(
aspectRatio: 1 / 0.53,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: VideoPlayer(controller)),
),
Positioned.fill(
child: BasicOverlayWidget(controller: controller)),
]),
)
: Center(
child: CircularProgressIndicator(
backgroundColor: Theme.of(context).accentColor,
));
}
}
class BasicOverlayWidget extends StatelessWidget {
final VideoPlayerController controller;
const BasicOverlayWidget({
Key? key,
required this.controller,
}) : super(key: key);
@override
Widget build(BuildContext context) => GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () =>
controller.value.isPlaying ? controller.pause() : controller.play(),
child: Stack(
children: <Widget>[
buildPlay(),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: buildIndicator(),
),
],
),
);
Widget buildIndicator() => Container(
margin: EdgeInsets.symmetric(horizontal: 10),
child: VideoProgressIndicator(
controller,
allowScrubbing: true,
),
);
Widget buildPlay() => controller.value.isPlaying
? Container()
: Container(
alignment: Alignment.center,
color: Colors.black38,
child: CircleAvatar(
backgroundColor: CustomTheme.mPrimaryColor,
child: Icon(Icons.play_arrow_rounded,
color: Colors.white, size: 30)),
);
}
| 0
|
mirrored_repositories/Flutter_StreamingApp_UI/lib
|
mirrored_repositories/Flutter_StreamingApp_UI/lib/screens/getStarted.dart
|
import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter_streaming_ui/screens/home.dart';
import 'package:flutter_streaming_ui/theme.dart';
class StartScreen extends StatefulWidget {
const StartScreen({Key? key}) : super(key: key);
@override
_StartScreenState createState() => _StartScreenState();
}
class _StartScreenState extends State<StartScreen> {
int _current = 0;
final CarouselController _controller = CarouselController();
List images = ['1.png', '2.jpg', '3.jpg', '4.jpg'];
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
body: Container(
height: size.height,
width: size.width,
color: Theme.of(context).backgroundColor,
child: SafeArea(
child: Padding(
padding: EdgeInsets.fromLTRB(
20, size.height * 0.05, 20, size.height * 0.1),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
children: [
CarouselSlider.builder(
carouselController: _controller,
itemCount: images.length,
options: CarouselOptions(
height: size.height * 0.65,
autoPlay: true,
viewportFraction: 1,
onPageChanged: (index, reason) {
setState(() {
_current = index;
});
}),
itemBuilder: (context, index, pageviewIndex) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
image: DecorationImage(
fit: BoxFit.cover,
image:
AssetImage('images/${images[index]}'))),
),
);
}),
Padding(
padding: const EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: images.asMap().entries.map((entry) {
return GestureDetector(
onTap: () => _controller.animateToPage(entry.key),
child: Container(
width: 12.0,
height: 12.0,
margin: EdgeInsets.symmetric(
vertical: 8.0, horizontal: 4.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: (Theme.of(context).brightness ==
Brightness.dark
? CustomTheme.mPrimaryColor
: Colors.white)
.withOpacity(
_current == entry.key ? 0.9 : 0.4)),
),
);
}).toList(),
),
)
],
),
TextButton(
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => Home()));
},
child: Container(
decoration: BoxDecoration(
color: CustomTheme.mPrimaryColor,
borderRadius: BorderRadius.circular(12)),
padding: EdgeInsets.symmetric(
vertical: size.height * 0.02,
horizontal: size.width * 0.2),
child: Text(
"Get Started",
style: Theme.of(context).textTheme.button,
),
)),
],
),
),
),
));
}
}
| 0
|
mirrored_repositories/Wassword
|
mirrored_repositories/Wassword/lib/main.dart
|
// ignore_for_file: depend_on_referenced_packages
import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_web_plugins/url_strategy.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wassword/app/app.dart';
import 'package:wassword/app/app_bloc_observer.dart';
import 'package:window_manager/window_manager.dart';
import 'package:wassword/styles/colors.dart' as mcolors;
import 'package:flutter/foundation.dart' show kIsWeb;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
usePathUrlStrategy();
if (!kIsWeb &&
!Platform.isAndroid &&
!Platform.isIOS &&
(Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
await windowManager.ensureInitialized();
windowManager.waitUntilReadyToShow().then((_) async {
await windowManager.setSize(const Size(385, 835));
});
}
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(
systemNavigationBarColor:
mcolors.backgroundView, // navigation bar color
statusBarColor: mcolors.backgroundView, //top bar color
statusBarIconBrightness: Brightness.light, // status bar icons' color
statusBarBrightness: Brightness.dark),
);
Bloc.observer = AppBlocObserver();
FlutterError.onError = (details) {
log(details.exceptionAsString(), stackTrace: details.stack);
};
runZonedGuarded(
() => runApp(App()),
(error, stackTrace) => log(error.toString(), stackTrace: stackTrace),
);
}
| 0
|
mirrored_repositories/Wassword/lib
|
mirrored_repositories/Wassword/lib/app/app.dart
|
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:wassword/pages/about_page.dart';
import 'package:wassword/pages/home_page.dart';
import 'package:wassword/styles/colors.dart' as mcolors;
class App extends StatelessWidget {
App({Key? key}) : super(key: key);
final _router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomePage(),
),
GoRoute(
path: '/about',
builder: (context, state) => const AboutPage(),
),
],
);
@override
Widget build(BuildContext context) => MaterialApp.router(
debugShowCheckedModeBanner: false,
routeInformationProvider: _router.routeInformationProvider,
routeInformationParser: _router.routeInformationParser,
routerDelegate: _router.routerDelegate,
theme: ThemeData(
useMaterial3: true,
textTheme: GoogleFonts.robotoTextTheme(
Theme.of(context).textTheme,
),
appBarTheme: AppBarTheme(
backgroundColor: mcolors.backgroundView,
centerTitle: true,
elevation: 0,
),
brightness: Brightness.dark,
visualDensity: VisualDensity.adaptivePlatformDensity,
backgroundColor: mcolors.backgroundView,
scaffoldBackgroundColor: mcolors.backgroundView,
),
);
}
| 0
|
mirrored_repositories/Wassword/lib
|
mirrored_repositories/Wassword/lib/app/app_bloc_observer.dart
|
import 'package:flutter_bloc/flutter_bloc.dart';
class AppBlocObserver extends BlocObserver {
@override
void onCreate(BlocBase bloc) {
super.onCreate(bloc);
print('onCreate -- bloc: ${bloc.runtimeType}');
}
@override
void onEvent(Bloc bloc, Object? event) {
super.onEvent(bloc, event);
print('onEvent -- bloc: ${bloc.runtimeType}, event: $event');
}
@override
void onChange(BlocBase bloc, Change change) {
super.onChange(bloc, change);
print('onChange -- bloc: ${bloc.runtimeType}, change: $change');
}
@override
void onTransition(Bloc bloc, Transition transition) {
super.onTransition(bloc, transition);
print('onTransition -- bloc: ${bloc.runtimeType}, transition: $transition');
}
@override
void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
print('onError -- bloc: ${bloc.runtimeType}, error: $error');
super.onError(bloc, error, stackTrace);
}
@override
void onClose(BlocBase bloc) {
super.onClose(bloc);
print('onClose -- bloc: ${bloc.runtimeType}');
}
}
| 0
|
mirrored_repositories/Wassword/lib
|
mirrored_repositories/Wassword/lib/pages/home_page.dart
|
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:wassword/cubit/password_cubit.dart';
import 'package:wassword/styles/colors.dart' as mcolors;
import 'package:wassword/styles/dimens.dart' as mdimens;
import 'package:wassword/ui/action_button.dart';
import 'package:wassword/ui/custom_slider_thumb_circle.dart';
import 'package:wassword/ui/option_button.dart';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => PasswordCubit(),
child: const HomeView(),
);
}
}
class HomeView extends StatelessWidget {
const HomeView({Key? key}) : super(key: key);
void _copyToClipboard(String newPassword) {
Clipboard.setData(ClipboardData(text: newPassword));
if (Platform.isAndroid || Platform.isIOS) {
Fluttertoast.showToast(
msg: "Password copied to clipboard",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor:
mcolors.backgroundView, // status bar colortatus bar brightness
title: Text(
"Wassword",
style: GoogleFonts.roboto(
color: mcolors.colorTextLight,
),
),
actions: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 16),
child: IconButton(
iconSize: 24,
color: mcolors.colorTextLight,
icon: const Icon(Icons.person_outline),
onPressed: () => context.push('/about')),
),
],
),
body: Column(
children: <Widget>[
Container(
margin: EdgeInsets.all(mdimens.defaultSpace),
height: 160,
decoration: BoxDecoration(
color: mcolors.colorEnabled,
borderRadius:
BorderRadius.all(Radius.circular(mdimens.roundedCorner)),
),
padding:
EdgeInsets.symmetric(horizontal: mdimens.paddingHorizontal),
alignment: const Alignment(0, 0),
child: Text(
context.select((PasswordCubit cubit) => cubit.state.password),
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 30,
color: mcolors.colorTextDark),
),
),
//https://medium.com/flutter-community/flutter-sliders-demystified-4b3ea65879c
SliderTheme(
data: SliderTheme.of(context).copyWith(
activeTrackColor: mcolors.colorEnabled,
trackHeight: mdimens.heightSlider * 1.1,
inactiveTrackColor: mcolors.colorDisabled,
thumbColor: mcolors.colorEnabled,
thumbShape: CustomSliderThumbCircle(
thumbRadius: mdimens.heightSlider,
value: context
.select((PasswordCubit cubit) => cubit.state.length))),
child: Slider(
min: 8.0,
max: 32.0,
divisions: 20,
value: context.select(
(PasswordCubit cubit) => cubit.state.length.toDouble()),
onChanged: (double value) =>
context.read<PasswordCubit>().changeLength(value.toInt())),
),
SizedBox(
height: mdimens.defaultSpace,
),
Padding(
padding:
EdgeInsets.symmetric(horizontal: mdimens.paddingHorizontal),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
OptionButton(
title: "Uppercase",
description: "ABC",
icon: Icons.title,
active: context.select(
(PasswordCubit cubit) => cubit.state.withUppercase),
callback: () =>
context.read<PasswordCubit>().changeUppercase(),
),
SizedBox(
width: mdimens.defaultSpace,
),
OptionButton(
title: "Lowercase",
description: "abc",
icon: Icons.format_size,
active: context.select(
(PasswordCubit cubit) => cubit.state.withLowercase),
callback: () =>
context.read<PasswordCubit>().changeLowercase()),
],
),
),
SizedBox(
height: mdimens.defaultSpace,
),
Padding(
padding:
EdgeInsets.symmetric(horizontal: mdimens.paddingHorizontal),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
OptionButton(
title: "Numbers",
description: "123",
icon: Icons.looks_one,
active: context.select(
(PasswordCubit cubit) => cubit.state.withNumbers),
callback: () =>
context.read<PasswordCubit>().changeNumbers()),
SizedBox(
width: mdimens.defaultSpace,
),
OptionButton(
title: "Special",
description: "@£*",
icon: Icons.star,
active: context.select(
(PasswordCubit cubit) => cubit.state.withSpecial),
callback: () =>
context.read<PasswordCubit>().changeSpecial()),
],
),
),
Expanded(
child: Container(),
),
BlocConsumer<PasswordCubit, PasswordState>(
listener: (context, state) {},
builder: (context, state) {
return Padding(
padding:
EdgeInsets.symmetric(horizontal: mdimens.paddingHorizontal),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
mainAxisSize: MainAxisSize.max,
children: [
ActionButton(
text: "Copy",
icon: Icons.copy,
isMain: false,
callback: () => _copyToClipboard(state.password),
),
SizedBox(
height: mdimens.defaultSpace,
),
ActionButton(
text: "Generate",
icon: Icons.sync,
isMain: true,
callback: () =>
context.read<PasswordCubit>().updatePassword(),
),
],
),
);
},
),
SizedBox(
height: mdimens.hugeSpace,
),
],
),
);
}
}
| 0
|
mirrored_repositories/Wassword/lib
|
mirrored_repositories/Wassword/lib/pages/about_page.dart
|
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:wassword/styles/colors.dart' as mcolors;
import 'package:wassword/ui/about_row.dart';
class AboutPage extends StatelessWidget {
const AboutPage({Key? key}) : super(key: key);
//Open the browser with the url provided
void _launchURL(String urlToLaunch) async {
if (await canLaunchUrlString(urlToLaunch)) {
await launchUrlString(urlToLaunch);
} else {
throw 'Could not launch $urlToLaunch';
}
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
backgroundColor: mcolors.backgroundView, // status bar colorstatus ba
leading: IconButton(
color: Colors.white,
icon: const Icon(Icons.arrow_back),
onPressed: () => context.pop(),
),
title: Text(
"About",
style: GoogleFonts.roboto(
color: mcolors.colorTextLight,
),
),
),
body: ListView(
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
const SizedBox(
height: 8,
),
ListTile(
title: Text(
"DEVELOPER",
textAlign: TextAlign.left,
style:
TextStyle(fontSize: 14, color: mcolors.colorTextLight),
),
),
AboutRow(
icon: Icons.language,
title: "AlbertoBonacina.com",
subtitle: "Website",
callback: () {
_launchURL("https://www.albertobonacina.com/");
},
),
AboutRow(
icon: Icons.code,
title: "@polilluminato",
subtitle: "Github",
callback: () {
_launchURL("https://www.github.com/polilluminato");
},
),
AboutRow(
icon: Icons.campaign,
title: "@polilluminato",
subtitle: "Twitter",
callback: () {
_launchURL("https://www.twitter.com/polilluminato");
},
),
AboutRow(
icon: Icons.business,
title: "bonacinaalberto",
subtitle: "Linkedin",
callback: () {
_launchURL("https://www.linkedin.com/in/bonacinaalberto");
},
),
],
),
],
),
);
}
| 0
|
mirrored_repositories/Wassword/lib
|
mirrored_repositories/Wassword/lib/styles/dimens.dart
|
double roundedCorner = 20;
double paddingButtonBig = 20;
double paddingButton = 16;
double paddingHorizontal = 16;
double defaultSpace = 16;
double hugeSpace = 32;
double heightSlider = 16;
| 0
|
mirrored_repositories/Wassword/lib
|
mirrored_repositories/Wassword/lib/styles/colors.dart
|
import 'package:flutter/material.dart';
Color backgroundView = const Color(0xFF1F1F1F);
Color colorWhite = const Color(0xFFFFFFFF);
Color colorBlack = const Color(0xFF000000);
Color colorLightGrey = const Color(0xFFAAACAB);
Color colorEnabled = const Color(0xFF7CC4FC);
Color colorDisabled = const Color(0xFF2A2A2A);
Color colorTextLight = const Color(0xFFEEEEEE);
Color colorTextLightDark = const Color(0xFFEEEEEE);
Color colorTextDark = const Color(0xFF212121);
Color colorTextDarkLight = const Color(0xFF565656);
Color colorMainButton = const Color(0xFF7CC4FC);
Color colorSecondaryButton = const Color(0xFFaeb6de);
| 0
|
mirrored_repositories/Wassword/lib
|
mirrored_repositories/Wassword/lib/utils/password_generator.dart
|
import 'dart:math';
/*
* @desc Function to generate passwords based on some criteria
* @param bool isWithLetters: password must contain letters
* @param bool isWithUppercase: password must contain uppercase letters
* @param bool isWithNumbers: password must contain numbers
* @param bool isWithSpecial: password must contain special chars
* @param int _numberCharPassword: password length
* @return string: new password
*/
String generatePassword(
{required bool isWithLowercase,
required bool isWithUppercase,
required bool isWithNumbers,
required bool isWithSpecial,
required int numberCharPassword}) {
String _lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz";
String _upperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String _numbers = "0123456789";
String _special = "@#=+!£\$%&?[](){}-_";
String _allowedChars = "";
_allowedChars += (isWithLowercase ? _lowerCaseLetters : '');
_allowedChars += (isWithUppercase ? _upperCaseLetters : '');
_allowedChars += (isWithNumbers ? _numbers : '');
_allowedChars += (isWithSpecial ? _special : '');
if (_allowedChars.length == 0) {
return '';
}
//If I can create a password because I've got some char to use
int i = 0;
String _result = "";
while (i < numberCharPassword) {
//https://stackoverflow.com/a/28614409/7483183
int randomInt = Random.secure().nextInt(_allowedChars.length);
_result += _allowedChars[randomInt];
i++;
}
return _result;
}
| 0
|
mirrored_repositories/Wassword/lib
|
mirrored_repositories/Wassword/lib/cubit/password_cubit.dart
|
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wassword/utils/password_generator.dart';
part 'password_state.dart';
class PasswordCubit extends Cubit<PasswordState> {
PasswordCubit()
: super(
PasswordState(
withLowercase: true,
withUppercase: false,
withNumbers: false,
withSpecial: false,
length: 8,
password: "password"),
);
void updatePassword(){
emit(
PasswordState(
withLowercase: state.withLowercase,
withUppercase: state.withUppercase,
withNumbers: state.withNumbers,
withSpecial: state.withSpecial,
length: state.length,
password: generateNewPassword(state.withLowercase, state.withUppercase,
state.withNumbers, state.withSpecial, state.length),
),
);
}
void changeLowercase() {
emit(
PasswordState(
withLowercase: !state.withLowercase,
withUppercase: state.withUppercase,
withNumbers: state.withNumbers,
withSpecial: state.withSpecial,
length: state.length,
password: generateNewPassword(!state.withLowercase, state.withUppercase,
state.withNumbers, state.withSpecial, state.length),
),
);
}
void changeUppercase() {
emit(
PasswordState(
withLowercase: state.withLowercase,
withUppercase: !state.withUppercase,
withNumbers: state.withNumbers,
withSpecial: state.withSpecial,
length: state.length,
password: generateNewPassword(state.withLowercase, !state.withUppercase,
state.withNumbers, state.withSpecial, state.length),
),
);
}
void changeNumbers() {
emit(
PasswordState(
withLowercase: state.withLowercase,
withUppercase: state.withUppercase,
withNumbers: !state.withNumbers,
withSpecial: state.withSpecial,
length: state.length,
password: generateNewPassword(state.withLowercase, state.withUppercase,
!state.withNumbers, state.withSpecial, state.length),
),
);
}
void changeSpecial() {
emit(
PasswordState(
withLowercase: state.withLowercase,
withUppercase: state.withUppercase,
withNumbers: state.withNumbers,
withSpecial: !state.withSpecial,
length: state.length,
password: generateNewPassword(state.withLowercase, state.withUppercase,
state.withNumbers, !state.withSpecial, state.length),
),
);
}
void changeLength(int newLength) {
emit(
PasswordState(
withLowercase: state.withLowercase,
withUppercase: state.withUppercase,
withNumbers: state.withNumbers,
withSpecial: state.withSpecial,
length: newLength,
password: generateNewPassword(state.withLowercase, state.withUppercase,
state.withNumbers, state.withSpecial, newLength),
),
);
}
String generateNewPassword(bool withLowercase, bool withUppercase,
bool withNumbers, bool withSpecial, int length) {
return generatePassword(
isWithLowercase: withLowercase,
isWithUppercase: withUppercase,
isWithNumbers: withNumbers,
isWithSpecial: withSpecial,
numberCharPassword: length);
}
}
| 0
|
mirrored_repositories/Wassword/lib
|
mirrored_repositories/Wassword/lib/cubit/password_state.dart
|
part of 'password_cubit.dart';
abstract class MyPasswordState extends Equatable {
const MyPasswordState();
}
class PasswordState extends MyPasswordState {
final bool withLowercase;
final bool withUppercase;
final bool withNumbers;
final bool withSpecial;
final int length;
final String password;
const PasswordState(
{required this.withLowercase,
required this.withUppercase,
required this.withNumbers,
required this.withSpecial,
required this.length,
required this.password});
@override
List<Object> get props => [
withLowercase,
withUppercase,
withNumbers,
withSpecial,
length,
password
];
}
| 0
|
mirrored_repositories/Wassword/lib
|
mirrored_repositories/Wassword/lib/ui/about_row.dart
|
import 'package:flutter/material.dart';
import 'package:wassword/styles/colors.dart' as mcolors;
import 'package:wassword/styles/dimens.dart' as mdimens;
class AboutRow extends StatelessWidget {
const AboutRow(
{Key? key,
required this.title,
required this.subtitle,
required this.icon,
required this.callback})
: super(key: key);
final String title;
final String subtitle;
final IconData icon;
final VoidCallback callback;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: callback,
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
height: 80,
decoration: BoxDecoration(
color: mcolors.colorDisabled,
borderRadius: BorderRadius.all(
Radius.circular(mdimens.roundedCorner),
),
),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Icon(
icon,
size: 32,
color: mcolors.colorTextLight,
),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(
fontWeight: FontWeight.w600,
color: mcolors.colorTextLight,
),
),
const SizedBox(
height: 6,
),
Text(
subtitle,
style: TextStyle(
fontWeight: FontWeight.w400,
color: mcolors.colorTextLightDark,
),
)
])
],
),
),
);
// return ListTile(
// leading: Icon(
// icon,
// color: mcolors.colorTextLight,
// size: 23,
// ),
// title: Text(
// subtitle,
// style: TextStyle(color: mcolors.colorTextLight, fontSize: 14),
// ),
// onTap: callback,
// );
}
}
| 0
|
mirrored_repositories/Wassword/lib
|
mirrored_repositories/Wassword/lib/ui/option_button.dart
|
import 'package:flutter/material.dart';
import 'package:wassword/styles/colors.dart' as mcolors;
import 'package:wassword/styles/dimens.dart' as mdimens;
class OptionButton extends StatelessWidget {
const OptionButton({
Key? key,
required this.title,
required this.description,
required this.icon,
required this.active,
required this.callback,
}) : super(key: key);
final String title;
final String description;
final IconData icon;
final bool active;
final VoidCallback callback;
@override
Widget build(BuildContext context) {
return Expanded(
child: GestureDetector(
onTap: callback,
child: Container(
height: 85,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(mdimens.roundedCorner),
color: active ? mcolors.colorEnabled : mcolors.colorDisabled,
),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(left: 16, right: 12),
child: Icon(
icon,
size: 24,
color:
active ? mcolors.colorTextDark : mcolors.colorTextLight,
),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
color: active
? mcolors.colorTextDark
: mcolors.colorTextLight,
),
),
const SizedBox(
height: 6,
),
Text(
description,
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w400,
color: active
? mcolors.colorTextDark
: mcolors.colorTextLight,
),
)
],
)
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/Wassword/lib
|
mirrored_repositories/Wassword/lib/ui/custom_slider_thumb_circle.dart
|
import 'package:flutter/material.dart';
import 'package:wassword/styles/colors.dart' as mcolors;
//https://medium.com/flutter-community/flutter-sliders-demystified-4b3ea65879c
class CustomSliderThumbCircle extends SliderComponentShape {
final double thumbRadius;
final int value;
final int min;
final int max;
const CustomSliderThumbCircle({
required this.thumbRadius,
required this.value,
this.min = 0,
this.max = 10,
});
@override
Size getPreferredSize(bool isEnabled, bool isDiscrete) {
return Size.fromRadius(thumbRadius);
}
@override
void paint(
PaintingContext context,
Offset center, {
Animation<double>? activationAnimation,
Animation<double>? enableAnimation,
bool? isDiscrete,
TextPainter? labelPainter,
RenderBox? parentBox,
SliderThemeData? sliderTheme,
TextDirection? textDirection,
double? value,
double? textScaleFactor,
Size? sizeWithOverflow,
}) {
final Canvas canvas = context.canvas;
final paint = Paint()
..color = mcolors.colorEnabled //Thumb Background Color
..style = PaintingStyle.fill;
TextSpan span = TextSpan(
style: TextStyle(
fontSize: thumbRadius,
fontWeight: FontWeight.w700,
color: mcolors.colorTextDark, //Text Color of Value on Thumb
),
text: getValue(this.value.toDouble()),
);
TextPainter tp = TextPainter(
text: span,
textAlign: TextAlign.center,
textDirection: TextDirection.ltr);
tp.layout();
Offset textCenter =
Offset(center.dx - (tp.width / 2), center.dy - (tp.height / 2));
canvas.drawCircle(center, thumbRadius * 1.1, paint);
tp.paint(canvas, textCenter);
}
String getValue(double value) {
return ((min + (max - min) * value) / 10).round().toString();
}
}
| 0
|
mirrored_repositories/Wassword/lib
|
mirrored_repositories/Wassword/lib/ui/action_button.dart
|
import 'package:flutter/material.dart';
import 'package:wassword/styles/colors.dart' as mcolors;
import 'package:wassword/styles/dimens.dart' as mdimens;
class ActionButton extends StatelessWidget {
const ActionButton({
Key? key,
required this.text,
required this.icon,
required this.callback,
required this.isMain,
}) : super(key: key);
final String text;
final IconData icon;
final VoidCallback callback;
final bool isMain;
final double actionButtonSizeBig = 56;
final double actionButtonSizeSmall = 44;
@override
Widget build(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
return GestureDetector(
onTap: callback,
child: Container(
height: isMain ? actionButtonSizeBig : actionButtonSizeSmall,
width: screenWidth * .7,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(mdimens.roundedCorner),
color: isMain ? mcolors.colorMainButton : mcolors.colorDisabled,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
icon,
color: isMain ? mcolors.colorTextDark : mcolors.colorTextLight,
size: isMain
? actionButtonSizeBig / 2
: actionButtonSizeSmall / 2.5,
),
SizedBox(
width: mdimens.defaultSpace,
),
Text(
text,
style: TextStyle(
fontSize: isMain ? 18 : 16,
color:
isMain ? mcolors.colorTextDark : mcolors.colorTextLight),
)
],
),
),
);
}
}
| 0
|
mirrored_repositories/MealsApp
|
mirrored_repositories/MealsApp/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:meals_app/data/dummy_meals.dart';
import 'package:meals_app/screens/categories_meals_screen.dart';
import 'package:meals_app/screens/filters_screen.dart';
import 'package:meals_app/screens/meal_detail_screen.dart';
import 'package:meals_app/screens/tabs_screen.dart';
import 'package:meals_app/util/constants.dart';
import 'package:meals_app/util/dimens.dart';
import 'models/meal.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Map<String, bool> _filters = {
gluten: false,
lactose: false,
vegan: false,
vegetarian: false,
};
List<Meal> _availableMeals = dummyMeals;
final List<Meal> _favoritedMeals = [];
void _setFilters(Map<String, bool> filterData) {
setState(() {
_filters = filterData;
_availableMeals = dummyMeals.where((meal) {
if (_filters[gluten]! && !meal.isGlutenFree) {
return false;
}
if (_filters[lactose]! && !meal.isLactoseFree) {
return false;
}
if (_filters[vegan]! && !meal.isVegan) {
return false;
}
if (_filters[vegetarian]! && !meal.isVegetarian) {
return false;
}
return true;
}).toList();
});
}
void _toggleFavorite(String id) {
final existingIndex = _favoritedMeals.indexWhere((meal) => meal.id == id);
if (existingIndex >= 0) {
setState(() {
_favoritedMeals.removeAt(existingIndex);
});
} else {
setState(() {
_favoritedMeals.add(dummyMeals.firstWhere((meal) => meal.id == id));
});
}
}
bool isMealFavorite(String id) {
return _favoritedMeals.any((meal) => meal.id == id);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: appName,
theme: ThemeData(
colorScheme: const ColorScheme.light(
primary: Colors.pinkAccent,
secondary: Colors.amber,
),
canvasColor: const Color.fromRGBO(255, 254, 229, 1),
fontFamily: raleway,
indicatorColor: Colors.amberAccent,
textTheme: ThemeData().textTheme.copyWith(
bodyMedium: const TextStyle(color: Color.fromRGBO(20, 51, 51, 1)),
bodySmall: const TextStyle(color: Color.fromRGBO(20, 51, 51, 1)),
titleMedium: const TextStyle(
fontSize: textThemeFontSize,
fontFamily: robotoCondensed,
fontWeight: FontWeight.bold,
),
),
),
//home: const CategoriesScreen(),
initialRoute: TabsScreen.routeName,
debugShowCheckedModeBanner: false,
routes: {
TabsScreen.routeName: (context) =>
TabsScreen(favoriteMeals: _favoritedMeals),
CategoriesMealsScreen.routeName: (context) =>
CategoriesMealsScreen(availableMeals: _availableMeals),
MealDetailsScreen.routeName: (context) => MealDetailsScreen(
toggleFavorite: _toggleFavorite, isFavorite: isMealFavorite),
FiltersScreen.routeName: (context) =>
FiltersScreen(saveFilters: _setFilters, filters: _filters),
},
);
}
}
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/widgets/meal_item.dart
|
import 'package:flutter/material.dart';
import 'package:meals_app/models/meal.dart';
import 'package:meals_app/screens/meal_detail_screen.dart';
import 'package:meals_app/util/dimens.dart';
class MealItem extends StatelessWidget {
final String id;
final String title;
final String imageUrl;
final int duration;
final Complexity complexity;
final Affordability affordability;
final Function? removeItem;
const MealItem({
Key? key,
required this.id,
required this.title,
required this.imageUrl,
required this.duration,
required this.complexity,
required this.affordability,
required this.removeItem,
}) : super(key: key);
String get complexityText {
switch (complexity) {
case Complexity.simple:
return "Simple";
case Complexity.challenging:
return "Challenging";
case Complexity.hard:
return 'Hard';
default:
return "Unknown";
}
}
String get affordabilityText {
switch (affordability) {
case Affordability.affordable:
return "Affordable";
case Affordability.pricey:
return "Pricey";
case Affordability.luxurious:
return "Luxurious";
default:
return "Unknown";
}
}
void selectMeal(BuildContext context) {
Navigator.of(context)
.pushNamed(
MealDetailsScreen.routeName,
arguments: id,
)
.then((result) {
if (result != null && removeItem != null) {
removeItem!(result);
}
});
}
Row buildRow(
String text,
IconData icon,
) {
return Row(
children: [
Icon(icon),
const SizedBox(
width: mealItemBuildRowSizedBoxWidth,
),
Text(text)
],
);
}
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () => selectMeal(context),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: mealItemCardBorderRadius,
),
elevation: mealItemCardElevation,
margin: mealItemCardMargin,
child: Column(
children: [
Stack(
children: [
Hero(
tag: imageUrl,
child: ClipRRect(
borderRadius: mealItemClipRRectBorderRadius,
child: Image.network(
imageUrl,
height: mealItemImageHeight,
width: double.infinity,
fit: BoxFit.cover,
),
),
),
Positioned(
bottom: mealItemBottomPositioned,
right: mealItemRightPositioned,
child: Container(
width: mealItemPositionedContainerWidth,
color: Colors.black54,
padding: mealItemPositionedContainerPadding,
child: Text(
title,
style: const TextStyle(
fontSize: mealItemPositionedTextSize,
color: Colors.white,
),
softWrap: true,
overflow: TextOverflow.fade,
),
),
)
],
),
Padding(
padding: mealItemPaddingWidgetPadding,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
buildRow("$duration min", Icons.schedule),
buildRow(complexityText, Icons.work),
buildRow(affordabilityText, Icons.attach_money),
],
),
)
],
),
),
);
}
}
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/widgets/main_drawer.dart
|
import 'package:flutter/material.dart';
import 'package:meals_app/screens/filters_screen.dart';
import 'package:meals_app/util/constants.dart';
import 'package:meals_app/util/dimens.dart';
class MainDrawer extends StatelessWidget {
const MainDrawer({Key? key}) : super(key: key);
Widget buildDrawerList(
IconData? icon,
String title,
Function() onTap,
) {
return ListTile(
leading: Icon(
icon,
size: mainDrawerListTitleIconSize,
),
title: Text(
title,
style: const TextStyle(
fontFamily: robotoCondensed,
fontSize: mainDrawerListTitleFontSize,
fontWeight: FontWeight.bold,
),
),
onTap: onTap,
);
}
@override
Widget build(BuildContext context) {
return Drawer(
child: Column(
children: [
Container(
height: mainDrawerContainerHeight,
width: double.infinity,
padding: mainDrawerContainerPadding,
alignment: Alignment.centerLeft,
color: Theme.of(context).colorScheme.secondary,
child: Text(
cookingUp,
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: mainDrawerContainerTextSize,
color: Theme.of(context).colorScheme.primary),
),
),
const SizedBox(height: mainDrawerSizedBoxHeight),
buildDrawerList(Icons.restaurant, meals, () {
Navigator.of(context).pushReplacementNamed('/');
}),
buildDrawerList(Icons.settings, filter, () {
Navigator.of(context).pushReplacementNamed(FiltersScreen.routeName);
})
],
),
);
}
}
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/widgets/category_item.dart
|
import 'package:flutter/material.dart';
import 'package:meals_app/screens/categories_meals_screen.dart';
import 'package:meals_app/util/constants.dart';
import 'package:meals_app/util/dimens.dart';
class CategoryItem extends StatelessWidget {
final String id;
final String title;
final Color color;
const CategoryItem(
this.id,
this.title,
this.color, {
Key? key,
}) : super(key: key);
void selectCategory(BuildContext context) {
Navigator.of(context).pushNamed(
CategoriesMealsScreen.routeName,
arguments: {
navArgId: id,
navArgTitle: title,
},
);
}
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () => selectCategory(context),
splashColor: Theme.of(context).primaryColor,
borderRadius: categoryItemBorderRadius,
child: Container(
padding: categoryItemPadding,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [color.withOpacity(0.7), color],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: categoryItemBorderRadius),
child: Text(
title,
style: Theme.of(context).textTheme.titleMedium,
),
),
);
}
}
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/models/meal.dart
|
enum Complexity {
simple,
challenging,
hard,
}
enum Affordability {
affordable,
pricey,
luxurious,
}
class Meal {
final String id;
final List<String> categories;
final String title;
final String imageUrl;
final List<String> ingredients;
final List<String> steps;
final int duration;
final Complexity complexity;
final Affordability affordability;
final bool isGlutenFree;
final bool isLactoseFree;
final bool isVegan;
final bool isVegetarian;
const Meal({
required this.id,
required this.categories,
required this.title,
required this.imageUrl,
required this.ingredients,
required this.steps,
required this.duration,
required this.complexity,
required this.affordability,
required this.isGlutenFree,
required this.isLactoseFree,
required this.isVegan,
required this.isVegetarian,
});
}
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/models/category.dart
|
import 'package:flutter/material.dart';
class Category {
final String id;
final String title;
final Color color;
const Category({
required this.id,
required this.title,
this.color = Colors.orange,
});
}
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/data/dummy_meals.dart
|
import '../models/meal.dart';
const dummyMeals = [
Meal(
id: 'm1',
categories: [
'c1',
'c2',
],
title: 'Spaghetti with Tomato Sauce',
affordability: Affordability.affordable,
complexity: Complexity.simple,
imageUrl:
'https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg/800px-Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg',
duration: 20,
ingredients: [
'4 Tomatoes',
'1 Tablespoon of Olive Oil',
'1 Onion',
'250g Spaghetti',
'Spices',
'Cheese (optional)'
],
steps: [
'Cut the tomatoes and the onion into small pieces.',
'Boil some water - add salt to it once it boils.',
'Put the spaghetti into the boiling water - they should be done in about 10 to 12 minutes.',
'In the meantime, heaten up some olive oil and add the cut onion.',
'After 2 minutes, add the tomato pieces, salt, pepper and your other spices.',
'The sauce will be done once the spaghetti are.',
'Feel free to add some cheese on top of the finished dish.'
],
isGlutenFree: false,
isVegan: true,
isVegetarian: true,
isLactoseFree: true,
),
Meal(
id: 'm2',
categories: [
'c2',
],
title: 'Toast Hawaii',
affordability: Affordability.affordable,
complexity: Complexity.simple,
imageUrl:
'https://cdn.pixabay.com/photo/2018/07/11/21/51/toast-3532016_1280.jpg',
duration: 10,
ingredients: [
'1 Slice White Bread',
'1 Slice Ham',
'1 Slice Pineapple',
'1-2 Slices of Cheese',
'Butter'
],
steps: [
'Butter one side of the white bread',
'Layer ham, the pineapple and cheese on the white bread',
'Bake the toast for round about 10 minutes in the oven at 200°C'
],
isGlutenFree: false,
isVegan: false,
isVegetarian: false,
isLactoseFree: false,
),
Meal(
id: 'm3',
categories: [
'c2',
'c3',
],
title: 'Classic Hamburger',
affordability: Affordability.pricey,
complexity: Complexity.simple,
imageUrl:
'https://cdn.pixabay.com/photo/2014/10/23/18/05/burger-500054_1280.jpg',
duration: 45,
ingredients: [
'300g Cattle Hack',
'1 Tomato',
'1 Cucumber',
'1 Onion',
'Ketchup',
'2 Burger Buns'
],
steps: [
'Form 2 patties',
'Fry the patties for c. 4 minutes on each side',
'Quickly fry the buns for c. 1 minute on each side',
'Bruch buns with ketchup',
'Serve burger with tomato, cucumber and onion'
],
isGlutenFree: false,
isVegan: false,
isVegetarian: false,
isLactoseFree: true,
),
Meal(
id: 'm4',
categories: [
'c4',
],
title: 'Wiener Schnitzel',
affordability: Affordability.luxurious,
complexity: Complexity.challenging,
imageUrl:
'https://cdn.pixabay.com/photo/2018/03/31/19/29/schnitzel-3279045_1280.jpg',
duration: 60,
ingredients: [
'8 Veal Cutlets',
'4 Eggs',
'200g Bread Crumbs',
'100g Flour',
'300ml Butter',
'100g Vegetable Oil',
'Salt',
'Lemon Slices'
],
steps: [
'Tenderize the veal to about 2–4mm, and salt on both sides.',
'On a flat plate, stir the eggs briefly with a fork.',
'Lightly coat the cutlets in flour then dip into the egg, and finally, coat in breadcrumbs.',
'Heat the butter and oil in a large pan (allow the fat to get very hot) and fry the schnitzels until golden brown on both sides.',
'Make sure to toss the pan regularly so that the schnitzels are surrounded by oil and the crumbing becomes ‘fluffy’.',
'Remove, and drain on kitchen paper. Fry the parsley in the remaining oil and drain.',
'Place the schnitzels on awarmed plate and serve garnishedwith parsley and slices of lemon.'
],
isGlutenFree: false,
isVegan: false,
isVegetarian: false,
isLactoseFree: false,
),
Meal(
id: 'm5',
categories: [
'c2',
'c5',
'c10',
],
title: 'Salad with Smoked Salmon',
affordability: Affordability.luxurious,
complexity: Complexity.simple,
imageUrl:
'https://cdn.pixabay.com/photo/2016/10/25/13/29/smoked-salmon-salad-1768890_1280.jpg',
duration: 15,
ingredients: [
'Arugula',
'Lamb\'s Lettuce',
'Parsley',
'Fennel',
'200g Smoked Salmon',
'Mustard',
'Balsamic Vinegar',
'Olive Oil',
'Salt and Pepper'
],
steps: [
'Wash and cut salad and herbs',
'Dice the salmon',
'Process mustard, vinegar and olive oil into a dessing',
'Prepare the salad',
'Add salmon cubes and dressing'
],
isGlutenFree: true,
isVegan: false,
isVegetarian: true,
isLactoseFree: true,
),
Meal(
id: 'm6',
categories: [
'c6',
'c10',
],
title: 'Delicious Orange Mousse',
affordability: Affordability.affordable,
complexity: Complexity.hard,
imageUrl:
'https://cdn.pixabay.com/photo/2017/05/01/05/18/pastry-2274750_1280.jpg',
duration: 240,
ingredients: [
'4 Sheets of Gelatine',
'150ml Orange Juice',
'80g Sugar',
'300g Yoghurt',
'200g Cream',
'Orange Peel',
],
steps: [
'Dissolve gelatine in pot',
'Add orange juice and sugar',
'Take pot off the stove',
'Add 2 tablespoons of yoghurt',
'Stir gelatin under remaining yoghurt',
'Cool everything down in the refrigerator',
'Whip the cream and lift it under die orange mass',
'Cool down again for at least 4 hours',
'Serve with orange peel',
],
isGlutenFree: true,
isVegan: false,
isVegetarian: true,
isLactoseFree: false,
),
Meal(
id: 'm7',
categories: [
'c7',
],
title: 'Pancakes',
affordability: Affordability.affordable,
complexity: Complexity.simple,
imageUrl:
'https://cdn.pixabay.com/photo/2018/07/10/21/23/pancake-3529653_1280.jpg',
duration: 20,
ingredients: [
'1 1/2 Cups all-purpose Flour',
'3 1/2 Teaspoons Baking Powder',
'1 Teaspoon Salt',
'1 Tablespoon White Sugar',
'1 1/4 cups Milk',
'1 Egg',
'3 Tablespoons Butter, melted',
],
steps: [
'In a large bowl, sift together the flour, baking powder, salt and sugar.',
'Make a well in the center and pour in the milk, egg and melted butter; mix until smooth.',
'Heat a lightly oiled griddle or frying pan over medium high heat.',
'Pour or scoop the batter onto the griddle, using approximately 1/4 cup for each pancake. Brown on both sides and serve hot.'
],
isGlutenFree: true,
isVegan: false,
isVegetarian: true,
isLactoseFree: false,
),
Meal(
id: 'm8',
categories: [
'c8',
],
title: 'Creamy Indian Chicken Curry',
affordability: Affordability.pricey,
complexity: Complexity.challenging,
imageUrl:
'https://cdn.pixabay.com/photo/2018/06/18/16/05/indian-food-3482749_1280.jpg',
duration: 35,
ingredients: [
'4 Chicken Breasts',
'1 Onion',
'2 Cloves of Garlic',
'1 Piece of Ginger',
'4 Tablespoons Almonds',
'1 Teaspoon Cayenne Pepper',
'500ml Coconut Milk',
],
steps: [
'Slice and fry the chicken breast',
'Process onion, garlic and ginger into paste and sauté everything',
'Add spices and stir fry',
'Add chicken breast + 250ml of water and cook everything for 10 minutes',
'Add coconut milk',
'Serve with rice'
],
isGlutenFree: true,
isVegan: false,
isVegetarian: false,
isLactoseFree: true,
),
Meal(
id: 'm9',
categories: [
'c9',
],
title: 'Chocolate Souffle',
affordability: Affordability.affordable,
complexity: Complexity.hard,
imageUrl:
'https://cdn.pixabay.com/photo/2014/08/07/21/07/souffle-412785_1280.jpg',
duration: 45,
ingredients: [
'1 Teaspoon melted Butter',
'2 Tablespoons white Sugar',
'2 Ounces 70% dark Chocolate, broken into pieces',
'1 Tablespoon Butter',
'1 Tablespoon all-purpose Flour',
'4 1/3 tablespoons cold Milk',
'1 Pinch Salt',
'1 Pinch Cayenne Pepper',
'1 Large Egg Yolk',
'2 Large Egg Whites',
'1 Pinch Cream of Tartar',
'1 Tablespoon white Sugar',
],
steps: [
'Preheat oven to 190°C. Line a rimmed baking sheet with parchment paper.',
'Brush bottom and sides of 2 ramekins lightly with 1 teaspoon melted butter; cover bottom and sides right up to the rim.',
'Add 1 tablespoon white sugar to ramekins. Rotate ramekins until sugar coats all surfaces.',
'Place chocolate pieces in a metal mixing bowl.',
'Place bowl over a pan of about 3 cups hot water over low heat.',
'Melt 1 tablespoon butter in a skillet over medium heat. Sprinkle in flour. Whisk until flour is incorporated into butter and mixture thickens.',
'Whisk in cold milk until mixture becomes smooth and thickens. Transfer mixture to bowl with melted chocolate.',
'Add salt and cayenne pepper. Mix together thoroughly. Add egg yolk and mix to combine.',
'Leave bowl above the hot (not simmering) water to keep chocolate warm while you whip the egg whites.',
'Place 2 egg whites in a mixing bowl; add cream of tartar. Whisk until mixture begins to thicken and a drizzle from the whisk stays on the surface about 1 second before disappearing into the mix.',
'Add 1/3 of sugar and whisk in. Whisk in a bit more sugar about 15 seconds.',
'whisk in the rest of the sugar. Continue whisking until mixture is about as thick as shaving cream and holds soft peaks, 3 to 5 minutes.',
'Transfer a little less than half of egg whites to chocolate.',
'Mix until egg whites are thoroughly incorporated into the chocolate.',
'Add the rest of the egg whites; gently fold into the chocolate with a spatula, lifting from the bottom and folding over.',
'Stop mixing after the egg white disappears. Divide mixture between 2 prepared ramekins. Place ramekins on prepared baking sheet.',
'Bake in preheated oven until scuffles are puffed and have risen above the top of the rims, 12 to 15 minutes.',
],
isGlutenFree: true,
isVegan: false,
isVegetarian: true,
isLactoseFree: false,
),
Meal(
id: 'm10',
categories: [
'c2',
'c5',
'c10',
],
title: 'Asparagus Salad with Cherry Tomatoes',
affordability: Affordability.luxurious,
complexity: Complexity.simple,
imageUrl:
'https://cdn.pixabay.com/photo/2018/04/09/18/26/asparagus-3304997_1280.jpg',
duration: 30,
ingredients: [
'White and Green Asparagus',
'30g Pine Nuts',
'300g Cherry Tomatoes',
'Salad',
'Salt, Pepper and Olive Oil'
],
steps: [
'Wash, peel and cut the asparagus',
'Cook in salted water',
'Salt and pepper the asparagus',
'Roast the pine nuts',
'Halve the tomatoes',
'Mix with asparagus, salad and dressing',
'Serve with Baguette'
],
isGlutenFree: true,
isVegan: true,
isVegetarian: true,
isLactoseFree: true,
),
];
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/data/dummy_categories.dart
|
import 'package:flutter/material.dart';
import '../models/category.dart';
const dummyCategories = [
Category(
id: 'c1',
title: 'Italian',
color: Colors.purple,
),
Category(
id: 'c2',
title: 'Quick & Easy',
color: Colors.red,
),
Category(
id: 'c3',
title: 'Hamburgers',
color: Colors.orange,
),
Category(
id: 'c4',
title: 'German',
color: Colors.amber,
),
Category(
id: 'c5',
title: 'Light & Lovely',
color: Colors.blue,
),
Category(
id: 'c6',
title: 'Exotic',
color: Colors.green,
),
Category(
id: 'c7',
title: 'Breakfast',
color: Colors.lightBlue,
),
Category(
id: 'c8',
title: 'Asian',
color: Colors.lightGreen,
),
Category(
id: 'c9',
title: 'French',
color: Colors.pink,
),
Category(
id: 'c10',
title: 'Summer',
color: Colors.teal,
),
];
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/util/dimens.dart
|
import 'package:flutter/material.dart';
// GridView dimensions
const gridViewPaddingAll = EdgeInsets.all(25);
const gridViewDelegate = SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
childAspectRatio: 1.5,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
);
// FilterScreen
const filterScreenContainerPadding = EdgeInsets.all(10);
// MealDetail screen
const popDelay = 2;
const sectionTitleMargin = EdgeInsets.symmetric(vertical: 10);
var mealDetailContainerBorderRadius = BorderRadius.circular(10);
const mealDetailContainerMargin = EdgeInsets.all(10);
const mealDetailContainerPadding = EdgeInsets.all(10);
const mealDetailIngredientCardPadding = EdgeInsets.symmetric(
vertical: 5,
horizontal: 10,
);
// CategoryItem
var categoryItemBorderRadius = BorderRadius.circular(15);
const categoryItemPadding = EdgeInsets.all(15);
// MainDrawer
const mainDrawerContainerPadding = EdgeInsets.all(20);
const double mainDrawerContainerHeight = 120;
const double mainDrawerSizedBoxHeight = 20;
const double mainDrawerListTitleFontSize = 20;
const double mainDrawerContainerTextSize = 30;
const double mainDrawerListTitleIconSize = 26;
// MealItem
var mealItemCardBorderRadius = BorderRadius.circular(15);
const double mealItemCardElevation = 5;
const mealItemCardMargin = EdgeInsets.all(10);
var mealItemClipRRectBorderRadius = const BorderRadius.only(
topLeft: Radius.circular(15),
topRight: Radius.circular(15),
);
const double mealItemImageHeight = 250;
const double mealItemBottomPositioned = 20;
const double mealItemRightPositioned = 10;
const double mealItemPositionedContainerWidth = 300;
const mealItemPositionedContainerPadding = EdgeInsets.symmetric(
vertical: 5,
horizontal: 20,
);
const mealItemPaddingWidgetPadding = EdgeInsets.all(20);
const double mealItemBuildRowSizedBoxWidth = 6;
const double mealItemPositionedTextSize = 26;
const double textThemeFontSize = 20;
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/util/constants.dart
|
const appName = 'DeliMeals';
const navArgId = 'id';
const navArgTitle = 'title';
const noFavoriteMessage = 'You have no favorites yet - add some!';
const gluten = 'Gluten';
const vegetarian = 'Vegetarian';
const vegan = 'Vegan';
const lactose = 'Lactose';
const yourFiltersText = "Your Filters";
const adjustMealSelectionText = 'Adjust your meal selection';
const glutenFree = "Gluten-free";
const glutenFreeDesc = 'Only include gluten-free meals.';
const lactoseFree = "Lactose-free";
const lactoseFreeDesc = 'Only include lactose-free meals.';
const vegetarianDesc = 'Only include vegetarian meals.';
const veganDesc = 'Only include vegan meals.';
const ingredients = 'Ingredients';
const steps = 'Steps';
const page = "page";
const title = "title";
const categories = 'Categories';
const favorite = 'Favorites';
const yourFavoritesText = 'Your Favorite';
const cookingUp = 'Cooking Up!';
const meals = 'Meals';
const filter = 'Filter';
const robotoCondensed = 'RobotoCondensed';
const raleway = 'Raleway';
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/screens/favorites_screen.dart
|
import 'package:flutter/material.dart';
import 'package:meals_app/util/constants.dart';
import '../models/meal.dart';
import '../widgets/meal_item.dart';
class FavoritesScreen extends StatefulWidget {
final List<Meal> favoriteMeals;
const FavoritesScreen({Key? key, required this.favoriteMeals})
: super(key: key);
@override
State<FavoritesScreen> createState() => _FavoritesScreenState();
}
class _FavoritesScreenState extends State<FavoritesScreen> {
void _removeMeal(String id) {
setState(() {
widget.favoriteMeals.removeWhere((meal) => meal.id == id);
});
}
@override
Widget build(BuildContext context) {
if (widget.favoriteMeals.isEmpty) {
return const Center(
child: Text(noFavoriteMessage),
);
} else {
return ListView.builder(
itemBuilder: (context, index) {
final meal = widget.favoriteMeals[index];
return MealItem(
id: meal.id,
title: meal.title,
imageUrl: meal.imageUrl,
affordability: meal.affordability,
complexity: meal.complexity,
duration: meal.duration,
removeItem: _removeMeal,
);
},
itemCount: widget.favoriteMeals.length,
);
}
}
}
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/screens/categories_meals_screen.dart
|
import 'package:flutter/material.dart';
import 'package:meals_app/util/constants.dart';
import 'package:meals_app/widgets/meal_item.dart';
import '../models/meal.dart';
class CategoriesMealsScreen extends StatefulWidget {
final List<Meal> availableMeals;
static const String routeName = 'categories_meals';
const CategoriesMealsScreen({
Key? key,
required this.availableMeals,
}) : super(key: key);
@override
State<CategoriesMealsScreen> createState() => _CategoriesMealsScreenState();
}
class _CategoriesMealsScreenState extends State<CategoriesMealsScreen> {
late String categoryTitle;
late List<Meal> categoryMeals;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final routeArgs =
ModalRoute
.of(context)
?.settings
.arguments as Map<String, String>;
final categoryId = routeArgs[navArgId].toString();
categoryTitle = routeArgs[navArgTitle].toString();
categoryMeals = widget.availableMeals.where((meal) {
return meal.categories.contains(categoryId);
}).toList();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(categoryTitle),
),
body: ListView.builder(
itemBuilder: (context, index) {
final meal = categoryMeals[index];
return MealItem(
id: meal.id,
title: meal.title,
imageUrl: meal.imageUrl,
affordability: meal.affordability,
complexity: meal.complexity,
duration: meal.duration,
removeItem: null,
);
},
itemCount: categoryMeals.length,
),
);
}
}
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/screens/tabs_screen.dart
|
import 'package:flutter/material.dart';
import 'package:meals_app/models/meal.dart';
import 'package:meals_app/screens/categories_screen.dart';
import 'package:meals_app/screens/favorites_screen.dart';
import 'package:meals_app/widgets/main_drawer.dart';
import '../util/constants.dart';
class TabsScreen extends StatefulWidget {
static const routeName = '/';
final List<Meal> favoriteMeals;
const TabsScreen({Key? key, required this.favoriteMeals}) : super(key: key);
@override
State<TabsScreen> createState() => _TabsScreenState();
}
class _TabsScreenState extends State<TabsScreen> {
late List<Map<String, Object>> _pages;
@override
void initState() {
super.initState();
_pages = [
{
page: const CategoriesScreen(),
title: categories,
},
{
page: FavoritesScreen(favoriteMeals: widget.favoriteMeals),
title: yourFavoritesText,
}
];
}
int _selectedPageIndex = 0;
void _selectPage(int index) {
setState(() {
_selectedPageIndex = index;
});
}
@override
Widget build(BuildContext context) {
var selectedPage = _pages[_selectedPageIndex];
return Scaffold(
appBar: AppBar(
title: Text(selectedPage[title].toString()),
),
bottomNavigationBar: BottomNavigationBar(
onTap: _selectPage,
backgroundColor: Theme.of(context).colorScheme.primary,
unselectedItemColor: Colors.white,
selectedItemColor: Theme.of(context).colorScheme.secondary,
currentIndex: _selectedPageIndex,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: const Icon(Icons.category),
label: categories,
// Add separate backgroundColor for BottomNavigationBarItem
// if type: BottomNavigationBarType.shifting
backgroundColor: Theme.of(context).colorScheme.primary,
),
BottomNavigationBarItem(
icon: const Icon(Icons.star),
label: favorite,
backgroundColor: Theme.of(context).colorScheme.primary,
),
],
),
body: selectedPage[page] as Widget,
drawer: const MainDrawer(),
);
}
}
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/screens/meal_detail_screen.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:meals_app/util/constants.dart';
import 'package:meals_app/util/dimens.dart';
import '../data/dummy_meals.dart';
class MealDetailsScreen extends StatelessWidget {
static const routeName = 'meals_details';
final Function toggleFavorite;
final Function isFavorite;
const MealDetailsScreen(
{Key? key, required this.toggleFavorite, required this.isFavorite})
: super(key: key);
Widget buildSectionTitle(BuildContext context, String text) {
return Container(
margin: sectionTitleMargin,
child: Text(
text,
style: Theme.of(context).textTheme.titleMedium,
),
);
}
Widget buildContainer(MediaQueryData mediaQuery, Widget child) {
return Container(
height: mediaQuery.size.height * 0.3,
width: mediaQuery.size.width * 0.9,
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: Colors.grey),
borderRadius: mealDetailContainerBorderRadius,
),
margin: mealDetailContainerMargin,
padding: mealDetailContainerPadding,
child: child,
);
}
@override
Widget build(BuildContext context) {
final mealId = ModalRoute.of(context)?.settings.arguments as String;
final selectedMeal = dummyMeals.firstWhere((meal) => meal.id == mealId);
final mediaQuery = MediaQuery.of(context);
return Scaffold(
appBar: AppBar(
title: Text(selectedMeal.title),
),
body: SingleChildScrollView(
child: Column(
children: [
Hero(
tag: selectedMeal.imageUrl,
child: SizedBox(
height: mediaQuery.size.height * 0.4,
width: double.infinity,
child: Image.network(
selectedMeal.imageUrl,
fit: BoxFit.cover,
),
),
),
buildSectionTitle(context, ingredients),
buildContainer(
mediaQuery,
ListView.builder(
itemBuilder: (context, index) {
return Card(
color: Theme.of(context).colorScheme.secondary,
child: Padding(
padding: mealDetailIngredientCardPadding,
child: Text(selectedMeal.ingredients[index]),
),
);
},
itemCount: selectedMeal.ingredients.length,
),
),
buildSectionTitle(context, steps),
buildContainer(
mediaQuery,
ListView.builder(
itemBuilder: (context, index) {
return Column(
children: [
ListTile(
leading: CircleAvatar(
backgroundColor:
Theme.of(context).colorScheme.primary,
child: Text("# ${index + 1}"),
),
title: Text(selectedMeal.steps[index]),
),
const Divider()
],
);
},
itemCount: selectedMeal.steps.length,
))
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
toggleFavorite(mealId);
Timer(const Duration(seconds: popDelay), () {
Navigator.of(context).pop(mealId);
});
},
child: Icon(isFavorite(mealId) ? Icons.star : Icons.star_border),
),
);
}
}
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/screens/categories_screen.dart
|
import 'package:flutter/material.dart';
import 'package:meals_app/data/dummy_categories.dart';
import 'package:meals_app/util/dimens.dart';
import 'package:meals_app/widgets/category_item.dart';
class CategoriesScreen extends StatelessWidget {
static const String routeName = "/";
const CategoriesScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GridView(
padding: gridViewPaddingAll,
gridDelegate: gridViewDelegate,
children: dummyCategories
.map((category) => CategoryItem(
category.id,
category.title,
category.color,
))
.toList(),
);
}
}
| 0
|
mirrored_repositories/MealsApp/lib
|
mirrored_repositories/MealsApp/lib/screens/filters_screen.dart
|
import 'package:flutter/material.dart';
import 'package:meals_app/util/constants.dart';
import 'package:meals_app/util/dimens.dart';
import 'package:meals_app/widgets/main_drawer.dart';
class FiltersScreen extends StatefulWidget {
static const routeName = 'filter_screen';
final Function saveFilters;
final Map<String, bool> filters;
const FiltersScreen({
Key? key,
required this.saveFilters,
required this.filters,
}) : super(key: key);
@override
State<FiltersScreen> createState() => _FiltersScreenState();
}
class _FiltersScreenState extends State<FiltersScreen> {
var _glutenFree = false;
var _vegetarian = false;
var _vegan = false;
var _lactoseFree = false;
@override
void initState() {
super.initState();
_glutenFree = widget.filters[gluten]!;
_vegetarian = widget.filters[vegetarian]!;
_vegan = widget.filters[vegan]!;
_lactoseFree = widget.filters[lactose]!;
}
SwitchListTile buildSwitchListTile(
String title,
String subtitle,
bool currentValue,
Function(bool) updatedValue,
) {
return SwitchListTile(
activeColor: Theme.of(context).colorScheme.secondary,
value: currentValue,
onChanged: updatedValue,
title: Text(title),
subtitle: Text(subtitle),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(yourFiltersText),
actions: [
IconButton(
onPressed: () {
final filters = {
gluten: _glutenFree,
lactose: _lactoseFree,
vegan: _vegan,
vegetarian: _vegetarian,
};
widget.saveFilters(filters);
},
icon: const Icon(Icons.save),
)
],
),
drawer: const MainDrawer(),
body: Column(
children: [
Container(
padding: filterScreenContainerPadding,
child: Text(
adjustMealSelectionText,
style: Theme.of(context).textTheme.titleMedium,
),
),
Expanded(
child: ListView(
children: [
buildSwitchListTile(
glutenFree,
glutenFreeDesc,
_glutenFree,
(isGlutenFree) {
setState(() => _glutenFree = isGlutenFree);
},
),
buildSwitchListTile(
lactose,
lactoseFree,
_lactoseFree,
(isLactoseFree) {
setState(() => _lactoseFree = isLactoseFree);
},
),
buildSwitchListTile(
vegetarian,
vegetarianDesc,
_vegetarian,
(isVegetarian) {
setState(() => _vegetarian = isVegetarian);
},
),
buildSwitchListTile(
vegan,
veganDesc,
_vegan,
(isVegan) {
setState(() => _vegan = isVegan);
},
),
],
),
)
],
),
);
}
}
| 0
|
mirrored_repositories/MealsApp
|
mirrored_repositories/MealsApp/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:meals_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/MiCard
|
mirrored_repositories/MiCard/lib/main.dart
|
import 'package:flutter/material.dart';
void main() {
runApp(
MyApp()
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.teal,
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircleAvatar(
radius: 50.0,
backgroundImage: AssetImage("images/adrish.jpeg"),
),
Text(
'Adrish Bose',
style: TextStyle(
fontFamily: 'Pacifico',
fontSize: 40.0,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
Text(
'ML ENGINEER',
style: TextStyle(
fontFamily: 'Source Sans Pro',
color: Colors.teal.shade100,
fontSize: 20.0,
letterSpacing: 2.5,
fontWeight: FontWeight.bold,
),
),
Text(
'FLUTTER DEVELOPER',
style: TextStyle(
fontFamily: 'Source Sans Pro',
color: Colors.teal.shade100,
fontSize: 20.0,
letterSpacing: 2.5,
fontWeight: FontWeight.bold,
),
),
Text(
'ANDROID DEVELOPER',
style: TextStyle(
fontFamily: 'Source Sans Pro',
color: Colors.teal.shade100,
fontSize: 20.0,
letterSpacing: 2.5,
fontWeight: FontWeight.bold,
),
),
SizedBox(
height: 20.0,
width: 150.0,
child: Divider(
color: Colors.teal.shade100,
),
),
Card(
color: Colors.white,
margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Icon(
Icons.phone,
color: Colors.teal,
),
title: Text(
'+91 975-610-2345',
style: TextStyle(
color: Colors.teal.shade900,
fontFamily: 'Source Sans Pro',
fontSize: 20.0,
),
),
),
),
Card(
color: Colors.white,
margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Icon(
Icons.email,
color: Colors.teal,
),
title: Text(
'adrishbose@email.com',
style: TextStyle(
color: Colors.teal.shade900,
fontFamily: 'Source Sans Pro',
fontSize: 20.0,
),
),
),
),
Card(
color: Colors.white,
margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Icon(
Icons.location_city,
color: Colors.teal,
),
title: Text(
'Kolkata, West Bengal, India',
style: TextStyle(
color: Colors.teal.shade900,
fontFamily: 'Source Sans Pro',
fontSize: 18.0,
),
),
),
),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/flutter_Pokedex
|
mirrored_repositories/flutter_Pokedex/lib/app.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pokedex/configs/constants.dart';
import 'package:pokedex/configs/theme.dart';
import 'package:pokedex/routes.dart';
import 'package:pokedex/states/theme/theme_cubit.dart';
class PokedexApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var themeCubit = BlocProvider.of<ThemeCubit>(context, listen: true);
var isDark = themeCubit.isDark;
return MaterialApp(
color: Colors.white,
title: 'Flutter Pokedex',
theme: isDark ? Themings.darkTheme : Themings.lightTheme,
navigatorKey: AppNavigator.navigatorKey,
onGenerateRoute: AppNavigator.onGenerateRoute,
builder: (context, child) {
if (child == null) return SizedBox.shrink();
final data = MediaQuery.of(context);
final smallestSize = min(data.size.width, data.size.height);
final textScaleFactor = min(smallestSize / AppConstants.designScreenSize.width, 1.0);
return MediaQuery(
data: data.copyWith(
textScaleFactor: textScaleFactor,
),
child: child,
);
},
);
}
}
| 0
|
mirrored_repositories/flutter_Pokedex
|
mirrored_repositories/flutter_Pokedex/lib/routes.dart
|
import 'package:flutter/material.dart';
import 'package:pokedex/core/fade_page_route.dart';
import 'package:pokedex/ui/screens/home/home.dart';
import 'package:pokedex/ui/screens/items/items.dart';
import 'package:pokedex/ui/screens/pokedex/pokedex.dart';
import 'package:pokedex/ui/screens/pokemon_info/pokemon_info.dart';
import 'package:pokedex/ui/screens/splash/splash.dart';
import 'package:pokedex/ui/screens/types/type_screen.dart';
enum Routes { splash, home, pokedex, pokemonInfo, typeEffects, items }
class _Paths {
static const String splash = '/';
static const String home = '/home';
static const String pokedex = '/home/pokedex';
static const String pokemonInfo = '/home/pokemon';
static const String typeEffectsScreen = '/home/type';
static const String itemsList = '/home/items';
static const Map<Routes, String> _pathMap = {
Routes.splash: _Paths.splash,
Routes.home: _Paths.home,
Routes.pokedex: _Paths.pokedex,
Routes.pokemonInfo: _Paths.pokemonInfo,
Routes.typeEffects: _Paths.typeEffectsScreen,
Routes.items: _Paths.itemsList
};
static String of(Routes route) => _pathMap[route] ?? splash;
}
class AppNavigator {
static GlobalKey<NavigatorState> navigatorKey = GlobalKey();
static Route onGenerateRoute(RouteSettings settings) {
switch (settings.name) {
case _Paths.splash:
return FadeRoute(page: SplashScreen());
case _Paths.pokedex:
return FadeRoute(page: PokedexScreen());
case _Paths.pokemonInfo:
return FadeRoute(page: PokemonInfo());
case _Paths.typeEffectsScreen:
return FadeRoute(page: TypeEffectScreen());
case _Paths.itemsList:
return FadeRoute(page: ItemsScreen());
case _Paths.home:
default:
return FadeRoute(page: HomeScreen());
}
}
static Future? push<T>(Routes route, [T? arguments]) =>
state?.pushNamed(_Paths.of(route), arguments: arguments);
static Future? replaceWith<T>(Routes route, [T? arguments]) =>
state?.pushReplacementNamed(_Paths.of(route), arguments: arguments);
static void pop() => state?.pop();
static NavigatorState? get state => navigatorKey.currentState;
}
| 0
|
mirrored_repositories/flutter_Pokedex
|
mirrored_repositories/flutter_Pokedex/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pokedex/app.dart';
import 'package:pokedex/core/network.dart';
import 'package:pokedex/data/repositories/item_repository.dart';
import 'package:pokedex/data/repositories/pokemon_repository.dart';
import 'package:pokedex/data/source/github/github_datasource.dart';
import 'package:pokedex/data/source/local/local_datasource.dart';
import 'package:pokedex/states/theme/theme_cubit.dart';
import 'package:pokedex/states/item/item_bloc.dart';
import 'package:pokedex/states/pokemon/pokemon_bloc.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await LocalDataSource.initialize();
runApp(
MultiRepositoryProvider(
providers: [
///
/// Services
///
RepositoryProvider<NetworkManager>(
create: (context) => NetworkManager(),
),
///
/// Data sources
///
RepositoryProvider<LocalDataSource>(
create: (context) => LocalDataSource(),
),
RepositoryProvider<GithubDataSource>(
create: (context) => GithubDataSource(context.read<NetworkManager>()),
),
///
/// Repositories
///
RepositoryProvider<PokemonRepository>(
create: (context) => PokemonDefaultRepository(
localDataSource: context.read<LocalDataSource>(),
githubDataSource: context.read<GithubDataSource>(),
),
),
RepositoryProvider<ItemRepository>(
create: (context) => ItemDefaultRepository(
localDataSource: context.read<LocalDataSource>(),
githubDataSource: context.read<GithubDataSource>(),
),
),
],
child: MultiBlocProvider(
providers: [
///
/// BLoCs
///
BlocProvider<PokemonBloc>(
create: (context) => PokemonBloc(context.read<PokemonRepository>()),
),
BlocProvider<ItemBloc>(
create: (context) => ItemBloc(context.read<ItemRepository>()),
),
///
/// Theme Cubit
///
BlocProvider<ThemeCubit>(
create: (context) => ThemeCubit(),
)
],
child: PokedexApp(),
),
),
);
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/data/categories.dart
|
import 'package:pokedex/configs/colors.dart';
import 'package:pokedex/domain/entities/category.dart';
import 'package:pokedex/routes.dart';
const List<Category> categories = [
Category(name: 'Pokedex', color: AppColors.teal, route: Routes.pokedex),
Category(name: 'Moves', color: AppColors.red, route: Routes.pokedex),
Category(name: 'Abilities', color: AppColors.blue, route: Routes.pokedex),
Category(name: 'Items', color: AppColors.yellow, route: Routes.items),
Category(name: 'Locations', color: AppColors.purple, route: Routes.pokedex),
Category(name: 'Type Effects', color: AppColors.brown, route: Routes.typeEffects),
];
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/data/generations.dart
|
import 'package:pokedex/domain/entities/generation.dart';
const List<Generation> generations = [
Generation(
title: 'Generation I',
pokemons: [
'assets/images/bulbasaur.png',
'assets/images/charmander.png',
'assets/images/squirtle.png'
],
),
Generation(
title: 'Generation II',
pokemons: [
'assets/images/chikorita.png',
'assets/images/cyndaquil.png',
'assets/images/totodile.png'
],
),
Generation(
title: 'Generation III',
pokemons: [
'assets/images/treecko.png',
'assets/images/torchic.png',
'assets/images/mudkip.png'
],
),
Generation(
title: 'Generation IV',
pokemons: [
'assets/images/turtwig.png',
'assets/images/chimchar.png',
'assets/images/piplup.png'
],
),
Generation(
title: 'Generation V',
pokemons: [
'assets/images/snivy.png',
'assets/images/tepig.png',
'assets/images/oshawott.png'
],
),
Generation(
title: 'Generation VI',
pokemons: [
'assets/images/chespin.png',
'assets/images/fennekin.png',
'assets/images/froakie.png'
],
),
Generation(
title: 'Generation VII',
pokemons: [
'assets/images/rowlet.png',
'assets/images/litten.png',
'assets/images/popplio.png'
],
),
Generation(
title: 'Generation VIII',
pokemons: [
'assets/images/grookey.png',
'assets/images/scorbunny.png',
'assets/images/sobble.png'
],
),
];
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source
|
mirrored_repositories/flutter_Pokedex/lib/data/source/github/github_datasource.dart
|
import 'dart:convert';
import 'package:pokedex/core/network.dart';
import 'package:pokedex/data/source/github/models/item.dart';
import 'package:pokedex/data/source/github/models/pokemon.dart';
class GithubDataSource {
GithubDataSource(this.networkManager);
static const String itemsURL =
'https://gist.githubusercontent.com/hungps/48f4355fb1a89ddaf47f56961dc8a245/raw/pokemon-items.json';
static const String url =
'https://gist.githubusercontent.com/hungps/0bfdd96d3ab9ee20c2e572e47c6834c7/raw/pokemons.json';
final NetworkManager networkManager;
Future<List<GithubPokemonModel>> getPokemons() async {
final response = await networkManager.request(RequestMethod.get, url);
final data = (json.decode(response.data) as List)
.map((item) => GithubPokemonModel.fromJson(item))
.toList();
return data;
}
Future<List<GithubItemModel>> getItems() async {
final response = await networkManager.request(RequestMethod.get, itemsURL);
final data =
(json.decode(response.data) as List).map((item) => GithubItemModel.fromJson(item)).toList();
return data;
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source/github
|
mirrored_repositories/flutter_Pokedex/lib/data/source/github/models/pokemon.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'pokemon.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
GithubPokemonModel _$GithubPokemonModelFromJson(Map<String, dynamic> json) {
$checkKeys(json, requiredKeys: const [
'name',
'id',
'imageurl',
'typeofpokemon',
'genderless'
], disallowNullValues: const [
'name',
'id',
'imageurl',
'typeofpokemon',
'genderless'
]);
return GithubPokemonModel(
json['name'] as String,
json['id'] as String,
json['imageurl'] as String,
json['xdescription'] as String? ?? '',
json['ydescription'] as String? ?? '',
json['height'] as String? ?? '',
json['category'] as String? ?? '',
json['weight'] as String? ?? '',
(json['typeofpokemon'] as List<dynamic>).map((e) => e as String).toList(),
(json['weaknesses'] as List<dynamic>?)?.map((e) => e as String).toList() ??
[],
(json['evolutions'] as List<dynamic>?)?.map((e) => e as String).toList() ??
[],
(json['abilities'] as List<dynamic>?)?.map((e) => e as String).toList() ??
[],
json['hp'] as num? ?? 0,
json['attack'] as num? ?? 0,
json['defense'] as num? ?? 0,
json['special_attack'] as num? ?? 0,
json['special_defense'] as num? ?? 0,
json['speed'] as num? ?? 0,
json['total'] as num? ?? 0,
json['male_percentage'] as String?,
json['female_percentage'] as String?,
json['genderless'] as num,
json['cycles'] as String?,
json['egg_groups'] as String?,
json['evolvedfrom'] as String?,
json['reason'] as String?,
json['base_exp'] as String? ?? '0',
);
}
Map<String, dynamic> _$GithubPokemonModelToJson(GithubPokemonModel instance) =>
<String, dynamic>{
'name': instance.name,
'id': instance.id,
'imageurl': instance.imageUrl,
'xdescription': instance.xDescription,
'ydescription': instance.yDescription,
'height': instance.height,
'category': instance.category,
'weight': instance.weight,
'typeofpokemon': instance.types,
'weaknesses': instance.weaknesses,
'evolutions': instance.evolutions,
'abilities': instance.abilities,
'hp': instance.hp,
'attack': instance.attack,
'defense': instance.defense,
'special_attack': instance.specialAttack,
'special_defense': instance.specialDefense,
'speed': instance.speed,
'total': instance.total,
'male_percentage': instance.genderMalePercentage,
'female_percentage': instance.genderFemalePercentage,
'genderless': instance.genderless,
'cycles': instance.cycles,
'egg_groups': instance.eggGroups,
'evolvedfrom': instance.evolvedFrom,
'reason': instance.reason,
'base_exp': instance.baseExp,
};
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source/github
|
mirrored_repositories/flutter_Pokedex/lib/data/source/github/models/item.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'item.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
GithubItemModel _$GithubItemModelFromJson(Map<String, dynamic> json) {
$checkKeys(json, disallowNullValues: const ['name', 'imageurl', 'effect']);
return GithubItemModel(
json['name'] as String,
json['category'] as String? ?? '',
json['imageurl'] as String,
json['effect'] as String,
);
}
Map<String, dynamic> _$GithubItemModelToJson(GithubItemModel instance) =>
<String, dynamic>{
'name': instance.name,
'category': instance.category,
'imageurl': instance.imageurl,
'effect': instance.effect,
};
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source/github
|
mirrored_repositories/flutter_Pokedex/lib/data/source/github/models/pokemon.dart
|
import 'package:json_annotation/json_annotation.dart';
part 'pokemon.g.dart';
@JsonSerializable()
class GithubPokemonModel {
GithubPokemonModel(
this.name,
this.id,
this.imageUrl,
this.xDescription,
this.yDescription,
this.height,
this.category,
this.weight,
this.types,
this.weaknesses,
this.evolutions,
this.abilities,
this.hp,
this.attack,
this.defense,
this.specialAttack,
this.specialDefense,
this.speed,
this.total,
this.genderMalePercentage,
this.genderFemalePercentage,
this.genderless,
this.cycles,
this.eggGroups,
this.evolvedFrom,
this.reason,
this.baseExp,
);
factory GithubPokemonModel.fromJson(Map<String, dynamic> json) =>
_$GithubPokemonModelFromJson(json);
Map<String, dynamic> toJson() => _$GithubPokemonModelToJson(this);
@JsonKey(required: true, disallowNullValue: true)
final String name;
@JsonKey(required: true, disallowNullValue: true)
final String id;
@JsonKey(required: true, name: 'imageurl', disallowNullValue: true)
final String imageUrl;
@JsonKey(name: 'xdescription', defaultValue: '')
final String xDescription;
@JsonKey(name: 'ydescription', defaultValue: '')
final String yDescription;
@JsonKey(defaultValue: '')
final String height;
@JsonKey(defaultValue: '')
final String category;
@JsonKey(defaultValue: '')
final String weight;
@JsonKey(name: 'typeofpokemon', required: true, disallowNullValue: true)
final List<String> types;
@JsonKey(defaultValue: [])
final List<String> weaknesses;
@JsonKey(defaultValue: [])
final List<String> evolutions;
@JsonKey(defaultValue: [])
final List<String> abilities;
@JsonKey(defaultValue: 0)
final num hp;
@JsonKey(defaultValue: 0)
final num attack;
@JsonKey(defaultValue: 0)
final num defense;
@JsonKey(name: 'special_attack', defaultValue: 0)
final num specialAttack;
@JsonKey(name: 'special_defense', defaultValue: 0)
final num specialDefense;
@JsonKey(defaultValue: 0)
final num speed;
@JsonKey(defaultValue: 0)
final num total;
@JsonKey(name: 'male_percentage')
final String? genderMalePercentage;
@JsonKey(name: 'female_percentage')
final String? genderFemalePercentage;
@JsonKey(required: true, disallowNullValue: true)
final num genderless;
@JsonKey()
final String? cycles;
@JsonKey(name: 'egg_groups')
final String? eggGroups;
@JsonKey(name: 'evolvedfrom')
final String? evolvedFrom;
@JsonKey()
final String? reason;
@JsonKey(name: 'base_exp', defaultValue: '0')
final String baseExp;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source/github
|
mirrored_repositories/flutter_Pokedex/lib/data/source/github/models/item.dart
|
import 'package:json_annotation/json_annotation.dart';
part 'item.g.dart';
@JsonSerializable()
class GithubItemModel {
GithubItemModel(
this.name,
this.category,
this.imageurl,
this.effect,
);
factory GithubItemModel.fromJson(Map<String, dynamic> json) => _$GithubItemModelFromJson(json);
Map<String, dynamic> toJson() => _$GithubItemModelToJson(this);
@JsonKey(disallowNullValue: true)
final String name;
@JsonKey(defaultValue: '')
final String category;
@JsonKey(disallowNullValue: true)
final String imageurl;
@JsonKey(disallowNullValue: true)
final String effect;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local/local_datasource.dart
|
import 'dart:math';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:pokedex/data/source/local/models/item.dart';
import 'package:pokedex/data/source/local/models/pokemon.dart';
import 'package:pokedex/data/source/local/models/pokemon_gender.dart';
import 'package:pokedex/data/source/local/models/pokemon_stats.dart';
class LocalDataSource {
static Future<void> initialize() async {
await Hive.initFlutter();
Hive.registerAdapter<PokemonHiveModel>(PokemonHiveModelAdapter());
Hive.registerAdapter<PokemonGenderHiveModel>(PokemonGenderHiveModelAdapter());
Hive.registerAdapter<PokemonStatsHiveModel>(PokemonStatsHiveModelAdapter());
Hive.registerAdapter<ItemHiveModel>(ItemHiveModelAdapter());
await Hive.openBox<PokemonHiveModel>(PokemonHiveModel.boxKey);
await Hive.openBox<PokemonGenderHiveModel>(PokemonGenderHiveModel.boxKey);
await Hive.openBox<PokemonStatsHiveModel>(PokemonStatsHiveModel.boxKey);
await Hive.openBox<ItemHiveModel>(ItemHiveModel.boxKey);
}
Future<bool> hasData() async {
final pokemonBox = Hive.box<PokemonHiveModel>(PokemonHiveModel.boxKey);
return pokemonBox.length > 0;
}
Future<bool> hasItemData() async {
final itemBox = Hive.box<ItemHiveModel>(ItemHiveModel.boxKey);
return itemBox.length > 0;
}
Future<void> savePokemons(Iterable<PokemonHiveModel> pokemons) async {
final pokemonBox = Hive.box<PokemonHiveModel>(PokemonHiveModel.boxKey);
final pokemonsMap = {for (var e in pokemons) e.number: e};
await pokemonBox.clear();
await pokemonBox.putAll(pokemonsMap);
}
Future<List<PokemonHiveModel>> getAllPokemons() async {
final pokemonBox = Hive.box<PokemonHiveModel>(PokemonHiveModel.boxKey);
final pokemons = List.generate(pokemonBox.length, (index) => pokemonBox.getAt(index))
.whereType<PokemonHiveModel>()
.toList();
return pokemons;
}
Future<List<PokemonHiveModel>> getPokemons({required int page, required int limit}) async {
final pokemonBox = Hive.box<PokemonHiveModel>(PokemonHiveModel.boxKey);
final totalPokemons = pokemonBox.length;
final start = (page - 1) * limit;
final newPokemonCount = min(totalPokemons - start, limit);
final pokemons = List.generate(newPokemonCount, (index) => pokemonBox.getAt(start + index))
.whereType<PokemonHiveModel>()
.toList();
return pokemons;
}
Future<PokemonHiveModel?> getPokemon(String number) async {
final pokemonBox = Hive.box<PokemonHiveModel>(PokemonHiveModel.boxKey);
return pokemonBox.get(number);
}
Future<List<PokemonHiveModel>> getEvolutions(PokemonHiveModel pokemon) async {
final pokemonFutures = pokemon.evolutions.map((pokemonNumber) => getPokemon(pokemonNumber));
final pokemons = await Future.wait(pokemonFutures);
return pokemons.whereType<PokemonHiveModel>().toList();
}
Future<void> saveItems(Iterable<ItemHiveModel> items) async {
final itemBox = Hive.box<ItemHiveModel>(ItemHiveModel.boxKey);
final itemsMap = {for (var e in items) e.name: e};
await itemBox.clear();
await itemBox.putAll(itemsMap);
}
Future<List<ItemHiveModel>> getAllItems() async {
final itemBox = Hive.box<ItemHiveModel>(ItemHiveModel.boxKey);
final items = List.generate(itemBox.length, (index) => itemBox.getAt(index))
.whereType<ItemHiveModel>()
.toList();
return items;
}
Future<List<ItemHiveModel>> getItems({required int page, required int limit}) async {
final itemBox = Hive.box<ItemHiveModel>(ItemHiveModel.boxKey);
final totalItems = itemBox.length;
final start = (page - 1) * limit;
final newItemCount = min(totalItems - start, limit);
final items = List.generate(newItemCount, (index) => itemBox.getAt(start + index))
.whereType<ItemHiveModel>()
.toList();
return items;
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local/models/pokemon.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'pokemon.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class PokemonHiveModelAdapter extends TypeAdapter<PokemonHiveModel> {
@override
final int typeId = 1;
@override
PokemonHiveModel read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return PokemonHiveModel()
..number = fields[0] as String
..name = fields[1] as String
..description = fields[2] as String
..types = (fields[3] as List).cast<String>()
..image = fields[4] as String
..height = fields[5] as String
..weight = fields[6] as String
..genera = fields[7] as String
..eggGroups = (fields[8] as List).cast<String>()
..gender = fields[9] as PokemonGenderHiveModel
..stats = fields[10] as PokemonStatsHiveModel
..baseExp = fields[11] as double
..evolutions = (fields[12] as List).cast<String>()
..evolutionReason = fields[13] as String;
}
@override
void write(BinaryWriter writer, PokemonHiveModel obj) {
writer
..writeByte(14)
..writeByte(0)
..write(obj.number)
..writeByte(1)
..write(obj.name)
..writeByte(2)
..write(obj.description)
..writeByte(3)
..write(obj.types)
..writeByte(4)
..write(obj.image)
..writeByte(5)
..write(obj.height)
..writeByte(6)
..write(obj.weight)
..writeByte(7)
..write(obj.genera)
..writeByte(8)
..write(obj.eggGroups)
..writeByte(9)
..write(obj.gender)
..writeByte(10)
..write(obj.stats)
..writeByte(11)
..write(obj.baseExp)
..writeByte(12)
..write(obj.evolutions)
..writeByte(13)
..write(obj.evolutionReason);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is PokemonHiveModelAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local/models/pokemon_gender.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'pokemon_gender.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class PokemonGenderHiveModelAdapter
extends TypeAdapter<PokemonGenderHiveModel> {
@override
final int typeId = 2;
@override
PokemonGenderHiveModel read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return PokemonGenderHiveModel()
..genderless = fields[0] as bool
..male = fields[1] as double
..female = fields[2] as double;
}
@override
void write(BinaryWriter writer, PokemonGenderHiveModel obj) {
writer
..writeByte(3)
..writeByte(0)
..write(obj.genderless)
..writeByte(1)
..write(obj.male)
..writeByte(2)
..write(obj.female);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is PokemonGenderHiveModelAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local/models/item.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'item.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class ItemHiveModelAdapter extends TypeAdapter<ItemHiveModel> {
@override
final int typeId = 4;
@override
ItemHiveModel read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return ItemHiveModel()
..name = fields[0] as String?
..category = fields[1] as String?
..imageurl = fields[2] as String?
..effect = fields[3] as String?;
}
@override
void write(BinaryWriter writer, ItemHiveModel obj) {
writer
..writeByte(4)
..writeByte(0)
..write(obj.name)
..writeByte(1)
..write(obj.category)
..writeByte(2)
..write(obj.imageurl)
..writeByte(3)
..write(obj.effect);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is ItemHiveModelAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local/models/pokemon_stats.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'pokemon_stats.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class PokemonStatsHiveModelAdapter extends TypeAdapter<PokemonStatsHiveModel> {
@override
final int typeId = 3;
@override
PokemonStatsHiveModel read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return PokemonStatsHiveModel()
..attack = fields[0] as int
..specialAttack = fields[1] as int
..defense = fields[2] as int
..specialDefense = fields[3] as int
..hp = fields[4] as int
..speed = fields[5] as int;
}
@override
void write(BinaryWriter writer, PokemonStatsHiveModel obj) {
writer
..writeByte(6)
..writeByte(0)
..write(obj.attack)
..writeByte(1)
..write(obj.specialAttack)
..writeByte(2)
..write(obj.defense)
..writeByte(3)
..write(obj.specialDefense)
..writeByte(4)
..write(obj.hp)
..writeByte(5)
..write(obj.speed);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is PokemonStatsHiveModelAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local/models/pokemon_stats.dart
|
import 'package:hive/hive.dart';
part 'pokemon_stats.g.dart';
@HiveType(typeId: 3)
class PokemonStatsHiveModel extends HiveObject {
static const String boxKey = 'pokemonStats';
@HiveField(0)
late int attack;
@HiveField(1)
late int specialAttack;
@HiveField(2)
late int defense;
@HiveField(3)
late int specialDefense;
@HiveField(4)
late int hp;
@HiveField(5)
late int speed;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local/models/pokemon.dart
|
import 'package:hive/hive.dart';
import 'pokemon_gender.dart';
import 'pokemon_stats.dart';
part 'pokemon.g.dart';
@HiveType(typeId: 1)
class PokemonHiveModel extends HiveObject {
static const String boxKey = 'pokemon';
@HiveField(0)
late String number;
@HiveField(1)
late String name;
@HiveField(2)
late String description;
@HiveField(3)
late List<String> types;
@HiveField(4)
late String image;
@HiveField(5)
late String height;
@HiveField(6)
late String weight;
@HiveField(7)
late String genera;
@HiveField(8)
late List<String> eggGroups;
@HiveField(9)
late PokemonGenderHiveModel gender;
@HiveField(10)
late PokemonStatsHiveModel stats;
@HiveField(11)
late double baseExp;
@HiveField(12)
late List<String> evolutions;
@HiveField(13)
late String evolutionReason;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local/models/pokemon_gender.dart
|
import 'package:hive/hive.dart';
part 'pokemon_gender.g.dart';
@HiveType(typeId: 2)
class PokemonGenderHiveModel extends HiveObject {
static const String boxKey = 'pokemonGender';
@HiveField(0)
late bool genderless;
@HiveField(1)
late double male;
@HiveField(2)
late double female;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local
|
mirrored_repositories/flutter_Pokedex/lib/data/source/local/models/item.dart
|
import 'package:hive/hive.dart';
part 'item.g.dart';
@HiveType(typeId: 4)
class ItemHiveModel extends HiveObject {
static const String boxKey = 'item';
@HiveField(0)
String? name;
@HiveField(1)
String? category;
@HiveField(2)
String? imageurl;
@HiveField(3)
String? effect;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source
|
mirrored_repositories/flutter_Pokedex/lib/data/source/mappers/github_to_local_mapper.dart
|
import 'package:pokedex/core/extensions/string.dart';
import 'package:pokedex/data/source/github/models/item.dart';
import 'package:pokedex/data/source/github/models/pokemon.dart';
import 'package:pokedex/data/source/local/models/item.dart';
import 'package:pokedex/data/source/local/models/pokemon.dart';
import 'package:pokedex/data/source/local/models/pokemon_gender.dart';
import 'package:pokedex/data/source/local/models/pokemon_stats.dart';
extension GithubPokemonModelToLocalX on GithubPokemonModel {
PokemonHiveModel toHiveModel() => PokemonHiveModel()
..number = id.trim()
..name = name.trim()
..description = xDescription.trim()
..types = types.toList(growable: false)
..image = imageUrl.trim()
..height = height.trim()
..weight = weight.trim()
..genera = category.trim()
..eggGroups = eggGroups?.split(RegExp(r',\s*?')).map((e) => e.trim()).toList() ?? []
..gender = (PokemonGenderHiveModel()
..male = genderMalePercentage?.parseDouble() ?? 0
..female = genderFemalePercentage?.parseDouble() ?? 0
..genderless = genderless == 1)
..stats = (PokemonStatsHiveModel()
..hp = hp.toInt()
..speed = speed.toInt()
..attack = attack.toInt()
..defense = defense.toInt()
..specialAttack = specialAttack.toInt()
..specialDefense = specialDefense.toInt())
..baseExp = baseExp.parseDouble()
..evolutions = evolutions
..evolutionReason = reason ?? '';
}
extension GithubItemModelToLocalX on GithubItemModel {
ItemHiveModel toHiveModel() => ItemHiveModel()
..name = name.trim()
..category = category.trim()
..imageurl = imageurl.trim()
..effect = effect.trim();
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data/source
|
mirrored_repositories/flutter_Pokedex/lib/data/source/mappers/local_to_entity_mapper.dart
|
import 'package:pokedex/data/source/local/models/item.dart';
import 'package:pokedex/data/source/local/models/pokemon.dart';
import 'package:pokedex/data/source/local/models/pokemon_gender.dart';
import 'package:pokedex/data/source/local/models/pokemon_stats.dart';
import 'package:pokedex/domain/entities/item.dart';
import 'package:pokedex/domain/entities/pokemon.dart';
import 'package:pokedex/domain/entities/pokemon_props.dart';
import 'package:pokedex/domain/entities/pokemon_types.dart';
extension PokemonHiveModelX on PokemonHiveModel {
Pokemon toEntity({List<PokemonHiveModel> evolutions = const []}) => Pokemon(
number: number.trim(),
name: name.trim(),
description: description.trim(),
types: types.map((e) => PokemonTypesX.parse(e)).toList(),
image: image.trim(),
height: height.trim(),
weight: weight.trim(),
genera: genera.trim(),
eggGroups: eggGroups.map((e) => e.trim()).where((e) => e.isNotEmpty).toList(),
gender: gender.toEntity(),
stats: stats.toEntity(),
baseExp: baseExp,
evolutions: evolutions.map((e) => e.toEntity()).toList(),
evolutionReason: evolutionReason,
);
}
extension PokemonGenderHiveModelX on PokemonGenderHiveModel {
PokemonGender toEntity() => PokemonGender(
male: male,
female: female,
genderless: genderless,
);
}
extension PokemonStatsHiveModelX on PokemonStatsHiveModel {
PokemonStats toEntity() => PokemonStats(
attack: attack,
specialAttack: specialAttack,
defense: defense,
specialDefense: specialDefense,
hp: hp,
speed: speed,
);
}
extension ItemHiveModelX on ItemHiveModel {
Item toEntity({List<ItemHiveModel> evolutions = const []}) => Item(
name: name?.trim() ?? '',
category: name?.trim() ?? '',
image: imageurl?.trim() ?? '',
effect: effect?.trim() ?? '',
);
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data
|
mirrored_repositories/flutter_Pokedex/lib/data/repositories/item_repository.dart
|
import 'package:pokedex/data/source/github/github_datasource.dart';
import 'package:pokedex/data/source/local/local_datasource.dart';
import 'package:pokedex/data/source/mappers/github_to_local_mapper.dart';
import 'package:pokedex/data/source/mappers/local_to_entity_mapper.dart';
import 'package:pokedex/domain/entities/item.dart';
abstract class ItemRepository {
Future<List<Item>> getAllItems();
Future<List<Item>> getItems({required int limit, required int page});
}
class ItemDefaultRepository extends ItemRepository {
ItemDefaultRepository({required this.githubDataSource, required this.localDataSource});
final GithubDataSource githubDataSource;
final LocalDataSource localDataSource;
@override
Future<List<Item>> getAllItems() async {
final hasCachedData = await localDataSource.hasData();
if (!hasCachedData) {
final itemGithubModel = await githubDataSource.getItems();
final itemHiveModels = itemGithubModel.map((e) => e.toHiveModel());
await localDataSource.saveItems(itemHiveModels);
}
final itemHiveModels = await localDataSource.getAllItems();
final itemEntities = itemHiveModels.map((e) => e.toEntity()).toList();
return itemEntities;
}
@override
Future<List<Item>> getItems({required int limit, required int page}) async {
final hasCachedData = await localDataSource.hasItemData();
if (!hasCachedData) {
final itemGithubModels = await githubDataSource.getItems();
final itemHiveModels = itemGithubModels.map((e) => e.toHiveModel());
await localDataSource.saveItems(itemHiveModels);
}
final itemHiveModels = await localDataSource.getItems(
page: page,
limit: limit,
);
final itemEntities = itemHiveModels.map((e) => e.toEntity()).toList();
return itemEntities;
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/data
|
mirrored_repositories/flutter_Pokedex/lib/data/repositories/pokemon_repository.dart
|
import 'package:pokedex/data/source/github/github_datasource.dart';
import 'package:pokedex/data/source/local/local_datasource.dart';
import 'package:pokedex/data/source/mappers/github_to_local_mapper.dart';
import 'package:pokedex/data/source/mappers/local_to_entity_mapper.dart';
import 'package:pokedex/domain/entities/pokemon.dart';
abstract class PokemonRepository {
Future<List<Pokemon>> getAllPokemons();
Future<List<Pokemon>> getPokemons({required int limit, required int page});
Future<Pokemon?> getPokemon(String number);
}
class PokemonDefaultRepository extends PokemonRepository {
PokemonDefaultRepository({required this.githubDataSource, required this.localDataSource});
final GithubDataSource githubDataSource;
final LocalDataSource localDataSource;
@override
Future<List<Pokemon>> getAllPokemons() async {
final hasCachedData = await localDataSource.hasData();
if (!hasCachedData) {
final pokemonGithubModels = await githubDataSource.getPokemons();
final pokemonHiveModels = pokemonGithubModels.map((e) => e.toHiveModel());
await localDataSource.savePokemons(pokemonHiveModels);
}
final pokemonHiveModels = await localDataSource.getAllPokemons();
final pokemonEntities = pokemonHiveModels.map((e) => e.toEntity()).toList();
return pokemonEntities;
}
@override
Future<List<Pokemon>> getPokemons({required int limit, required int page}) async {
final hasCachedData = await localDataSource.hasData();
if (!hasCachedData) {
final pokemonGithubModels = await githubDataSource.getPokemons();
final pokemonHiveModels = pokemonGithubModels.map((e) => e.toHiveModel());
await localDataSource.savePokemons(pokemonHiveModels);
}
final pokemonHiveModels = await localDataSource.getPokemons(
page: page,
limit: limit,
);
final pokemonEntities = pokemonHiveModels.map((e) => e.toEntity()).toList();
return pokemonEntities;
}
@override
Future<Pokemon?> getPokemon(String number) async {
final pokemonModel = await localDataSource.getPokemon(number);
if (pokemonModel == null) return null;
// get all evolutions
final evolutions = await localDataSource.getEvolutions(pokemonModel);
final pokemon = pokemonModel.toEntity(evolutions: evolutions);
return pokemon;
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/states
|
mirrored_repositories/flutter_Pokedex/lib/states/item/item_state.dart
|
import 'package:pokedex/domain/entities/item.dart';
enum ItemStateStatus {
initial,
loading,
loadSuccess,
loadFailure,
loadingMore,
loadMoreSuccess,
loadMoreFailure,
}
class ItemState {
final ItemStateStatus status;
final List<Item> items;
final int selectedItemIndex;
final int page;
final Exception? error;
final bool canLoadMore;
Item get selectedItem => items[selectedItemIndex];
const ItemState._({
this.status = ItemStateStatus.initial,
this.items = const [],
this.selectedItemIndex = 0,
this.page = 1,
this.canLoadMore = true,
this.error,
});
const ItemState.initial() : this._();
ItemState asLoading() {
return copyWith(
status: ItemStateStatus.loading,
);
}
ItemState asLoadSuccess(List<Item> items, {bool canLoadMore = true}) {
return copyWith(
status: ItemStateStatus.loadSuccess,
items: items,
page: 1,
canLoadMore: canLoadMore,
);
}
ItemState asLoadFailure(Exception e) {
return copyWith(
status: ItemStateStatus.loadFailure,
error: e,
);
}
ItemState asLoadingMore() {
return copyWith(status: ItemStateStatus.loadingMore);
}
ItemState asLoadMoreSuccess(List<Item> newItems, {bool canLoadMore = true}) {
return copyWith(
status: ItemStateStatus.loadMoreSuccess,
items: [...items, ...newItems],
page: canLoadMore ? page + 1 : page,
canLoadMore: canLoadMore,
);
}
ItemState asLoadMoreFailure(Exception e) {
return copyWith(
status: ItemStateStatus.loadMoreFailure,
error: e,
);
}
ItemState copyWith({
ItemStateStatus? status,
List<Item>? items,
int? selectedPokemonIndex,
int? page,
bool? canLoadMore,
Exception? error,
}) {
return ItemState._(
status: status ?? this.status,
items: items ?? this.items,
selectedItemIndex: selectedItemIndex,
page: page ?? this.page,
canLoadMore: canLoadMore ?? this.canLoadMore,
error: error ?? this.error,
);
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/states
|
mirrored_repositories/flutter_Pokedex/lib/states/item/item_selector.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pokedex/domain/entities/item.dart';
import 'package:pokedex/states/item/item_bloc.dart';
import 'package:pokedex/states/item/item_state.dart';
class ItemStateSelector<T> extends BlocSelector<ItemBloc, ItemState, T> {
ItemStateSelector({
required T Function(ItemState) selector,
required Widget Function(T) builder,
}) : super(
selector: selector,
builder: (_, value) => builder(value),
);
}
class ItemStateStatusSelector extends ItemStateSelector<ItemStateStatus> {
ItemStateStatusSelector(Widget Function(ItemStateStatus) builder)
: super(
selector: (state) => state.status,
builder: builder,
);
}
class ItemCanLoadMoreSelector extends ItemStateSelector<bool> {
ItemCanLoadMoreSelector(Widget Function(bool) builder)
: super(
selector: (state) => state.canLoadMore,
builder: builder,
);
}
class NumberOfItemsSelector extends ItemStateSelector<int> {
NumberOfItemsSelector(Widget Function(int) builder)
: super(
selector: (state) => state.items.length,
builder: builder,
);
}
class CurrentItemSelector extends ItemStateSelector<Item> {
CurrentItemSelector(Widget Function(Item) builder)
: super(
selector: (state) => state.selectedItem,
builder: builder,
);
}
class ItemSelector extends ItemStateSelector<ItemSelectorState> {
ItemSelector(int index, Widget Function(Item, bool) builder)
: super(
selector: (state) => ItemSelectorState(
state.items[index],
state.selectedItemIndex == index,
),
builder: (value) => builder(value.item, value.selected),
);
}
class ItemSelectorState {
final Item item;
final bool selected;
const ItemSelectorState(this.item, this.selected);
@override
bool operator ==(Object other) =>
other is ItemSelectorState && item == other.item && selected == other.selected;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/states
|
mirrored_repositories/flutter_Pokedex/lib/states/item/item_bloc.dart
|
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pokedex/data/repositories/item_repository.dart';
import 'package:pokedex/states/item/item_event.dart';
import 'package:pokedex/states/item/item_state.dart';
import 'package:stream_transform/stream_transform.dart';
class ItemBloc extends Bloc<ItemEvent, ItemState> {
static const int itemsPerPage = 20;
final ItemRepository _itemRepository;
ItemBloc(this._itemRepository) : super(ItemState.initial()) {
on<ItemLoadStarted>(
_onLoadStarted,
transformer: (events, mapper) => events.switchMap(mapper),
);
on<ItemLoadMoreStarted>(
_onLoadMoreStarted,
transformer: (events, mapper) => events.switchMap(mapper),
);
// on<ItemSelectChanged>(_onSelectChanged);
}
void _onLoadStarted(ItemLoadStarted event, Emitter<ItemState> emit) async {
try {
emit(state.asLoading());
final items = event.loadAll
? await _itemRepository.getAllItems()
: await _itemRepository.getItems(page: 1, limit: itemsPerPage);
final canLoadMore = items.length >= itemsPerPage;
emit(state.asLoadSuccess(items, canLoadMore: canLoadMore));
} on Exception catch (e) {
emit(state.asLoadFailure(e));
}
}
void _onLoadMoreStarted(ItemLoadMoreStarted event, Emitter<ItemState> emit) async {
try {
if (!state.canLoadMore) return;
emit(state.asLoadingMore());
final pokemons = await _itemRepository.getItems(
page: state.page + 1,
limit: itemsPerPage,
);
final canLoadMore = pokemons.length >= itemsPerPage;
emit(state.asLoadMoreSuccess(pokemons, canLoadMore: canLoadMore));
} on Exception catch (e) {
emit(state.asLoadMoreFailure(e));
}
}
// void _onSelectChanged(ItemSelectChanged event, Emitter<ItemState> emit) async {
// try {
// final itemIndex = state.items.indexWhere(
// (item) => item.number == event.pokemonId,
// );
// if (itemIndex < 0 || itemIndex >= state.pokemons.length) return;
// final item = await _itemRepository.getPokemon(event.pokemonId);
// if (pokemon == null) return;
// emit(state.copyWith(
// pokemons: state.pokemons..setAll(itemIndex, [pokemon]),
// selectedPokemonIndex: itemIndex,
// ));
// } on Exception catch (e) {
// emit(state.asLoadMoreFailure(e));
// }
// }
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/states
|
mirrored_repositories/flutter_Pokedex/lib/states/item/item_event.dart
|
abstract class ItemEvent {
const ItemEvent();
}
class ItemLoadStarted extends ItemEvent {
final bool loadAll;
const ItemLoadStarted({this.loadAll = false});
}
class ItemLoadMoreStarted extends ItemEvent {}
class ItemSelectChanged extends ItemEvent {
final String itemId;
const ItemSelectChanged({required this.itemId});
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/states
|
mirrored_repositories/flutter_Pokedex/lib/states/pokemon/pokemon_selector.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pokedex/domain/entities/pokemon.dart';
import 'package:pokedex/states/pokemon/pokemon_bloc.dart';
import 'package:pokedex/states/pokemon/pokemon_state.dart';
class PokemonStateSelector<T> extends BlocSelector<PokemonBloc, PokemonState, T> {
PokemonStateSelector({
required T Function(PokemonState) selector,
required Widget Function(T) builder,
}) : super(
selector: selector,
builder: (_, value) => builder(value),
);
}
class PokemonStateStatusSelector extends PokemonStateSelector<PokemonStateStatus> {
PokemonStateStatusSelector(Widget Function(PokemonStateStatus) builder)
: super(
selector: (state) => state.status,
builder: builder,
);
}
class PokemonCanLoadMoreSelector extends PokemonStateSelector<bool> {
PokemonCanLoadMoreSelector(Widget Function(bool) builder)
: super(
selector: (state) => state.canLoadMore,
builder: builder,
);
}
class NumberOfPokemonsSelector extends PokemonStateSelector<int> {
NumberOfPokemonsSelector(Widget Function(int) builder)
: super(
selector: (state) => state.pokemons.length,
builder: builder,
);
}
class CurrentPokemonSelector extends PokemonStateSelector<Pokemon> {
CurrentPokemonSelector(Widget Function(Pokemon) builder)
: super(
selector: (state) => state.selectedPokemon,
builder: builder,
);
}
class PokemonSelector extends PokemonStateSelector<PokemonSelectorState> {
PokemonSelector(int index, Widget Function(Pokemon, bool) builder)
: super(
selector: (state) => PokemonSelectorState(
state.pokemons[index],
state.selectedPokemonIndex == index,
),
builder: (value) => builder(value.pokemon, value.selected),
);
}
class PokemonSelectorState {
final Pokemon pokemon;
final bool selected;
const PokemonSelectorState(this.pokemon, this.selected);
@override
bool operator ==(Object other) =>
other is PokemonSelectorState && pokemon == other.pokemon && selected == other.selected;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/states
|
mirrored_repositories/flutter_Pokedex/lib/states/pokemon/pokemon_event.dart
|
abstract class PokemonEvent {
const PokemonEvent();
}
class PokemonLoadStarted extends PokemonEvent {
final bool loadAll;
const PokemonLoadStarted({this.loadAll = false});
}
class PokemonLoadMoreStarted extends PokemonEvent {}
class PokemonSelectChanged extends PokemonEvent {
final String pokemonId;
const PokemonSelectChanged({required this.pokemonId});
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/states
|
mirrored_repositories/flutter_Pokedex/lib/states/pokemon/pokemon_state.dart
|
import 'package:pokedex/domain/entities/pokemon.dart';
enum PokemonStateStatus {
initial,
loading,
loadSuccess,
loadFailure,
loadingMore,
loadMoreSuccess,
loadMoreFailure,
}
class PokemonState {
final PokemonStateStatus status;
final List<Pokemon> pokemons;
final int selectedPokemonIndex;
final int page;
final Exception? error;
final bool canLoadMore;
Pokemon get selectedPokemon => pokemons[selectedPokemonIndex];
const PokemonState._({
this.status = PokemonStateStatus.initial,
this.pokemons = const [],
this.selectedPokemonIndex = 0,
this.page = 1,
this.canLoadMore = true,
this.error,
});
const PokemonState.initial() : this._();
PokemonState asLoading() {
return copyWith(
status: PokemonStateStatus.loading,
);
}
PokemonState asLoadSuccess(List<Pokemon> pokemons, {bool canLoadMore = true}) {
return copyWith(
status: PokemonStateStatus.loadSuccess,
pokemons: pokemons,
page: 1,
canLoadMore: canLoadMore,
);
}
PokemonState asLoadFailure(Exception e) {
return copyWith(
status: PokemonStateStatus.loadFailure,
error: e,
);
}
PokemonState asLoadingMore() {
return copyWith(status: PokemonStateStatus.loadingMore);
}
PokemonState asLoadMoreSuccess(List<Pokemon> newPokemons, {bool canLoadMore = true}) {
return copyWith(
status: PokemonStateStatus.loadMoreSuccess,
pokemons: [...pokemons, ...newPokemons],
page: canLoadMore ? page + 1 : page,
canLoadMore: canLoadMore,
);
}
PokemonState asLoadMoreFailure(Exception e) {
return copyWith(
status: PokemonStateStatus.loadMoreFailure,
error: e,
);
}
PokemonState copyWith({
PokemonStateStatus? status,
List<Pokemon>? pokemons,
int? selectedPokemonIndex,
int? page,
bool? canLoadMore,
Exception? error,
}) {
return PokemonState._(
status: status ?? this.status,
pokemons: pokemons ?? this.pokemons,
selectedPokemonIndex: selectedPokemonIndex ?? this.selectedPokemonIndex,
page: page ?? this.page,
canLoadMore: canLoadMore ?? this.canLoadMore,
error: error ?? this.error,
);
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/states
|
mirrored_repositories/flutter_Pokedex/lib/states/pokemon/pokemon_bloc.dart
|
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:stream_transform/stream_transform.dart';
import 'package:pokedex/data/repositories/pokemon_repository.dart';
import 'package:pokedex/states/pokemon/pokemon_event.dart';
import 'package:pokedex/states/pokemon/pokemon_state.dart';
class PokemonBloc extends Bloc<PokemonEvent, PokemonState> {
static const int pokemonsPerPage = 20;
final PokemonRepository _pokemonRepository;
PokemonBloc(this._pokemonRepository) : super(PokemonState.initial()) {
on<PokemonLoadStarted>(
_onLoadStarted,
transformer: (events, mapper) => events.switchMap(mapper),
);
on<PokemonLoadMoreStarted>(
_onLoadMoreStarted,
transformer: (events, mapper) => events.switchMap(mapper),
);
on<PokemonSelectChanged>(_onSelectChanged);
}
void _onLoadStarted(PokemonLoadStarted event, Emitter<PokemonState> emit) async {
try {
emit(state.asLoading());
final pokemons = event.loadAll
? await _pokemonRepository.getAllPokemons()
: await _pokemonRepository.getPokemons(page: 1, limit: pokemonsPerPage);
final canLoadMore = pokemons.length >= pokemonsPerPage;
emit(state.asLoadSuccess(pokemons, canLoadMore: canLoadMore));
} on Exception catch (e) {
emit(state.asLoadFailure(e));
}
}
void _onLoadMoreStarted(PokemonLoadMoreStarted event, Emitter<PokemonState> emit) async {
try {
if (!state.canLoadMore) return;
emit(state.asLoadingMore());
final pokemons = await _pokemonRepository.getPokemons(
page: state.page + 1,
limit: pokemonsPerPage,
);
final canLoadMore = pokemons.length >= pokemonsPerPage;
emit(state.asLoadMoreSuccess(pokemons, canLoadMore: canLoadMore));
} on Exception catch (e) {
emit(state.asLoadMoreFailure(e));
}
}
void _onSelectChanged(PokemonSelectChanged event, Emitter<PokemonState> emit) async {
try {
final pokemonIndex = state.pokemons.indexWhere(
(pokemon) => pokemon.number == event.pokemonId,
);
if (pokemonIndex < 0 || pokemonIndex >= state.pokemons.length) return;
final pokemon = await _pokemonRepository.getPokemon(event.pokemonId);
if (pokemon == null) return;
emit(state.copyWith(
pokemons: state.pokemons..setAll(pokemonIndex, [pokemon]),
selectedPokemonIndex: pokemonIndex,
));
} on Exception catch (e) {
emit(state.asLoadMoreFailure(e));
}
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/states
|
mirrored_repositories/flutter_Pokedex/lib/states/theme/theme_state.dart
|
part of 'theme_cubit.dart';
@immutable
abstract class ThemeState {}
class ThemeDark extends ThemeState {
final String message;
ThemeDark({required this.message});
}
class ThemeLight extends ThemeState {
final String message;
ThemeLight({required this.message});
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/states
|
mirrored_repositories/flutter_Pokedex/lib/states/theme/theme_cubit.dart
|
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
part 'theme_state.dart';
// Values are stored and updated here
class ThemeCubit extends Cubit<ThemeState> {
ThemeCubit() : super(ThemeLight(message: 'Dark Theme'));
bool _isDark = true;
bool get isDark => _isDark;
void toggleTheme() {
_isDark = !_isDark;
if (_isDark) {
emit(ThemeDark(message: 'Dark Theme'));
} else {
emit(ThemeLight(message: 'Light Theme'));
}
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/core/exceptions.dart
|
class ServerException implements Exception {}
class CacheException implements Exception {}
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/core/network.dart
|
import 'package:dio/dio.dart';
import 'package:dio_http_cache/dio_http_cache.dart';
import 'package:pokedex/core/utils.dart';
class NetworkManager {
final Dio dio;
const NetworkManager._(this.dio);
factory NetworkManager() {
final dio = Dio();
dio.interceptors.add(DioCacheManager(CacheConfig(
defaultMaxAge: Duration(days: 10),
maxMemoryCacheCount: 3,
)).interceptor);
return NetworkManager._(dio);
}
Future<Response<T>> request<T>(
RequestMethod method,
String url, {
data,
Map<String, dynamic>? headers,
Map<String, dynamic>? queryParameters,
}) {
return dio.request(
url,
data: data,
queryParameters: queryParameters,
options: Options(
method: method.value,
headers: headers,
),
);
}
}
enum RequestMethod {
get,
head,
post,
put,
delete,
connect,
options,
trace,
patch,
}
extension RequestMethodX on RequestMethod {
String get value => getEnumValue(this).toUpperCase();
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/core/fade_page_route.dart
|
import 'package:flutter/material.dart';
class FadeRoute extends PageRouteBuilder {
FadeRoute({required this.page})
: super(
pageBuilder: (_, __, ___) => page,
transitionsBuilder: (_, animation, __, child) => FadeTransition(
opacity: animation,
child: child,
),
);
final Widget page;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/core/utils.dart
|
String getEnumValue(e) => e.toString().split('.').last;
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/core/usecase.dart
|
abstract class BaseUseCase<T> {
const BaseUseCase();
}
abstract class UseCase<T, P> extends BaseUseCase<T> {
const UseCase() : super();
Future<T> call(P params);
}
abstract class NoParamsUseCase<T> extends BaseUseCase<T> {
const NoParamsUseCase() : super();
Future<T> call();
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/core
|
mirrored_repositories/flutter_Pokedex/lib/core/extensions/animation.dart
|
import 'package:flutter/animation.dart';
extension AnimationControllerX on AnimationController {
Animation<T> curvedTweenAnimation<T>({required T begin, required T end}) {
return Tween<T>(begin: begin, end: end).animate(CurvedAnimation(
curve: Curves.easeInOut,
parent: this,
));
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/core
|
mirrored_repositories/flutter_Pokedex/lib/core/extensions/string.dart
|
extension StringX on String {
String capitalize() {
if (length > 0) {
return '${this[0].toUpperCase()}${substring(1)}';
}
return this;
}
double parseDouble([double defaultValue = 0.0]) {
return double.tryParse(replaceAll(RegExp(r'[^0-9\.]'), '')) ?? defaultValue;
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/core
|
mirrored_repositories/flutter_Pokedex/lib/core/extensions/modal.dart
|
import 'package:flutter/material.dart';
extension BuildContextX on BuildContext {
void showModal(Widget child) {
showModalBottomSheet(
context: this,
backgroundColor: Colors.transparent,
builder: (context) => child,
);
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/core
|
mirrored_repositories/flutter_Pokedex/lib/core/extensions/context.dart
|
import 'package:flutter/material.dart';
import 'package:pokedex/configs/constants.dart';
extension BuildContextX on BuildContext {
Size get screenSize => MediaQuery.of(this).size;
double? get iconSize => IconTheme.of(this).size;
EdgeInsets get padding => MediaQuery.of(this).padding;
double responsive(double size, {Axis axis = Axis.vertical}) {
final currentSize = axis == Axis.horizontal ? screenSize.width : screenSize.height;
final designSize = axis == Axis.horizontal
? AppConstants.designScreenSize.width
: AppConstants.designScreenSize.height;
return size * currentSize / designSize;
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/domain
|
mirrored_repositories/flutter_Pokedex/lib/domain/entities/pokemon_types.dart
|
import 'dart:ui';
import 'package:pokedex/configs/colors.dart';
import '../../core/extensions/string.dart';
import '../../core/utils.dart';
enum PokemonTypes {
grass,
poison,
fire,
flying,
water,
bug,
normal,
electric,
ground,
fairy,
fighting,
psychic,
rock,
steel,
ice,
ghost,
dragon,
dark,
monster,
unknown,
}
extension PokemonTypesX on PokemonTypes {
String get value => getEnumValue(this).capitalize();
static PokemonTypes parse(String rawValue) {
final type = PokemonTypes.values.firstWhere(
(element) => element.value.trim().toLowerCase() == rawValue.toLowerCase(),
orElse: () => PokemonTypes.unknown,
);
return type;
}
Map<PokemonTypes, double> get effectiveness => _pokemonEffectivenessMap[this] ?? {};
Color get color {
switch (this) {
case PokemonTypes.grass:
return AppColors.lightGreen;
case PokemonTypes.bug:
return AppColors.lightTeal;
case PokemonTypes.fire:
return AppColors.lightRed;
case PokemonTypes.water:
return AppColors.lightBlue;
case PokemonTypes.fighting:
return AppColors.red;
case PokemonTypes.normal:
return AppColors.beige;
case PokemonTypes.electric:
return AppColors.lightYellow;
case PokemonTypes.psychic:
return AppColors.lightPink;
case PokemonTypes.poison:
return AppColors.lightPurple;
case PokemonTypes.ghost:
return AppColors.purple;
case PokemonTypes.ground:
return AppColors.darkBrown;
case PokemonTypes.rock:
return AppColors.lightBrown;
case PokemonTypes.dark:
return AppColors.black;
case PokemonTypes.dragon:
return AppColors.violet;
case PokemonTypes.fairy:
return AppColors.pink;
case PokemonTypes.flying:
return AppColors.lilac;
case PokemonTypes.ice:
return AppColors.lightCyan;
case PokemonTypes.steel:
return AppColors.grey;
default:
return AppColors.lightBlue;
}
}
}
final _pokemonEffectivenessMap = <PokemonTypes, Map<PokemonTypes, double>>{
PokemonTypes.normal: {
PokemonTypes.ghost: 0,
PokemonTypes.fighting: 2,
},
PokemonTypes.fire: {
PokemonTypes.bug: 0.5,
PokemonTypes.fairy: 0.5,
PokemonTypes.fire: 0.5,
PokemonTypes.grass: 0.5,
PokemonTypes.ice: 0.5,
PokemonTypes.steel: 0.5,
PokemonTypes.ground: 2,
PokemonTypes.rock: 2,
PokemonTypes.water: 2,
},
PokemonTypes.water: {
PokemonTypes.fire: 0.5,
PokemonTypes.ice: 0.5,
PokemonTypes.steel: 0.5,
PokemonTypes.water: 0.5,
PokemonTypes.electric: 2,
PokemonTypes.grass: 2,
},
PokemonTypes.electric: {
PokemonTypes.electric: 0.5,
PokemonTypes.flying: 0.5,
PokemonTypes.steel: 0.5,
PokemonTypes.ground: 2,
},
PokemonTypes.grass: {
PokemonTypes.electric: 0.5,
PokemonTypes.grass: 0.5,
PokemonTypes.ground: 0.5,
PokemonTypes.water: 0.5,
PokemonTypes.bug: 2,
PokemonTypes.ice: 2,
PokemonTypes.flying: 2,
PokemonTypes.fire: 2,
PokemonTypes.poison: 2,
},
PokemonTypes.ice: {
PokemonTypes.ice: 0.5,
PokemonTypes.fire: 2,
PokemonTypes.fighting: 2,
PokemonTypes.rock: 2,
PokemonTypes.steel: 2,
},
PokemonTypes.fighting: {
PokemonTypes.bug: 0.5,
PokemonTypes.rock: 0.5,
PokemonTypes.dark: 0.5,
PokemonTypes.flying: 2,
PokemonTypes.psychic: 2,
PokemonTypes.fairy: 2,
},
PokemonTypes.poison: {
PokemonTypes.fighting: 0.5,
PokemonTypes.poison: 0.5,
PokemonTypes.bug: 0.5,
PokemonTypes.fairy: 0.5,
PokemonTypes.ground: 2,
PokemonTypes.psychic: 2,
},
PokemonTypes.ground: {
PokemonTypes.electric: 0,
PokemonTypes.poison: 0.5,
PokemonTypes.rock: 0.5,
PokemonTypes.water: 2,
PokemonTypes.grass: 2,
PokemonTypes.ice: 2,
},
PokemonTypes.flying: {
PokemonTypes.ground: 0,
PokemonTypes.grass: 0.5,
PokemonTypes.fighting: 0.5,
PokemonTypes.bug: 0.5,
PokemonTypes.electric: 2,
PokemonTypes.ice: 2,
PokemonTypes.rock: 2,
},
PokemonTypes.psychic: {
PokemonTypes.fighting: 0.5,
PokemonTypes.psychic: 0.5,
PokemonTypes.bug: 2,
PokemonTypes.ghost: 2,
PokemonTypes.dark: 2,
},
PokemonTypes.bug: {
PokemonTypes.grass: 0.5,
PokemonTypes.fighting: 0.5,
PokemonTypes.ground: 0.5,
PokemonTypes.fire: 2,
PokemonTypes.flying: 2,
PokemonTypes.rock: 2,
},
PokemonTypes.rock: {
PokemonTypes.normal: 0.5,
PokemonTypes.fire: 0.5,
PokemonTypes.poison: 0.5,
PokemonTypes.flying: 0.5,
PokemonTypes.water: 2,
PokemonTypes.grass: 2,
PokemonTypes.fighting: 2,
PokemonTypes.ground: 2,
PokemonTypes.steel: 2,
},
PokemonTypes.ghost: {
PokemonTypes.normal: 0,
PokemonTypes.fighting: 0,
PokemonTypes.poison: 0.5,
PokemonTypes.bug: 0.5,
PokemonTypes.ghost: 2,
PokemonTypes.dark: 2,
},
PokemonTypes.dragon: {
PokemonTypes.fire: 0.5,
PokemonTypes.water: 0.5,
PokemonTypes.electric: 0.5,
PokemonTypes.grass: 0.5,
PokemonTypes.ice: 2,
PokemonTypes.dragon: 2,
PokemonTypes.fairy: 2,
},
PokemonTypes.dark: {
PokemonTypes.psychic: 0,
PokemonTypes.ghost: 0.5,
PokemonTypes.dark: 0.5,
PokemonTypes.fighting: 2,
PokemonTypes.bug: 2,
PokemonTypes.fairy: 2,
},
PokemonTypes.steel: {
PokemonTypes.poison: 0,
PokemonTypes.normal: 0.5,
PokemonTypes.grass: 0.5,
PokemonTypes.ice: 0.5,
PokemonTypes.flying: 0.5,
PokemonTypes.psychic: 0.5,
PokemonTypes.bug: 0.5,
PokemonTypes.rock: 0.5,
PokemonTypes.dragon: 0.5,
PokemonTypes.steel: 0.5,
PokemonTypes.fairy: 0.5,
PokemonTypes.fire: 2,
PokemonTypes.fighting: 2,
PokemonTypes.ground: 2,
},
PokemonTypes.fairy: {
PokemonTypes.dragon: 0,
PokemonTypes.fighting: 0.5,
PokemonTypes.bug: 0.5,
PokemonTypes.dark: 0.5,
PokemonTypes.poison: 2,
PokemonTypes.steel: 2,
},
};
| 0
|
mirrored_repositories/flutter_Pokedex/lib/domain
|
mirrored_repositories/flutter_Pokedex/lib/domain/entities/category.dart
|
import 'package:flutter/material.dart';
import 'package:pokedex/routes.dart';
class Category {
const Category({
required this.name,
required this.color,
required this.route,
});
final Color color;
final String name;
final Routes route;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/domain
|
mirrored_repositories/flutter_Pokedex/lib/domain/entities/pokemon.dart
|
import 'package:flutter/material.dart';
import 'pokemon_props.dart';
import 'pokemon_types.dart';
class Pokemon {
const Pokemon({
required this.number,
required this.name,
required this.description,
required this.types,
required this.image,
required this.height,
required this.weight,
required this.genera,
required this.eggGroups,
required this.gender,
required this.stats,
required this.baseExp,
required this.evolutions,
required this.evolutionReason,
});
final String number;
final String name;
final String description;
final List<PokemonTypes> types;
final String image;
final String height;
final String weight;
final String genera;
final List<String> eggGroups;
final PokemonGender gender;
final PokemonStats stats;
final double baseExp;
final List<Pokemon> evolutions;
final String evolutionReason;
}
extension PokemonX on Pokemon {
Color get color => types.first.color;
Map<PokemonTypes, double> get typeEffectiveness {
final effectiveness =
PokemonTypes.values.where((element) => element != PokemonTypes.unknown).map(
(type) => MapEntry(
type,
types
.map((pokemonType) => pokemonType.effectiveness[type] ?? 1.0)
.reduce((total, effectiveness) => total * effectiveness),
),
);
return Map.fromEntries(effectiveness);
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/domain
|
mirrored_repositories/flutter_Pokedex/lib/domain/entities/item.dart
|
class Item {
const Item({
required this.name,
required this.image,
required this.category,
required this.effect,
});
final String name;
final String image;
final String category;
final String effect;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/domain
|
mirrored_repositories/flutter_Pokedex/lib/domain/entities/type_color.dart
|
import 'package:flutter/material.dart';
import 'package:pokedex/configs/colors.dart';
import 'package:pokedex/domain/entities/pokemon_types.dart';
Color colorGenerator(PokemonTypes val) {
switch (val) {
case PokemonTypes.grass:
case PokemonTypes.bug:
return AppColors.lightTeal;
case PokemonTypes.fire:
return AppColors.lightRed;
case PokemonTypes.water:
return AppColors.lightBlue;
case PokemonTypes.normal:
case PokemonTypes.flying:
return AppColors.semiGrey;
case PokemonTypes.fighting:
return AppColors.brown;
case PokemonTypes.electric:
case PokemonTypes.psychic:
return AppColors.lightYellow;
case PokemonTypes.poison:
case PokemonTypes.ghost:
return AppColors.lightPurple;
case PokemonTypes.ground:
case PokemonTypes.rock:
return AppColors.lightBrown;
case PokemonTypes.dark:
return AppColors.black;
case PokemonTypes.fairy:
return AppColors.lightPink;
default:
return AppColors.lightBlue;
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/domain
|
mirrored_repositories/flutter_Pokedex/lib/domain/entities/pokemon_props.dart
|
class PokemonGender {
final bool genderless;
final double male;
final double female;
PokemonGender({
required this.genderless,
required this.male,
required this.female,
});
}
class PokemonStats {
const PokemonStats({
required this.attack,
required this.specialAttack,
required this.defense,
required this.specialDefense,
required this.hp,
required this.speed,
});
final int attack;
final int specialAttack;
final int defense;
final int specialDefense;
final int hp;
final int speed;
int get total => attack + specialAttack + defense + specialDefense + hp + speed;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/domain
|
mirrored_repositories/flutter_Pokedex/lib/domain/entities/generation.dart
|
class Generation {
const Generation({
required this.title,
required this.pokemons,
});
final List<String> pokemons;
final String title;
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/domain
|
mirrored_repositories/flutter_Pokedex/lib/domain/usecases/item_usecases.dart
|
import 'package:pokedex/core/usecase.dart';
import '../../data/repositories/item_repository.dart';
import '../entities/item.dart';
class GetItemUseCase extends NoParamsUseCase<List<Item>> {
const GetItemUseCase(this.repository);
final ItemRepository repository;
@override
Future<List<Item>> call() {
return repository.getAllItems();
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib/domain
|
mirrored_repositories/flutter_Pokedex/lib/domain/usecases/pokemon_usecases.dart
|
import '../../core/usecase.dart';
import '../../data/repositories/pokemon_repository.dart';
import '../entities/pokemon.dart';
class GetAllPokemonsUseCase extends NoParamsUseCase<List<Pokemon>> {
const GetAllPokemonsUseCase(this.repository);
final PokemonRepository repository;
@override
Future<List<Pokemon>> call() {
return repository.getAllPokemons();
}
}
class GetPokemonsParams {
const GetPokemonsParams({
required this.page,
required this.limit,
});
final int page;
final int limit;
}
class GetPokemonsUseCase extends UseCase<List<Pokemon>, GetPokemonsParams> {
const GetPokemonsUseCase(this.repository);
final PokemonRepository repository;
@override
Future<List<Pokemon>> call(GetPokemonsParams params) {
return repository.getPokemons(page: params.page, limit: params.limit);
}
}
class GetPokemonParam {
final String number;
const GetPokemonParam(this.number);
}
class GetPokemonUseCase extends UseCase<Pokemon?, GetPokemonParam> {
final PokemonRepository repository;
const GetPokemonUseCase(this.repository);
@override
Future<Pokemon?> call(GetPokemonParam params) {
return repository.getPokemon(params.number);
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/configs/images.dart
|
import 'package:flutter/material.dart';
const String _imagePath = 'assets/images';
class _Image extends AssetImage {
const _Image(String fileName) : super('$_imagePath/$fileName');
}
class AppImages {
static const bulbasaur = _Image('bulbasaur.png');
static const charmander = _Image('charmander.png');
static const squirtle = _Image('squirtle.png');
static const pokeball = _Image('pokeball.png');
static const male = _Image('male.png');
static const female = _Image('female.png');
static const dotted = _Image('dotted.png');
static const thumbnail = _Image('thumbnail.png');
static const pikloader = _Image('pika_loader.gif');
static Future precacheAssets(BuildContext context) async {
await precacheImage(bulbasaur, context);
await precacheImage(charmander, context);
await precacheImage(squirtle, context);
await precacheImage(pokeball, context);
await precacheImage(male, context);
await precacheImage(female, context);
await precacheImage(dotted, context);
await precacheImage(thumbnail, context);
await precacheImage(pikloader, context);
}
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/configs/durations.dart
|
const animationDuration = Duration(milliseconds: 260);
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/configs/constants.dart
|
import 'dart:ui';
class AppConstants {
static const Size designScreenSize = Size(375, 754);
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/configs/colors.dart
|
import 'package:flutter/material.dart';
class AppColors {
static const Color beige = Color(0xFFA8A878);
static const Color black = Color(0xFF303943);
static const Color blue = Color(0xFF429BED);
static const Color brown = Color(0xFFB1736C);
static const Color darkBrown = Color(0xD0795548);
static const Color darkGrey = Color(0xFF303943);
static const Color grey = Color(0x64303943);
static const Color indigo = Color(0xFF6C79DB);
static const Color lightBlue = Color(0xFF7AC7FF);
static const Color lightBrown = Color(0xFFCA8179);
static const Color whiteGrey = Color(0xFFFDFDFD);
static const Color lightCyan = Color(0xFF98D8D8);
static const Color lightGreen = Color(0xFF78C850);
static const Color lighterGrey = Color(0xFFF4F5F4);
static const Color lightGrey = Color(0xFFF5F5F5);
static const Color lightPink = Color(0xFFEE99AC);
static const Color lightPurple = Color(0xFF9F5BBA);
static const Color lightRed = Color(0xFFFB6C6C);
static const Color lightTeal = Color(0xFF48D0B0);
static const Color lightYellow = Color(0xFFFFCE4B);
static const Color lilac = Color(0xFFA890F0);
static const Color pink = Color(0xFFF85888);
static const Color purple = Color(0xFF7C538C);
static const Color red = Color(0xFFFA6555);
static const Color teal = Color(0xFF4FC1A6);
static const Color yellow = Color(0xFFF6C747);
static const Color semiGrey = Color(0xFFbababa);
static const Color violet = Color(0xD07038F8);
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/configs/theme.dart
|
import 'package:flutter/material.dart';
import 'package:pokedex/configs/colors.dart';
import 'fonts.dart';
class Themings {
static final TextStyle darkText = TextStyle(
color: AppColors.whiteGrey,
fontFamily: AppFonts.circularStd,
);
static final TextStyle lightText = TextStyle(
color: AppColors.black,
fontFamily: AppFonts.circularStd,
);
static final ThemeData darkTheme = ThemeData(
primarySwatch: Colors.blue,
backgroundColor: AppColors.black,
brightness: Brightness.dark,
primaryColor: AppColors.blue,
appBarTheme: AppBarTheme(
toolbarTextStyle: darkText,
),
textTheme: TextTheme(
bodyText1: darkText,
bodyText2: darkText,
labelMedium: darkText,
caption: darkText,
button: darkText,
overline: darkText,
),
scaffoldBackgroundColor: AppColors.black,
);
static final ThemeData lightTheme = ThemeData(
primarySwatch: Colors.blue,
backgroundColor: AppColors.whiteGrey,
brightness: Brightness.light,
primaryColor: AppColors.blue,
appBarTheme: AppBarTheme(
toolbarTextStyle: lightText,
),
textTheme: TextTheme(
bodyText1: lightText,
bodyText2: lightText,
labelMedium: lightText,
caption: lightText,
button: lightText,
overline: lightText,
),
scaffoldBackgroundColor: AppColors.lightGrey,
);
}
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/configs/types.dart
|
import 'package:flutter/material.dart';
import 'package:pokedex/domain/entities/pokemon_types.dart';
class PokeTypes {
const PokeTypes({
required this.type,
required this.superEffective,
required this.notEffective,
required this.nilEffective,
required this.color,
});
final PokemonTypes type;
final List<String> superEffective;
final List<String> notEffective;
final List<String> nilEffective;
final Color color;
}
List<PokeTypes> tps = [];
const List<PokeTypes> types = [
PokeTypes(
type: PokemonTypes.normal,
superEffective: [],
notEffective: ["Rock", "Steel"],
nilEffective: ["Ghost"],
color: Color(0xFFa8a8a8),
),
PokeTypes(
type: PokemonTypes.fire,
superEffective: ["Bug", "Steel", "Grass", "Ice"],
notEffective: ["Rock", "Fire", "Water", "Dragon"],
nilEffective: [],
color: Color(0xFFf08030),
),
PokeTypes(
type: PokemonTypes.water,
notEffective: ["Water", "Grass", "Dragon"],
superEffective: ["Ground", "Rock", "Fire"],
nilEffective: [],
color: Color(0xFF6890f0),
),
PokeTypes(
type: PokemonTypes.electric,
notEffective: ["Grass", "Electric", "Dragon"],
superEffective: ["Flying", "Water"],
nilEffective: ["Ground"],
color: Color(0xFFf8b00f),
),
PokeTypes(
type: PokemonTypes.grass,
nilEffective: [],
superEffective: ["Ground", "Rock", "Water"],
notEffective: ["Flying", "Poison", "Bug", "Steel", "Fire", "Grass", "Dragon"],
color: Color(0xFF78c851),
),
PokeTypes(
type: PokemonTypes.ice,
notEffective: ["Steel", "Fire", "Water", "Ice"],
superEffective: ["Flying", "Ground", "Grass", "Dragon"],
nilEffective: [],
color: Color(0xFF98d9d8),
),
PokeTypes(
type: PokemonTypes.fighting,
notEffective: ["Flying", "Poison", "Bug", "Psychic", "Fairy"],
superEffective: ["Normal", "Rock", "Steel", "Ice", "Dark"],
nilEffective: ["Ghost"],
color: Color(0xFFe83001),
),
PokeTypes(
type: PokemonTypes.poison,
superEffective: ["Grass", "Fairy"],
nilEffective: ["Steel"],
notEffective: ["Poison", "Ground", "Rock", "Ghost"],
color: Color(0xFFa040a0),
),
PokeTypes(
type: PokemonTypes.ground,
nilEffective: ["Flying"],
superEffective: ["Poison", "Rock", "Steel", "Fire", "Electric"],
notEffective: ["Bug", "Grass"],
color: Color(0xFFd8e02f),
),
PokeTypes(
type: PokemonTypes.flying,
notEffective: ["Rock", "Steel", "Electric"],
superEffective: ["Fighting", "Bug", "Grass"],
nilEffective: [],
color: Color(0xFF9f94be),
),
PokeTypes(
type: PokemonTypes.psychic,
notEffective: ["Steel", "Psychic"],
superEffective: ["Fighting", "Poison"],
nilEffective: ["Dark"],
color: Color(0xFFf85888),
),
PokeTypes(
type: PokemonTypes.bug,
nilEffective: [],
superEffective: ["Grass", "Psychic", "Dark"],
notEffective: ["Fighting", "Flying", "Poison", "Ghost", "Steel", "Fire", "Fairy"],
color: Color(0xFFa8b821),
),
PokeTypes(
type: PokemonTypes.rock,
nilEffective: [],
superEffective: ["Flying", "Bug", "Fire", "Ice"],
notEffective: ["Fighting", "Ground", "Steel"],
color: Color(0xFFb8a038),
),
PokeTypes(
type: PokemonTypes.ghost,
notEffective: ["Dark"],
nilEffective: ["Normal"],
superEffective: ["Ghost", "Psychic"],
color: Color(0xFF5d4674),
),
PokeTypes(
type: PokemonTypes.dragon,
superEffective: ["Dragon"],
nilEffective: ["Fairy"],
notEffective: ["Steel"],
color: Color(0xFF623bd5),
),
PokeTypes(
type: PokemonTypes.dark,
superEffective: ["Ghost", "Psychic"],
nilEffective: [],
notEffective: ["Fighting", "Dark", "Fairy"],
color: Color(0xFF776554),
),
PokeTypes(
type: PokemonTypes.steel,
superEffective: ["Rock", "Ice", "Fairy"],
nilEffective: [],
notEffective: ["Steel", "Fire", "Water", "Electric"],
color: Color(0xFFb1adbb),
),
PokeTypes(
type: PokemonTypes.fairy,
notEffective: ["Poison", "Steel", "Fire"],
nilEffective: [],
superEffective: ["Fighting", "Dragon", "Dark"],
color: Color(0xFFf8b8e8),
)
];
| 0
|
mirrored_repositories/flutter_Pokedex/lib
|
mirrored_repositories/flutter_Pokedex/lib/configs/fonts.dart
|
class AppFonts {
static const circularStd = 'CircularStd';
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.