repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/youtube/lib
|
mirrored_repositories/youtube/lib/components/detailed_button.dart
|
import 'package:flutter/material.dart';
class CustomButton extends StatelessWidget {
final IconData startIcon;
final String label;
final String value;
final VoidCallback onPressed;
const CustomButton({super.key,
required this.startIcon,
required this.label,
required this.value,
required this.onPressed,
});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(8),
),
child: SizedBox(
width: 250,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Icon(startIcon),
const SizedBox(width: 16),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label,style: const TextStyle(
fontSize: 12,
color: Colors.grey,
),),
Text(value),
],
)
],
),
const Icon(Icons.arrow_circle_right),
],
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/youtube/lib
|
mirrored_repositories/youtube/lib/components/youtube_video.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:youtube/components/user_avatar.dart';
import 'package:youtube/models/user.dart';
import 'package:youtube/models/video.dart';
class YoutubeVideo extends StatefulWidget {
final Video video;
final BuildContext context;
const YoutubeVideo({super.key, required this.video,required this.context});
@override
State<YoutubeVideo> createState() => _YoutubeVideoState();
}
class _YoutubeVideoState extends State<YoutubeVideo> {
String getTime() {
final currentTime = DateTime.now().millisecondsSinceEpoch;
final durationMilli = currentTime - widget.video.uploadTime;
var text = "";
if (durationMilli>=1000) {
final seconds = (durationMilli/1000).round();
if (seconds>=60){
final minutes = (seconds/60).round();
if (minutes>=60) {
final hours = (minutes/60).round();
if (hours>=24) {
var days = (hours/24).round();
text = "$days days"; //More can be added
}
else {
text = "$hours hours";
}
}
else {
text = "$minutes minutes";
}
}
else {
text = "$seconds seconds";
}
}
return text;
}
UserModel? user;
void getUploader()async {
final userDoc = await FirebaseFirestore.instance.collection("users")
.doc(widget.video.ownerId).get();
setState(() {
user = UserModel.fromJson(userDoc.data()!);
});
}
void gotoUser() {
}
@override
void initState() {
getUploader();
super.initState();
}
Widget buildBottomWidget() {
const detailsTextStyle = TextStyle(fontSize: 10,color: Colors.grey);
return SizedBox(
width: 200,
child: Column(
children: [
Text(widget.video.title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
Row(
children: [
Text(user?.name??"",style: detailsTextStyle,),
const SizedBox(width: 8,),
Text("${widget.video.views} views",style: detailsTextStyle,),
const SizedBox(width: 8,),
Text("${getTime()} ago",style: detailsTextStyle,)
],
)
],
),
);
}
void _openMenu() {
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Card(
elevation: 8,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16.0),
),
clipBehavior: Clip.hardEdge,
margin: const EdgeInsets.only(left: 16,right: 16),
child: InkWell(
child:
Stack(
children: [
Image.network(widget.video.thumbnail),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: buildBottom(context),
)
],
)
,
),
),
);
}
Container buildBottom(BuildContext context) {
return Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface.withAlpha(150)
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
UserAvatar(profileImage: user?.profileImage, onPress: gotoUser),
buildBottomWidget(),
IconButton(
onPressed: _openMenu,
icon: Icon(Icons.more_vert_outlined,
color: Theme.of(context).colorScheme.inverseSurface,),
)
],
),
);
}
}
| 0
|
mirrored_repositories/youtube/lib
|
mirrored_repositories/youtube/lib/models/video.dart
|
enum VideoPrivacy {
public,
private,
linkOnly
}
class Video {
final String id;
final String title;
final String description;
final VideoPrivacy privacy;
final String thumbnail;
final int views;
final int likes;
final int dislikes;
final int comments;
final String ownerId;
final int uploadTime;
Video({
required this.id,
required this.title,
required this.description,
required this.thumbnail,
required this.privacy,
required this.ownerId,
required this.uploadTime,
this.views = 0,
this.likes = 0,
this.dislikes = 0,
this.comments = 0,
});
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
'description': description,
'privacy': privacy.toString(),
'thumbnail': thumbnail,
'views': views,
'likes': likes,
'dislikes': dislikes,
'comments': comments,
'ownerId': ownerId,
"uploadTime": uploadTime,
};
}
factory Video.fromJson(Map<String, dynamic> json) {
return Video(
id: json['id'],
title: json['title'],
description: json['description'],
privacy: _parsePrivacy(json['privacy']),
thumbnail: json['thumbnail'],
views: json['views'] ?? 0,
likes: json['likes'] ?? 0,
dislikes: json['dislikes'] ?? 0,
comments: json['comments'] ?? 0,
ownerId: json['ownerId'],
uploadTime: json["uploadTime"],
);
}
static VideoPrivacy _parsePrivacy(String privacy) {
switch (privacy) {
case 'VideoPrivacy.public':
return VideoPrivacy.public;
case 'VideoPrivacy.private':
return VideoPrivacy.private;
case 'VideoPrivacy.linkOnly':
return VideoPrivacy.linkOnly;
default:
throw ArgumentError("Invalid VideoPrivacy value: $privacy");
}
}
}
| 0
|
mirrored_repositories/youtube/lib
|
mirrored_repositories/youtube/lib/models/channel.dart
|
class Channel {
final String id;
final String username;
final String displayName;
final String profileImage;
final String description;
final String banner;
final int totalViews;
final int videoCount;
Channel({
required this.id,
required this.username,
required this.displayName,
required this.description,
this.profileImage='assets/ProfileImage.png',
this.banner = '',
this.totalViews = 0,
this.videoCount = 0,
});
Map<String, dynamic> toJson() {
return {
'id': id,
'username': username,
'displayName': displayName,
'profileImage': profileImage,
'banner': banner,
'totalViews': totalViews,
'videoCount' : videoCount,
'description': description,
};
}
factory Channel.fromJson(Map<String, dynamic> json) {
return Channel(
id: json['id'],
username: json['username'],
displayName: json['displayName'],
profileImage: json['profileImage'],
banner: json['banner'],
totalViews: json['totalViews'],
videoCount: json['videoCount'],
description: json['description'],
);
}
}
| 0
|
mirrored_repositories/youtube/lib
|
mirrored_repositories/youtube/lib/models/user.dart
|
class UserModel {
final String id;
final String name;
final String username;
final String email;
String? profileImage;
UserModel({
required this.id,
required this.name,
required this.username,
required this.email,
this.profileImage,
});
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'username': username,
'email': email,
'profileImage': profileImage,
};
}
factory UserModel.fromJson(Map<String, dynamic> json) {
return UserModel(
id: json['id'],
name: json['name'],
username: json['username'],
email: json['email'],
profileImage: json['profileImage'],
);
}
}
| 0
|
mirrored_repositories/pokedex_flutter
|
mirrored_repositories/pokedex_flutter/lib/session.dart
|
// imports nativos do flutter
import 'package:flutter/material.dart';
// imports das telas
import 'package:pokedex/app/core/services/shared.dart';
// import dos domain
import 'package:pokedex/domain/source/remote/credentials.dart';
import 'package:pokedex/domain/source/remote/app_events.dart';
import 'package:pokedex/domain/source/remote/crash.dart';
class Session {
static GlobalKey<NavigatorState> globalContext = GlobalKey<NavigatorState>();
static final SharedServices sharedServices = SharedServices();
static final Credentials credentials = Credentials();
static final AppEvents appEvents = AppEvents();
static final Crash crash = Crash();
}
| 0
|
mirrored_repositories/pokedex_flutter
|
mirrored_repositories/pokedex_flutter/lib/main.dart
|
// imports nativos
import 'package:flutter/material.dart';
import 'dart:ui';
// imports globais
import 'package:pokedex/session.dart';
// import dos app
import 'package:pokedex/app/core/services/languages.dart';
import 'package:pokedex/app/core/routes/routes.dart';
import 'package:pokedex/app/core/style/themes.dart';
// import dos domain
import 'package:pokedex/domain/source/local/mobx/connection/connection.dart';
import 'package:pokedex/domain/source/local/injection/injection.dart';
// import dos pacotes
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:firebase_performance/firebase_performance.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:provider/provider.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
PlatformDispatcher.instance.onError = ( error, stackTrace ) {
FirebaseCrashlytics.instance.recordError(error, stackTrace, fatal: true);
return true;
};
FirebasePerformance.instance;
configureDependencies();
runApp(
MultiProvider(
providers: [
Provider(
create: (context) => ConnectionMobx(),
),
],
child: MaterialApp(
navigatorKey: Session.globalContext,
title: "Pokédex",
theme: Themes.lightTheme,
onGenerateRoute: Routes.generateRoutes,
initialRoute: "/splash",
supportedLocales: supportedLocale,
localizationsDelegates: localizationsDelegate,
debugShowCheckedModeBanner: false,
),
),
);
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app
|
mirrored_repositories/pokedex_flutter/lib/app/pages/splash.dart
|
// pacotes nativos flutter
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
// import das telas
import 'package:pokedex/app/core/style/app_images.dart';
class SplashPage extends StatefulWidget {
const SplashPage({Key? key}) : super(key: key);
@override
State<SplashPage> createState() => _SplashPageState();
}
class _SplashPageState extends State<SplashPage> {
@override
void initState() {
super.initState();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
Timer(
const Duration(seconds: 3),
() => Navigator.pushNamedAndRemoveUntil(
context,
"/",
(route) => false,
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).colorScheme.secondary,
body: Container(
padding: const EdgeInsets.all(16),
child: Center(
child: Image.asset(
AppImages.logo,
width: 150,
),
),
),
);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/pages
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home/detail.dart
|
// imports nativos
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// imports globais
import 'package:pokedex/session.dart';
// import das telas
import 'package:pokedex/app/pages/home/widgets/loading_detail.dart';
import 'package:pokedex/app/core/widgets/loading_connection.dart';
import 'package:pokedex/app/core/widgets/pokedex_card.dart';
import 'package:pokedex/app/pages/home/mobx/pokemon.dart';
import 'package:pokedex/app/core/style/app_colors.dart';
import 'package:pokedex/app/core/style/app_images.dart';
// import dos domain
import 'package:pokedex/domain/source/local/mobx/connection/connection.dart';
import 'package:pokedex/domain/entities/pokemon.dart';
// import dos pacotes
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:provider/provider.dart';
class DetailPage extends StatefulWidget {
final PokemonEntity pokemon;
const DetailPage({ Key? key, required this.pokemon }) : super(key: key);
@override
State<DetailPage> createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
final PokemonMobx _mobx = PokemonMobx();
late ConnectionMobx _connectionMobx;
@override
void initState() {
super.initState();
Session.appEvents.sendScreen("detail");
}
@override
void didChangeDependencies() async {
super.didChangeDependencies();
_connectionMobx = Provider.of<ConnectionMobx>(context);
await _mobx.getPokemon(widget.pokemon.id);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Observer(
builder: (builder) {
return ( _mobx.pokemon == null )
? LoadingDetail(
pokemon: widget.pokemon,
)
: Scaffold(
backgroundColor: _mobx.pokemon?.primaryColor,
appBar: AppBar(
systemOverlayStyle: SystemUiOverlayStyle(
statusBarColor: _mobx.pokemon?.primaryColor
),
title: Text(
_mobx.pokemon?.name ?? widget.pokemon.name,
),
backgroundColor: _mobx.pokemon?.primaryColor,
actions: [
Padding(
padding: const EdgeInsets.only( right: 16 ),
child: Text(
"# ${_mobx.pokemon?.id ?? widget.pokemon.id}",
style: TextStyle(
color: theme.scaffoldBackgroundColor,
fontWeight: FontWeight.w700,
fontSize: 18,
),
),
),
],
),
body: ( !Session.sharedServices.validateConnection(_connectionMobx) )
? const LoadingConnection()
: Container(
decoration: BoxDecoration(
color: _mobx.pokemon!.primaryColor,
image: DecorationImage(
image: AssetImage(AppImages.pokeBall),
fit: BoxFit.scaleDown,
alignment: Alignment.topRight,
scale: 1.5,
opacity: 98,
),
),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Stack(
children: [
Padding(
padding: const EdgeInsets.only( top: 155 ),
child: PokedexCardWidget(
body: Padding(
padding: const EdgeInsets.only( top: 35 ),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for ( final types in _mobx.pokemon!.types! )
Padding(
padding: const EdgeInsets.only( right: 10 ),
child: RawChip(
backgroundColor: types.color,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular( 20 ),
),
label: Text(
types.type,
style: theme.textTheme.displaySmall!.apply(color: theme.scaffoldBackgroundColor),
),
),
),
],
),
Padding(
padding: const EdgeInsets.symmetric( vertical: 16 ),
child: Text(
FlutterI18n.translate(context, "pages.detail.about"),
style: theme.textTheme.displayMedium!.apply( color: _mobx.pokemon!.primaryColor ),
),
),
Row(
children: [
Expanded(
flex: 2,
child: ListTile(
title: Text(
"${Session.sharedServices.convertValue(_mobx.pokemon!.weight!)} KG",
style: theme.textTheme.bodyMedium,
),
subtitle: Text(
FlutterI18n.translate(context, "pages.detail.weight"),
style: theme.textTheme.bodySmall,
),
),
),
Expanded(
flex: 2,
child: ListTile(
title: Text(
"${Session.sharedServices.convertValue(_mobx.pokemon!.height!)} m",
style: theme.textTheme.bodyMedium,
),
subtitle: Text(
FlutterI18n.translate(context, "pages.detail.height"),
style: theme.textTheme.bodySmall,
),
),
),
Expanded(
flex: 3,
child: ListTile(
title: Column(
children: [
for ( final item in _mobx.pokemon!.abilities! )
Text(
item.ability,
style: theme.textTheme.bodySmall,
textAlign: TextAlign.center,
),
],
),
subtitle: Text(
FlutterI18n.translate(context, "pages.detail.abilities"),
style: theme.textTheme.bodyMedium,
textAlign: TextAlign.center,
),
),
),
],
),
Padding(
padding: const EdgeInsets.symmetric( vertical: 15 ),
child: Text(
FlutterI18n.translate(context, "pages.detail.stats"),
style: theme.textTheme.displayMedium!.apply( color: _mobx.pokemon!.primaryColor ),
),
),
for ( final item in _mobx.pokemon!.stats! )
ListTile(
leading: Text.rich(
TextSpan(
text: item.attributeAbbreviation,
style: theme.textTheme.displaySmall!.apply( color: _mobx.pokemon!.primaryColor ),
children: [
TextSpan(
text: " ${item.value}",
style: theme.textTheme.bodySmall,
),
],
),
),
title: LinearProgressIndicator(
minHeight: 5,
value: item.value / 250,
color: _mobx.pokemon!.primaryColor,
backgroundColor: _mobx.pokemon!.primaryColor.withOpacity(0.25),
),
),
],
),
),
),
),
Positioned(
top: 80,
child: TextButton(
onPressed: () => _mobx.getPokemon(_mobx.pokemon!.id - 1),
child: const FaIcon(
FontAwesomeIcons.circleArrowLeft,
color: AppColors.white,
size: 25,
),
),
),
Positioned(
top: 80,
right: 0,
child: TextButton(
onPressed: () => _mobx.getPokemon(_mobx.pokemon!.id + 1),
child: const FaIcon(
FontAwesomeIcons.circleArrowRight,
color: AppColors.white,
size: 25,
),
),
),
Positioned(
top: 8,
child: Center(
widthFactor: 1.8,
child: Image.network(
_mobx.pokemon!.image,
height: 200,
),
),
),
],
),
],
),
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/pages
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home/home.dart
|
// imports nativos
import 'package:flutter/material.dart';
// imports globais
import 'package:pokedex/session.dart';
// import das telas
import 'package:pokedex/app/pages/home/widgets/loading_pokemon.dart';
import 'package:pokedex/app/core/widgets/loading_connection.dart';
import 'package:pokedex/app/pages/home/cubit/home_cubit.dart';
import 'package:pokedex/app/core/widgets/pokedex_card.dart';
import 'package:pokedex/app/core/style/app_images.dart';
// import dos domain
import 'package:pokedex/domain/source/local/mobx/connection/connection.dart';
import 'package:pokedex/domain/source/local/injection/injection.dart';
import 'package:pokedex/domain/entities/pokemon.dart';
// import dos pacotes
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:provider/provider.dart';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
Session.appEvents.sendScreen("home");
final connectionMobx = Provider.of<ConnectionMobx>(context);
connectionMobx.connectivity.onConnectivityChanged.listen(connectionMobx.updateConnectionStatus);
final ThemeData theme = Theme.of(context);
return Observer(
builder: (builder) {
return Scaffold(
backgroundColor: theme.colorScheme.secondary,
appBar: AppBar(
toolbarHeight: 70,
leading: CircleAvatar(
backgroundColor: theme.colorScheme.secondary,
child: Image.asset(
AppImages.pokeBall,
width: 30,
),
),
title: Text(
FlutterI18n.translate(builder, "app_name"),
style: theme.textTheme.headlineLarge,
),
),
body: ( !Session.sharedServices.validateConnection(connectionMobx) )
? const LoadingConnection()
: BlocProvider(
create: (create) => getIt<HomeCubit>(),
child: BlocBuilder<HomeCubit, HomeCubitState>(
builder: ( blocBuilder, state ) {
final bloc = BlocProvider.of<HomeCubit>(blocBuilder);
if ( !bloc.isLoaded ) {
clearPagination();
bloc.scrollController.addListener(() {
if ( bloc.scrollController.position.maxScrollExtent == bloc.scrollController.position.pixels ) {
bloc.loadMore();
}
});
bloc.getPokemon();
}
if ( state is HomeInitial || state is HomeStateLoading ) {
return const LoadingPokemonWidget();
}
if ( state is HomeStateError || bloc.listPokemon.isEmpty ) {
return PokedexCardWidget(
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
AppImages.darkrai,
height: 150,
),
Padding(
padding: const EdgeInsets.only( top: 15 ),
child: Text(
FlutterI18n.translate(blocBuilder, "routes.empty"),
textAlign: TextAlign.center,
style: theme.textTheme.bodySmall,
),
),
],
),
);
}
return PokedexCardWidget(
body: RefreshIndicator(
onRefresh: () => bloc.refresh(),
child: GridView.builder(
controller: bloc.scrollController,
itemCount: bloc.listPokemon.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemBuilder: ( itemBuilder, index ) {
PokemonEntity pokemon = bloc.listPokemon[index];
return GestureDetector(
onTap: () => bloc.goToDetail(pokemon),
child: Card(
shadowColor: Colors.grey,
child: GridTile(
header: Padding(
padding: const EdgeInsets.fromLTRB(0, 10, 8, 0),
child: Text(
"# ${pokemon.id}",
textAlign: TextAlign.end,
style: theme.textTheme.bodySmall,
),
),
footer: GridTileBar(
backgroundColor: theme.colorScheme.primary.withOpacity(0.8),
title: Text(
pokemon.name,
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium,
),
),
child: Image.network(
pokemon.image,
),
),
),
);
},
),
),
);
},
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home/widgets/loading_detail.dart
|
// imports nativos
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// import das telas
import 'package:pokedex/app/core/widgets/pokedex_card.dart';
import 'package:pokedex/app/core/style/app_images.dart';
import 'package:pokedex/app/core/style/app_colors.dart';
import 'package:pokedex/domain/entities/pokemon.dart';
// import dos paoctes
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:shimmer_animation/shimmer_animation.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
class LoadingDetail extends StatelessWidget {
final PokemonEntity pokemon;
const LoadingDetail({ Key? key, required this.pokemon }) : super(key: key);
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
backgroundColor: AppColors.neutralGreen,
systemOverlayStyle: const SystemUiOverlayStyle(
statusBarColor: AppColors.neutralGreen,
),
title: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
pokemon.name,
),
),
actions: [
Padding(
padding: const EdgeInsets.only( right: 16 ),
child: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"# ${pokemon.id}",
style: TextStyle(
color: theme.scaffoldBackgroundColor,
fontWeight: FontWeight.w700,
fontSize: 18,
),
),
),
),
],
),
body: Container(
decoration: BoxDecoration(
color: AppColors.neutralGreen,
image: DecorationImage(
image: AssetImage(AppImages.pokeBall),
fit: BoxFit.scaleDown,
alignment: Alignment.topRight,
scale: 1.5,
opacity: 98,
),
),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Stack(
children: [
Padding(
padding: const EdgeInsets.only( top: 155 ),
child: PokedexCardWidget(
body: Padding(
padding: const EdgeInsets.only( top: 35 ),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only( right: 10 ),
child: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: RawChip(
backgroundColor: AppColors.neutralGreen,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular( 20 ),
),
label: Text(
"Normal",
style: theme.textTheme.displaySmall!.apply(color: theme.scaffoldBackgroundColor),
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric( vertical: 16 ),
child: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
FlutterI18n.translate(context, "pages.detail.about"),
style: theme.textTheme.displayMedium!.apply( color: AppColors.neutralGreen ),
),
),
),
Row(
children: [
Expanded(
child: ListTile(
leading: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: const FaIcon(
FontAwesomeIcons.weightHanging,
),
),
title: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"2.5 KG",
style: theme.textTheme.bodyMedium,
),
),
subtitle: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
FlutterI18n.translate(context, "pages.detail.weight"),
style: theme.textTheme.bodySmall,
),
),
),
),
Expanded(
child: ListTile(
leading: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: const FaIcon(
FontAwesomeIcons.rulerVertical,
),
),
title: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"0.9 m",
style: theme.textTheme.bodyMedium,
),
),
subtitle: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
FlutterI18n.translate(context, "pages.detail.height"),
style: theme.textTheme.bodySmall,
),
),
),
),
Expanded(
child: ListTile(
title: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"Synchronize",
style: theme.textTheme.bodySmall,
),
),
subtitle: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
FlutterI18n.translate(context, "pages.detail.abilities"),
style: theme.textTheme.bodySmall,
),
),
),
),
],
),
Padding(
padding: const EdgeInsets.symmetric( vertical: 15 ),
child: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
FlutterI18n.translate(context, "pages.detail.stats"),
style: theme.textTheme.displayMedium!.apply( color: AppColors.neutralGreen ),
),
),
),
ListTile(
leading: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"HP",
style: theme.textTheme.displaySmall!.apply( color: AppColors.neutralGreen ),
),
),
title: LinearProgressIndicator(
minHeight: 5,
value: 100 / 250,
color: AppColors.neutralGreen,
backgroundColor: AppColors.neutralGreen.withOpacity(0.25),
),
),
ListTile(
leading: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"ATK",
style: theme.textTheme.displaySmall!.apply( color: AppColors.neutralGreen ),
),
),
title: LinearProgressIndicator(
minHeight: 5,
value: 100 / 250,
color: AppColors.neutralGreen,
backgroundColor: AppColors.neutralGreen.withOpacity(0.25),
),
),
ListTile(
leading: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"DEF",
style: theme.textTheme.displaySmall!.apply( color: AppColors.neutralGreen ),
),
),
title: LinearProgressIndicator(
minHeight: 5,
value: 100 / 250,
color: AppColors.neutralGreen,
backgroundColor: AppColors.neutralGreen.withOpacity(0.25),
),
),
ListTile(
leading: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"SATK",
style: theme.textTheme.displaySmall!.apply( color: AppColors.neutralGreen ),
),
),
title: LinearProgressIndicator(
minHeight: 5,
value: 100 / 250,
color: AppColors.neutralGreen,
backgroundColor: AppColors.neutralGreen.withOpacity(0.25),
),
),
ListTile(
leading: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"SDEF",
style: theme.textTheme.displaySmall!.apply( color: AppColors.neutralGreen ),
),
),
title: LinearProgressIndicator(
minHeight: 5,
value: 100 / 250,
color: AppColors.neutralGreen,
backgroundColor: AppColors.neutralGreen.withOpacity(0.25),
),
),
ListTile(
leading: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"SPD",
style: theme.textTheme.displaySmall!.apply( color: AppColors.neutralGreen ),
),
),
title: LinearProgressIndicator(
minHeight: 5,
value: 100 / 250,
color: AppColors.neutralGreen,
backgroundColor: AppColors.neutralGreen.withOpacity(0.25),
),
),
],
),
),
),
),
Positioned(
top: 80,
left: 15,
child: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: const FaIcon(
FontAwesomeIcons.circleArrowLeft,
color: AppColors.white,
size: 25,
),
),
),
Positioned(
top: 80,
right: 15,
child: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: const FaIcon(
FontAwesomeIcons.circleArrowRight,
color: AppColors.white,
size: 25,
),
),
),
Positioned(
top: 8,
child: Center(
widthFactor: 1.8,
child: Image.network(
pokemon.image,
height: 200,
),
),
),
],
),
],
),
),
),
);
}
}
/*
GridView.builder(
itemCount: 6,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemBuilder: (builder, index) {
return Card(
shadowColor: Colors.grey,
child: GridTile(
header: Padding(
padding: const EdgeInsets.fromLTRB(0, 10, 8, 0),
child: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"# 150",
textAlign: TextAlign.end,
style: theme.textTheme.bodySmall,
),
),
),
footer: GridTileBar(
backgroundColor: theme.colorScheme.primary.withOpacity(0.8),
title: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"MewTwo",
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium,
),
),
),
child: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Image.asset(
AppImages.mewtwo,
color: Colors.grey,
),
),
),
);
},
),
*/
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home/widgets/loading_pokemon.dart
|
// imports nativos
import 'package:flutter/material.dart';
// import das telas
import 'package:pokedex/app/core/widgets/pokedex_card.dart';
import 'package:pokedex/app/core/style/app_images.dart';
// import dos paoctes
import 'package:shimmer_animation/shimmer_animation.dart';
class LoadingPokemonWidget extends StatelessWidget {
const LoadingPokemonWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return PokedexCardWidget(
body: GridView.builder(
itemCount: 6,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemBuilder: (builder, index) {
return Card(
shadowColor: Colors.grey,
child: GridTile(
header: Padding(
padding: const EdgeInsets.fromLTRB(0, 10, 8, 0),
child: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"# 150",
textAlign: TextAlign.end,
style: theme.textTheme.bodySmall,
),
),
),
footer: GridTileBar(
backgroundColor: theme.colorScheme.primary.withOpacity(0.8),
title: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Text(
"MewTwo",
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium,
),
),
),
child: Shimmer(
duration: const Duration(seconds: 5),
color: Colors.grey[50]!,
colorOpacity: 0.3,
enabled: true,
direction: const ShimmerDirection.fromLTRB(),
child: Image.asset(
AppImages.mewtwo,
color: Colors.grey,
),
),
),
);
},
),
);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home/mobx/pokemon.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'pokemon.dart';
// **************************************************************************
// StoreGenerator
// **************************************************************************
// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic, no_leading_underscores_for_local_identifiers
mixin _$PokemonMobx on _PokemonMobx, Store {
late final _$pokemonAtom =
Atom(name: '_PokemonMobx.pokemon', context: context);
@override
PokemonEntity? get pokemon {
_$pokemonAtom.reportRead();
return super.pokemon;
}
@override
set pokemon(PokemonEntity? value) {
_$pokemonAtom.reportWrite(value, super.pokemon, () {
super.pokemon = value;
});
}
late final _$getPokemonAsyncAction =
AsyncAction('_PokemonMobx.getPokemon', context: context);
@override
Future<void> getPokemon(int id) {
return _$getPokemonAsyncAction.run(() => super.getPokemon(id));
}
late final _$_PokemonMobxActionController =
ActionController(name: '_PokemonMobx', context: context);
@override
void setPokemon(PokemonEntity pokemonEntity) {
final _$actionInfo = _$_PokemonMobxActionController.startAction(
name: '_PokemonMobx.setPokemon');
try {
return super.setPokemon(pokemonEntity);
} finally {
_$_PokemonMobxActionController.endAction(_$actionInfo);
}
}
@override
String toString() {
return '''
pokemon: ${pokemon}
''';
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home/mobx/pokemon.dart
|
// imports globais
import 'package:pokedex/session.dart';
// import dos domain
import 'package:pokedex/domain/source/local/injection/injection.dart';
import 'package:pokedex/domain/usecases/pokemon_usecase.dart';
import 'package:pokedex/domain/entities/pokemon.dart';
// import dos pacotes
import 'package:mobx/mobx.dart';
part 'pokemon.g.dart';
class PokemonMobx extends _PokemonMobx with _$PokemonMobx {}
abstract class _PokemonMobx with Store {
final PokemonUseCase useCase = PokemonUseCase(getIt());
@observable
PokemonEntity? pokemon;
@action
Future<void> getPokemon( int id ) async {
if ( id == 1011 ) {
id = 1;
}
if ( id == 0 ) {
id = 1010;
}
final failureOrPokemon = await useCase.getPokemon(id);
failureOrPokemon.fold(
(failure) => Session.crash.onFailure(failure.message),
(success) => setPokemon(success),
);
}
@action
void setPokemon( PokemonEntity pokemonEntity ) => pokemon = pokemonEntity;
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home/cubit/home_cubit.dart
|
// imports globais
import 'package:flutter/material.dart';
// imports globais
import 'package:pokedex/session.dart';
// imports dos domain
import 'package:pokedex/domain/source/local/injection/injection.dart';
import 'package:pokedex/domain/usecases/pokemon_usecase.dart';
import 'package:pokedex/domain/entities/pokemon.dart';
import 'package:pokedex/domain/failures/failure.dart';
// import dos pacotes
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
part 'home_state.dart';
const generalFailureMessage = "Ups, something gone wrong. Please try again!";
const serverFailureMessage = "Ups, API error. Please try again!";
const cacheFailureMessage = "Ups, cache failed. Please try again";
class HomeCubit extends Cubit<HomeCubitState> {
final PokemonUseCase pokemonUseCase;
HomeCubit( this.pokemonUseCase ) : super(const HomeInitial());
TextEditingController controllerSearch = TextEditingController();
final ScrollController scrollController = ScrollController();
final List<PokemonEntity> listPokemon = [];
bool isLoaded = false;
Future<void> getPokemon() async {
if ( nextPage == null && previousPage == null ) {
emit(const HomeStateLoading());
}
// execute bussiness logic
final failureOrList = await pokemonUseCase.getListPokemon();
failureOrList.fold(
(failure) => emit(HomeStateError(message: _mapFailureToMessage(failure))),
(success) {
isLoaded = true;
emit(HomeStateLoaded(success));
listPokemon.addAll(success);
},
);
}
Future<void> loadMore() async {
if ( nextPage != null ) {
if ( scrollController.position.maxScrollExtent == scrollController.position.pixels ) {
await getPokemon();
}
}
}
Future<void> refresh() async {
emit(const HomeStateLoading());
Session.appEvents.sharedEvent("home_refresh");
clearPagination();
listPokemon.clear();
await getPokemon();
}
void goToDetail( PokemonEntity pokemon ) {
Session.appEvents.sharedEvent("home_open_detail");
Navigator.pushNamed(
Session.globalContext.currentContext!,
"/detail",
arguments: {
"pokemon": pokemon,
}
);
}
String _mapFailureToMessage( Failure failure ) {
Session.crash.onFailure(failure.message);
switch (failure.runtimeType) {
case ServerFailure:
return serverFailureMessage;
case CacheFailure:
return cacheFailureMessage;
default:
return generalFailureMessage;
}
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home
|
mirrored_repositories/pokedex_flutter/lib/app/pages/home/cubit/home_state.dart
|
part of 'home_cubit.dart';
abstract class HomeCubitState extends Equatable {
const HomeCubitState();
@override
List<Object?> get props => [];
}
class HomeInitial extends HomeCubitState {
const HomeInitial();
}
class HomeStateLoading extends HomeCubitState {
const HomeStateLoading();
}
class HomeStateLoaded extends HomeCubitState {
const HomeStateLoaded( this.listPokemon );
final List<PokemonEntity> listPokemon;
@override
List<Object?> get props => [listPokemon];
}
class HomeStateError extends HomeCubitState {
const HomeStateError({ required this.message });
final String message;
@override
List<Object?> get props => [message];
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/core
|
mirrored_repositories/pokedex_flutter/lib/app/core/widgets/loading_connection.dart
|
// pacotes nativos do flutter
import 'package:flutter/material.dart';
import 'dart:async';
// import dos pacotes
import 'package:flutter_i18n/flutter_i18n.dart';
class LoadingConnection extends StatefulWidget {
const LoadingConnection({ Key? key }) : super(key: key);
@override
State<LoadingConnection> createState() => _LoadingConnectionState();
}
class _LoadingConnectionState extends State<LoadingConnection> {
bool _status = true;
double _opacity = 1;
Timer? _timer;
_changeStatus() {
_timer = Timer.periodic(const Duration(seconds: 3), (Timer t) {
if ( _opacity == 0 ) {
setState(() {
_status = !_status;
_opacity = 1;
});
} else {
setState(() {
_opacity = 0;
});
}
});
}
@override
void initState() {
super.initState();
_changeStatus();
}
@override
void dispose() {
super.dispose();
_timer!.cancel();
}
@override
Widget build(BuildContext context) {
final themeData = Theme.of(context);
return Scaffold(
body: AnimatedContainer(
padding: const EdgeInsets.only( top: 20, bottom: 100 ),
color: themeData.scaffoldBackgroundColor,
alignment: Alignment.center,
duration: const Duration(seconds: 4),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedOpacity(
duration: const Duration(seconds: 2),
opacity: _opacity,
child: SizedBox(
height: 50,
child: Icon(
( _status )
? Icons.wifi
: Icons.wifi_off,
size: 80,
color: themeData.colorScheme.error,
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(22, 60, 22, 10),
child: Text(
FlutterI18n.translate(context, "pages.connection.title"),
textAlign: TextAlign.center,
style: themeData.textTheme.displayMedium,
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/core
|
mirrored_repositories/pokedex_flutter/lib/app/core/widgets/pokedex_card.dart
|
// imports nativos
import 'package:flutter/material.dart';
class PokedexCardWidget extends StatelessWidget {
final Widget body;
const PokedexCardWidget({ Key? key, required this.body }) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(3.0),
child: Card(
elevation: 0,
child: Padding(
padding: const EdgeInsets.symmetric( vertical: 10, horizontal: 8 ),
child: body,
),
),
);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/core
|
mirrored_repositories/pokedex_flutter/lib/app/core/widgets/custom_snack_bar.dart
|
// imports nativos do flutter
import 'package:flutter/material.dart';
// imports globais
import 'package:pokedex/session.dart';
// import dos pacotes
import 'package:flutter_i18n/flutter_i18n.dart';
class CustomSnackBar {
CustomSnackBar({ required String messageKey, Color? color, Map<String, String>? params }) {
final context = Session.globalContext.currentContext!;
final snackBar = SnackBar(
content: Text(
FlutterI18n.translate(context, messageKey, translationParams: params),
style: const TextStyle(
color: Colors.white,
),
),
backgroundColor: color ?? Theme.of(context).colorScheme.error,
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/core
|
mirrored_repositories/pokedex_flutter/lib/app/core/routes/routes.dart
|
// imports nativos do flutter
import 'package:flutter/material.dart';
import 'package:pokedex/app/pages/home/detail.dart';
import 'package:pokedex/app/pages/home/home.dart';
// import das telas
import 'package:pokedex/app/pages/splash.dart';
// import dos pacotes
import 'package:flutter_i18n/flutter_i18n.dart';
class Routes {
static Route<dynamic>? generateRoutes(RouteSettings settings) {
final args = settings.arguments;
switch( settings.name ) {
case "/splash" :
return MaterialPageRoute(
builder: (_) => const SplashPage(),
);
case "/" :
return MaterialPageRoute(
builder: (_) => const HomePage(),
);
case "/detail" :
final params = args as Map;
return MaterialPageRoute(
builder: (_) => DetailPage(
pokemon: params["pokemon"],
),
);
default:
_errorRoute();
}
return null;
}
static Route<dynamic> _errorRoute() {
return MaterialPageRoute(
builder: (_) {
return Scaffold(
backgroundColor: Theme.of(_).colorScheme.background,
appBar: AppBar(
title: Text(
FlutterI18n.translate(_, "routes.app_bar"),
style: TextStyle(
color: Theme.of(_).secondaryHeaderColor,
),
),
),
body: Center(
child: Text(
FlutterI18n.translate(_, "routes.app_bar"),
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/core
|
mirrored_repositories/pokedex_flutter/lib/app/core/services/languages.dart
|
// import dos pacotes nativos do flutter
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:io' show Platform;
// import dos pacotes
import 'package:flutter_i18n/flutter_i18n.dart';
const Iterable<Locale> supportedLocale = [
Locale("en", "US"),
Locale("pt", "BR"),
Locale("pt", "PT"),
];
final Iterable<LocalizationsDelegate<dynamic>> localizationsDelegate = [
const MaterialLocalisationsDelegate(),
const CupertinoLocalisationsDelegate(),
FlutterI18nDelegate(
translationLoader: FileTranslationLoader(
useCountryCode: false,
basePath: "assets/languages",
fallbackFile: ( Platform.localeName == "pt_BR" )
? "pt_BR"
: "en_US",
),
),
];
class MaterialLocalisationsDelegate extends LocalizationsDelegate<MaterialLocalizations> {
const MaterialLocalisationsDelegate();
@override
bool isSupported(Locale locale) {
return true;
}
@override
Future<MaterialLocalizations> load(Locale locale) {
return DefaultMaterialLocalizations.load(locale);
}
@override
bool shouldReload(MaterialLocalisationsDelegate old) {
return false;
}
}
class CupertinoLocalisationsDelegate extends LocalizationsDelegate<CupertinoLocalizations> {
const CupertinoLocalisationsDelegate();
@override
bool isSupported(Locale locale) {
return true;
}
@override
Future<CupertinoLocalizations> load(Locale locale) {
return DefaultCupertinoLocalizations.load(locale);
}
@override
bool shouldReload(CupertinoLocalisationsDelegate old) {
return false;
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/core
|
mirrored_repositories/pokedex_flutter/lib/app/core/services/shared.dart
|
// import dos domains
import 'package:pokedex/domain/source/local/mobx/connection/connection.dart';
// import dos pacotes
import 'package:connectivity_plus/connectivity_plus.dart';
class SharedServices {
bool validateConnection( ConnectionMobx connectionMobx ) {
if ( connectionMobx.connectionStatus == ConnectivityResult.wifi || connectionMobx.connectionStatus == ConnectivityResult.mobile ) {
return true;
}
return false;
}
String convertValue( int oldValue ) {
String newValue = "";
if ( oldValue.toString().length == 1 ) {
newValue = "0.$oldValue";
} else if ( oldValue.toString().length == 2 ) {
newValue = "${oldValue.toString().substring(0, 1)}.${oldValue.toString().substring(1)}";
} else if ( oldValue.toString().length == 3 ) {
newValue = "${oldValue.toString().substring(0, 2)}.${oldValue.toString().substring(2)}";
} else if ( oldValue.toString().length == 4 ) {
newValue = "${oldValue.toString().substring(0, 3)}.${oldValue.toString().substring(3)}";
} else {
newValue = "${oldValue.toString().substring(0, 4)}.${oldValue.toString().substring(4)}";
}
return newValue;
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/core
|
mirrored_repositories/pokedex_flutter/lib/app/core/style/themes.dart
|
// imports nativos
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// import das telas
import 'package:pokedex/app/core/style/app_colors.dart';
class Themes {
Themes._();
// light colors
static const Color _backgroundColorLight = AppColors.white;
static const Color _primaryColorLight = AppColors.whiteSmoke;
static const Color _secondaryColorLight = AppColors.crimson;
static const Color _textPrimaryLight = AppColors.nero;
static const Color _textSecondaryLight = AppColors.dimGray;
// .****************
// Theme - Light
// .****************
static const TextStyle _headlineLargeTextLight = TextStyle(
color: _backgroundColorLight,
fontWeight: FontWeight.w700,
fontFamily: "Poppins",
fontSize: 24,
);
static const TextStyle _displayMediumTextLight = TextStyle(
fontWeight: FontWeight.w700,
fontFamily: "Poppins",
fontSize: 17,
);
static const TextStyle _displaySmallTextLight = TextStyle(
fontWeight: FontWeight.w700,
fontFamily: "Poppins",
fontSize: 12,
);
static const TextStyle _defaultTextLight = TextStyle(
fontWeight: FontWeight.w400,
color: _textPrimaryLight,
fontFamily: "Poppins",
fontSize: 16,
);
static const TextStyle _bodySmallTextLight = TextStyle(
fontWeight: FontWeight.w400,
color: _textSecondaryLight,
fontFamily: "Poppins",
fontSize: 14,
);
static const TextTheme _textThemeLight = TextTheme(
headlineLarge: _headlineLargeTextLight,
displayMedium: _displayMediumTextLight,
displaySmall: _displaySmallTextLight,
bodyMedium: _defaultTextLight,
bodySmall: _bodySmallTextLight,
);
static final ThemeData lightTheme = ThemeData(
useMaterial3: true,
scaffoldBackgroundColor: _backgroundColorLight,
appBarTheme: const AppBarTheme(
backgroundColor: _secondaryColorLight,
titleTextStyle: TextStyle(
color: _backgroundColorLight,
fontWeight: FontWeight.w700,
fontSize: 24,
),
systemOverlayStyle: SystemUiOverlayStyle(
statusBarBrightness: Brightness.light,
statusBarColor: _secondaryColorLight,
),
iconTheme: IconThemeData(
color: _backgroundColorLight,
),
),
textTheme: _textThemeLight,
colorScheme: const ColorScheme.light(
background: _backgroundColorLight,
primary: _primaryColorLight,
secondary: _secondaryColorLight,
tertiary: _textPrimaryLight,
onTertiary: _textSecondaryLight,
),
cardTheme: CardTheme(
color: _backgroundColorLight,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular( 8 ),
),
elevation: 5,
),
iconTheme: const IconThemeData(
color: _textPrimaryLight,
size: 18,
),
inputDecorationTheme: InputDecorationTheme(
contentPadding: const EdgeInsets.all(8),
labelStyle: _defaultTextLight,
filled: true,
fillColor: Colors.transparent,
enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(
color: _secondaryColorLight,
),
),
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: _secondaryColorLight,
),
borderRadius: BorderRadius.circular(16),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
),
),
floatingActionButtonTheme: FloatingActionButtonThemeData(
backgroundColor: _backgroundColorLight,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular( 30 ),
),
),
);
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/core
|
mirrored_repositories/pokedex_flutter/lib/app/core/style/app_colors.dart
|
// imports nativos
import 'package:flutter/material.dart';
class AppColors {
// amarelo
static const Color neutralGreen = Color(0xFFAAA67F);
static const Color sunGlow = Color(0xFFF9CF30);
static const Color sahara = Color(0xFFB69E31);
// azul
static const Color cornflowerBlue = Color(0xFF6493EB);
static const Color morningGlory = Color(0xFF98D8D8);
static const Color mayaBlue = Color(0xFF7AC7FF);
// branco
static const Color whiteSmoke = Color(0xFFEFEFEF);
static const Color gainsBoro = Color(0xFFE0E0E0);
static const Color white = Colors.white;
// cinza
static const Color lavenderGrey = Color(0xFFB7B9D0);
static const Color licorice = Color(0xFF303943);
static const Color dimGray = Color(0xFF666666);
static const Color nero = Color(0xFF1D1D1D);
// laranja
static const Color burntOrange = Color(0xFFF57D31);
// marrom
static const Color ironstone = Color(0xD0795548);
// rosa
static const Color bittersweet = Color(0xFFFB6C6C);
static const Color coralTree = Color(0xFFB1736C);
static const Color brinkPink = Color(0xFFF85888);
static const Color illusion = Color(0xFFEE99AC);
// roxo
static const Color bilobaFlower = Color(0xFFA890F0);
static const Color violetBlue = Color(0xD0A43E9E);
static const Color studio = Color(0xFF70559B);
// verde
static const Color mantis = Color(0xFF78C850);
static const Color bahia = Color(0xFFA7B723);
// vermelho
static const Color crimson = Color(0xFFDC0A2D);
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/app/core
|
mirrored_repositories/pokedex_flutter/lib/app/core/style/app_images.dart
|
class AppImages {
static String get pokeBall => "assets/img/poke_ball.png";
static String get darkrai => "assets/img/darkrai.png";
static String get lapras => "assets/img/lapras.png";
static String get mewtwo => "assets/img/mewtwo.png";
static String get logo => "assets/img/logo.png";
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/data
|
mirrored_repositories/pokedex_flutter/lib/data/models/pokemon_stat_model.dart
|
// import dos domain
import 'package:pokedex/domain/entities/pokemon_stat.dart';
// import dos pacotes
import 'package:equatable/equatable.dart';
class PokemonStatModel extends PokemonStatEntity with EquatableMixin {
PokemonStatModel( String attribute, int value ) : super(attribute, value);
factory PokemonStatModel.fromJson( Map<String, dynamic> json ) {
return PokemonStatModel(
json["stat"]["name"],
json["base_stat"],
);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/data
|
mirrored_repositories/pokedex_flutter/lib/data/models/pokemon_type_model.dart
|
// import dos domain
import 'package:pokedex/domain/entities/pokemon_type.dart';
// import dos pacotes
import 'package:equatable/equatable.dart';
class PokemonTypeModel extends PokemonTypeEntity with EquatableMixin {
PokemonTypeModel( int slot, String type ) : super(slot, type);
factory PokemonTypeModel.fromJson( dynamic json ) {
return PokemonTypeModel(
json["slot"],
json["type"]["name"],
);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/data
|
mirrored_repositories/pokedex_flutter/lib/data/models/pokemon_model.dart
|
// import dos domain
import 'package:pokedex/data/models/pokemon_abilities_model.dart';
import 'package:pokedex/domain/entities/pokemon.dart';
// import dos data
import 'package:pokedex/data/models/pokemon_stat_model.dart';
import 'package:pokedex/data/models/pokemon_type_model.dart';
// import dos pacotes
import 'package:equatable/equatable.dart';
class PokemonModel extends PokemonEntity with EquatableMixin {
PokemonModel( int id, String name, String image, List<PokemonTypeModel>? types, int? height, int? weight, List<PokemonStatModel>? stats, List<PokemonAbilitiesModel>? abilities ) : super(id, name, image, types, height, weight, stats, abilities);
factory PokemonModel.fromJson( Map<String, dynamic> json, { int? pokemonId } ) {
int idParse = pokemonId ?? int.parse(json["url"].toString().split("/pokemon/")[1].replaceAll("/", ""));
List<PokemonTypeModel> listTypes = [];
if ( json["types"] != null ) {
for ( final item in json["types"] ) {
listTypes.add(
PokemonTypeModel.fromJson(item),
);
}
}
List<PokemonStatModel> listStats = [];
if ( json["stats"] != null ) {
for ( final item in json["stats"] ) {
listStats.add(
PokemonStatModel.fromJson(item),
);
}
}
List<PokemonAbilitiesModel> listAbilities = [];
if ( json["abilities"] != null ) {
for ( final item in json["abilities"] ) {
listAbilities.add(
PokemonAbilitiesModel.fromJson(item),
);
}
}
return PokemonModel(
idParse,
json["name"],
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/$idParse.png",
listTypes,
json["height"],
json["weight"],
listStats,
listAbilities,
);
}
@override
String toString() => name;
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/data
|
mirrored_repositories/pokedex_flutter/lib/data/models/pokemon_abilities_model.dart
|
// import dos domain
import 'package:pokedex/domain/entities/pokemon_abilities.dart';
// import dos pacotes
import 'package:equatable/equatable.dart';
class PokemonAbilitiesModel extends PokemonAbilitiesEntity with EquatableMixin {
PokemonAbilitiesModel( String ability ) : super(ability);
factory PokemonAbilitiesModel.fromJson( Map<String, dynamic> json ) {
return PokemonAbilitiesModel(
json["ability"]["name"],
);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/data
|
mirrored_repositories/pokedex_flutter/lib/data/datasource/pokemon_remote_datasource.dart
|
// imports nativos
import 'dart:convert';
// imports globais
import 'package:pokedex/session.dart';
// import dos domain
import 'package:pokedex/domain/source/local/injection/injection.dart';
// import dos data
import 'package:pokedex/data/exceptions/exceptions.dart';
import 'package:pokedex/data/models/pokemon_model.dart';
// import dos pacotess
import 'package:http/http.dart' as http;
abstract class PokemonRemoteDatasource {
Future<List<PokemonModel>> getListPokemon();
Future<PokemonModel> getPokemon( int id );
}
class PokemonRemoteDatasourceImpl implements PokemonRemoteDatasource {
final http.Client client;
PokemonRemoteDatasourceImpl( this.client );
@override
Future<List<PokemonModel>> getListPokemon() async {
Map<String, String> header = {
"content-Type": "application/json",
};
Uri url = Uri.parse(Session.credentials.url);
if ( nextPage != null ) {
url = Uri.parse(nextPage!);
}
final response = await client.get(
url,
headers: header,
);
if ( response.statusCode != 200 ) {
throw ServerExceptions();
}
final responseBody = jsonDecode(response.body);
setPagination(responseBody);
final List<PokemonModel> list = [];
for ( final item in responseBody["results"] ) {
list.add(
PokemonModel.fromJson(item),
);
}
return list;
}
@override
Future<PokemonModel> getPokemon( int id ) async {
Map<String, String> header = {
"content-Type": "application/json",
};
final url = Uri.parse("${Session.credentials.url}/$id");
final response = await client.get(
url,
headers: header,
);
if ( response.statusCode != 200 ) {
throw ServerExceptions();
}
final responseBody = jsonDecode(response.body);
return PokemonModel.fromJson(responseBody, pokemonId: id);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/data
|
mirrored_repositories/pokedex_flutter/lib/data/repositories/pokemon_repo_impl.dart
|
// imports globais
import 'package:pokedex/session.dart';
// import dos domain
import 'package:pokedex/domain/repositories/pokemon_repo.dart';
import 'package:pokedex/domain/failures/failure.dart';
// import dos data
import 'package:pokedex/data/datasource/pokemon_remote_datasource.dart';
import 'package:pokedex/data/exceptions/exceptions.dart';
import 'package:pokedex/data/models/pokemon_model.dart';
// import dos pacotes
import 'package:dartz/dartz.dart';
class PokemonRepoImpl implements PokemonRepo {
final PokemonRemoteDatasource pokemonRemoteDatasource;
PokemonRepoImpl(this.pokemonRemoteDatasource);
@override
Future<Either<Failure, List<PokemonModel>>> getListPokemon() async {
try {
final result = await pokemonRemoteDatasource.getListPokemon();
return right(result);
} on ServerExceptions {
return left(ServerFailure());
} catch (e) {
return left(GeneralFailure());
}
}
@override
Future<Either<Failure, PokemonModel>> getPokemon( int id ) async {
try {
final result = await pokemonRemoteDatasource.getPokemon( id );
return right(result);
} on ServerExceptions {
return left(ServerFailure());
} catch (e) {
Session.crash.onFailure(e.toString());
return left(GeneralFailure());
}
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/data
|
mirrored_repositories/pokedex_flutter/lib/data/exceptions/exceptions.dart
|
class ServerExceptions implements Exception {}
class CacheExceptions implements Exception {}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain
|
mirrored_repositories/pokedex_flutter/lib/domain/failures/failure.dart
|
// import dos pacotes
import 'package:equatable/equatable.dart';
abstract class Failure {
final String message = "";
}
class ServerFailure extends Failure with EquatableMixin {
@override
List<Object?> get props => [];
}
class CacheFailure extends Failure with EquatableMixin {
@override
List<Object?> get props => [];
}
class GeneralFailure extends Failure with EquatableMixin {
@override
List<Object?> get props => [];
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain/source
|
mirrored_repositories/pokedex_flutter/lib/domain/source/remote/credentials.dart
|
class Credentials {
String url = "https://pokeapi.co/api/v2/pokemon";
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain/source
|
mirrored_repositories/pokedex_flutter/lib/domain/source/remote/app_events.dart
|
// import dos pacotes
import 'package:firebase_analytics/firebase_analytics.dart';
class AppEvents {
final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;
Future<void> sendScreen( String screenName ) async {
await _analytics.setCurrentScreen(
screenName: screenName,
screenClassOverride: screenName,
);
}
Future<void> sharedEvent( String eventName ) async {
await _analytics.logEvent(name: eventName);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain/source
|
mirrored_repositories/pokedex_flutter/lib/domain/source/remote/crash.dart
|
// imports nativos
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// import dos pacotes
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
class Crash {
final FirebaseCrashlytics _crashlytics = FirebaseCrashlytics.instance;
void onFailure( String errorMessage ) {
_crashlytics.log(errorMessage);
}
void log( PlatformException exception ) {
_crashlytics.log("${exception.code} - ${exception.details}");
FlutterError.reportError(
FlutterErrorDetails(
exception: exception,
library: "${exception.message}",
context: ErrorSummary("${exception.details}"),
),
);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain/source/local/mobx
|
mirrored_repositories/pokedex_flutter/lib/domain/source/local/mobx/connection/connection.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'connection.dart';
// **************************************************************************
// StoreGenerator
// **************************************************************************
// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic, no_leading_underscores_for_local_identifiers
mixin _$ConnectionMobx on _ConnectionMobx, Store {
late final _$connectionStatusAtom =
Atom(name: '_ConnectionMobx.connectionStatus', context: context);
@override
ConnectivityResult get connectionStatus {
_$connectionStatusAtom.reportRead();
return super.connectionStatus;
}
@override
set connectionStatus(ConnectivityResult value) {
_$connectionStatusAtom.reportWrite(value, super.connectionStatus, () {
super.connectionStatus = value;
});
}
late final _$connectivityAtom =
Atom(name: '_ConnectionMobx.connectivity', context: context);
@override
Connectivity get connectivity {
_$connectivityAtom.reportRead();
return super.connectivity;
}
@override
set connectivity(Connectivity value) {
_$connectivityAtom.reportWrite(value, super.connectivity, () {
super.connectivity = value;
});
}
late final _$verifyConnectionAsyncAction =
AsyncAction('_ConnectionMobx.verifyConnection', context: context);
@override
Future<void> verifyConnection() {
return _$verifyConnectionAsyncAction.run(() => super.verifyConnection());
}
late final _$updateConnectionStatusAsyncAction =
AsyncAction('_ConnectionMobx.updateConnectionStatus', context: context);
@override
Future<void> updateConnectionStatus(ConnectivityResult result) {
return _$updateConnectionStatusAsyncAction
.run(() => super.updateConnectionStatus(result));
}
@override
String toString() {
return '''
connectionStatus: ${connectionStatus},
connectivity: ${connectivity}
''';
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain/source/local/mobx
|
mirrored_repositories/pokedex_flutter/lib/domain/source/local/mobx/connection/connection.dart
|
// pacotes nativos do flutter
import 'package:flutter/services.dart';
import 'dart:async';
// imports globais
import 'package:pokedex/session.dart';
// import dos pacotes
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:mobx/mobx.dart';
part 'connection.g.dart';
class ConnectionMobx extends _ConnectionMobx with _$ConnectionMobx {}
abstract class _ConnectionMobx with Store {
@observable
ConnectivityResult connectionStatus = ConnectivityResult.none;
@observable
Connectivity connectivity = Connectivity();
@action
Future<void> verifyConnection() async {
ConnectivityResult result;
try {
result = await connectivity.checkConnectivity();
} on PlatformException catch (e) {
Session.crash.log(e);
return;
}
return updateConnectionStatus(result);
}
@action
Future<void> updateConnectionStatus( ConnectivityResult result ) async => connectionStatus = result;
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain/source/local
|
mirrored_repositories/pokedex_flutter/lib/domain/source/local/injection/injection.config.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// InjectableConfigGenerator
// **************************************************************************
// ignore_for_file: unnecessary_lambdas
// ignore_for_file: lines_longer_than_80_chars
// coverage:ignore-file
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:get_it/get_it.dart' as _i1;
import 'package:injectable/injectable.dart' as _i2;
extension GetItInjectableX on _i1.GetIt {
// initializes the registration of main-scope dependencies inside of GetIt
_i1.GetIt init({
String? environment,
_i2.EnvironmentFilter? environmentFilter,
}) {
final gh = _i2.GetItHelper(
this,
environment,
environmentFilter,
);
return this;
}
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain/source/local
|
mirrored_repositories/pokedex_flutter/lib/domain/source/local/injection/injection.dart
|
// import das telas
import 'package:pokedex/app/pages/home/cubit/home_cubit.dart';
// import dos domain
import 'package:pokedex/domain/repositories/pokemon_repo.dart';
import 'package:pokedex/domain/usecases/pokemon_usecase.dart';
// import dos data
import 'package:pokedex/data/datasource/pokemon_remote_datasource.dart';
import 'package:pokedex/data/repositories/pokemon_repo_impl.dart';
// import dos pacotes
import 'package:injectable/injectable.dart';
import 'package:http/http.dart' as http;
import 'package:get_it/get_it.dart';
final getIt = GetIt.I;
int totalItems = 0;
String? nextPage;
String? previousPage;
@InjectableInit()
void configureDependencies() {
// pages
getIt.registerFactory(() => HomeCubit(getIt()));
// domain
getIt.registerFactory(() => PokemonUseCase(getIt()));
// data
getIt.registerFactory<PokemonRemoteDatasource>(() => PokemonRemoteDatasourceImpl(getIt()));
getIt.registerFactory<PokemonRepo>(() => PokemonRepoImpl(getIt()));
// extern
getIt.registerFactory(() => http.Client());
}
void setPagination( Map<String, dynamic> json ) {
totalItems = json["count"];
nextPage = json["next"];
previousPage = json["previous"];
}
void clearPagination() {
totalItems = 0;
nextPage = null;
previousPage = null;
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain
|
mirrored_repositories/pokedex_flutter/lib/domain/entities/pokemon_stat.dart
|
// import dos pacotes
import 'package:equatable/equatable.dart';
class PokemonStatEntity extends Equatable{
final String attribute;
final int value;
const PokemonStatEntity( this.attribute, this.value );
String get attributeAbbreviation {
Map<String, dynamic> values = {
"hp": "HP",
"attack": "ATK",
"defense": "DEF",
"special-attack": "SATK",
"special-defense": "SDEF",
"speed": "SPD",
};
return values[attribute] ?? attribute;
}
@override
List<Object?> get props => [attribute, value];
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain
|
mirrored_repositories/pokedex_flutter/lib/domain/entities/pokemon_abilities.dart
|
// import dos pacotes
import 'package:equatable/equatable.dart';
class PokemonAbilitiesEntity extends Equatable{
final String ability;
const PokemonAbilitiesEntity( this.ability );
@override
List<Object?> get props => [ability];
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain
|
mirrored_repositories/pokedex_flutter/lib/domain/entities/pokemon_type.dart
|
// imports nativos
import 'dart:ui';
// import das telas
import 'package:pokedex/app/core/style/app_colors.dart';
// import dos pacotes
import 'package:equatable/equatable.dart';
class PokemonTypeEntity extends Equatable {
final int slot;
final String type;
const PokemonTypeEntity( this.slot, this.type);
Color get color {
Map<String, dynamic> colors = {
"grass": AppColors.mantis,
"bug": AppColors.bahia,
"fire": AppColors.burntOrange,
"water": AppColors.cornflowerBlue,
"fighting": AppColors.bittersweet,
"normal": AppColors.neutralGreen,
"electric": AppColors.sunGlow,
"psychic": AppColors.brinkPink,
"poison": AppColors.violetBlue,
"ghost": AppColors.studio,
"ground": AppColors.ironstone,
"rock": AppColors.sahara,
"dark": AppColors.licorice,
"dragon": AppColors.coralTree,
"fairy": AppColors.illusion,
"flying": AppColors.bilobaFlower,
"ice": AppColors.morningGlory,
"steel": AppColors.lavenderGrey,
"monster": AppColors.mayaBlue,
"unknown": AppColors.mayaBlue,
};
return colors[type] ?? AppColors.mayaBlue;
}
@override
List<Object?> get props => [slot, type];
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain
|
mirrored_repositories/pokedex_flutter/lib/domain/entities/pokemon.dart
|
// import dos domain
import 'dart:ui';
import 'package:pokedex/app/core/style/app_colors.dart';
import 'package:pokedex/domain/entities/pokemon_abilities.dart';
import 'package:pokedex/domain/entities/pokemon_stat.dart';
import 'package:pokedex/domain/entities/pokemon_type.dart';
// import dos pacotes
import 'package:equatable/equatable.dart';
class PokemonEntity extends Equatable {
final int id;
final String name, image;
final List<PokemonTypeEntity>? types;
final int? height, weight;
final List<PokemonStatEntity>? stats;
final List<PokemonAbilitiesEntity>? abilities;
const PokemonEntity( this.id, this.name, this.image, this.types, this.height, this.weight, this.stats, this.abilities );
Color get primaryColor => types?[0].color ?? AppColors.crimson;
@override
List<Object?> get props => [id, name, image, types, height, weight, stats, abilities];
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain
|
mirrored_repositories/pokedex_flutter/lib/domain/repositories/pokemon_repo.dart
|
// import dos modelos
import 'package:pokedex/domain/entities/pokemon.dart';
import 'package:pokedex/domain/failures/failure.dart';
// import dos pacotes
import 'package:dartz/dartz.dart';
abstract class PokemonRepo {
Future<Either<Failure, List<PokemonEntity>>> getListPokemon();
Future<Either<Failure, PokemonEntity>> getPokemon( int id );
}
| 0
|
mirrored_repositories/pokedex_flutter/lib/domain
|
mirrored_repositories/pokedex_flutter/lib/domain/usecases/pokemon_usecase.dart
|
// import dos domain
import 'package:pokedex/domain/repositories/pokemon_repo.dart';
import 'package:pokedex/domain/entities/pokemon.dart';
import 'package:pokedex/domain/failures/failure.dart';
// import dos pacotes
import 'package:dartz/dartz.dart';
class PokemonUseCase {
final PokemonRepo pokemonRepo;
PokemonUseCase( this.pokemonRepo );
Future<Either<Failure, List<PokemonEntity>>> getListPokemon() async {
return pokemonRepo.getListPokemon();
}
Future<Either<Failure, PokemonEntity>> getPokemon( int id ) async {
return pokemonRepo.getPokemon(id);
}
}
| 0
|
mirrored_repositories/pokedex_flutter/test/data
|
mirrored_repositories/pokedex_flutter/test/data/datasource/pokemon_remote_datasource_test.mocks.dart
|
// Mocks generated by Mockito 5.4.0 from annotations
// in pokedex/test/data/datasource/pokemon_remote_datasource_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'dart:convert' as _i4;
import 'dart:typed_data' as _i5;
import 'package:http/http.dart' as _i2;
import 'package:mockito/mockito.dart' as _i1;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response {
_FakeResponse_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeStreamedResponse_1 extends _i1.SmartFake
implements _i2.StreamedResponse {
_FakeStreamedResponse_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [Client].
///
/// See the documentation for Mockito's code generation for more information.
class MockClient extends _i1.Mock implements _i2.Client {
@override
_i3.Future<_i2.Response> head(
Uri? url, {
Map<String, String>? headers,
}) =>
(super.noSuchMethod(
Invocation.method(
#head,
[url],
{#headers: headers},
),
returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#head,
[url],
{#headers: headers},
),
)),
returnValueForMissingStub:
_i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#head,
[url],
{#headers: headers},
),
)),
) as _i3.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> get(
Uri? url, {
Map<String, String>? headers,
}) =>
(super.noSuchMethod(
Invocation.method(
#get,
[url],
{#headers: headers},
),
returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#get,
[url],
{#headers: headers},
),
)),
returnValueForMissingStub:
_i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#get,
[url],
{#headers: headers},
),
)),
) as _i3.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> post(
Uri? url, {
Map<String, String>? headers,
Object? body,
_i4.Encoding? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
#post,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#post,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
)),
returnValueForMissingStub:
_i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#post,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
)),
) as _i3.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> put(
Uri? url, {
Map<String, String>? headers,
Object? body,
_i4.Encoding? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
#put,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#put,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
)),
returnValueForMissingStub:
_i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#put,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
)),
) as _i3.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> patch(
Uri? url, {
Map<String, String>? headers,
Object? body,
_i4.Encoding? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
#patch,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#patch,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
)),
returnValueForMissingStub:
_i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#patch,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
)),
) as _i3.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> delete(
Uri? url, {
Map<String, String>? headers,
Object? body,
_i4.Encoding? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
#delete,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#delete,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
)),
returnValueForMissingStub:
_i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#delete,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
)),
) as _i3.Future<_i2.Response>);
@override
_i3.Future<String> read(
Uri? url, {
Map<String, String>? headers,
}) =>
(super.noSuchMethod(
Invocation.method(
#read,
[url],
{#headers: headers},
),
returnValue: _i3.Future<String>.value(''),
returnValueForMissingStub: _i3.Future<String>.value(''),
) as _i3.Future<String>);
@override
_i3.Future<_i5.Uint8List> readBytes(
Uri? url, {
Map<String, String>? headers,
}) =>
(super.noSuchMethod(
Invocation.method(
#readBytes,
[url],
{#headers: headers},
),
returnValue: _i3.Future<_i5.Uint8List>.value(_i5.Uint8List(0)),
returnValueForMissingStub:
_i3.Future<_i5.Uint8List>.value(_i5.Uint8List(0)),
) as _i3.Future<_i5.Uint8List>);
@override
_i3.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) =>
(super.noSuchMethod(
Invocation.method(
#send,
[request],
),
returnValue:
_i3.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1(
this,
Invocation.method(
#send,
[request],
),
)),
returnValueForMissingStub:
_i3.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1(
this,
Invocation.method(
#send,
[request],
),
)),
) as _i3.Future<_i2.StreamedResponse>);
@override
void close() => super.noSuchMethod(
Invocation.method(
#close,
[],
),
returnValueForMissingStub: null,
);
}
| 0
|
mirrored_repositories/pokedex_flutter/test/data
|
mirrored_repositories/pokedex_flutter/test/data/datasource/pokemon_remote_datasource_test.dart
|
// imports globais
import 'package:pokedex/session.dart';
// import dos test
import 'pokemon_remote_datasource_test.mocks.dart';
// import dos data
import 'package:pokedex/data/datasource/pokemon_remote_datasource.dart';
import 'package:pokedex/data/exceptions/exceptions.dart';
import 'package:pokedex/data/models/pokemon_model.dart';
// import dos pacotes
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
import 'package:http/http.dart';
@GenerateNiceMocks([MockSpec<Client>()])
void main() {
group('PokemonRemoteDatasource get List', () {
final mockClient = MockClient();
final pokemonRemoteDataSourceTest = PokemonRemoteDatasourceImpl(mockClient);
// list
group('should throw get list', () {
test('A serverException when Client response was not 200 and has no valid data', () {
when(
mockClient.get(
Uri.parse(Session.credentials.url),
headers: {
"content-Type": "application/json",
},
),
).thenAnswer((realInvocation) => Future.value(
Response('', 400),
));
expect(pokemonRemoteDataSourceTest.getListPokemon(), throwsA(isA<ServerExceptions>()));
});
});
group("should return a List<PokemonModel>", () {
test("When client response was 200 and has valid data", () async {
const responseBody = '''{
"count": 1281,
"next": "https://pokeapi.co/api/v2/pokemon/?offset=20&limit=20",
"previous": null,
"results": [
{
"name": "bulbasaur",
"url": "https://pokeapi.co/api/v2/pokemon/1/"
},
{
"name": "ivysaur",
"url": "https://pokeapi.co/api/v2/pokemon/2/"
},
{
"name": "venusaur",
"url": "https://pokeapi.co/api/v2/pokemon/3/"
}
]
}''';
List<PokemonModel> listPokemon = [
PokemonModel(
1,
"bulbasaur",
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png",
const [],
null,
null,
const [],
const [],
),
PokemonModel(
2,
"ivysaur",
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/2.png",
const [],
null,
null,
const [],
const [],
),
PokemonModel(
3,
"venusaur",
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/3.png",
const [],
null,
null,
const [],
const [],
),
];
when(
mockClient.get(
Uri.parse(Session.credentials.url),
headers: {
"content-Type": "application/json",
},
),
).thenAnswer((realInvocation) => Future.value(
Response(responseBody, 200),
));
final result = await pokemonRemoteDataSourceTest.getListPokemon();
expect(result, listPokemon);
});
});
});
}
| 0
|
mirrored_repositories/pokedex_flutter/test/data
|
mirrored_repositories/pokedex_flutter/test/data/repositories/pokemon_repo_impl_test.dart
|
// imports nativos
import 'dart:io';
// import dos testes
import 'pokemon_repo_impl_test.mocks.dart';
// import dos domain
import 'package:pokedex/domain/failures/failure.dart';
// import dos data
import 'package:pokedex/data/datasource/pokemon_remote_datasource.dart';
import 'package:pokedex/data/repositories/pokemon_repo_impl.dart';
import 'package:pokedex/data/models/pokemon_abilities_model.dart';
import 'package:pokedex/data/models/pokemon_stat_model.dart';
import 'package:pokedex/data/models/pokemon_type_model.dart';
import 'package:pokedex/data/exceptions/exceptions.dart';
import 'package:pokedex/data/models/pokemon_model.dart';
// import dos pacotes
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:dartz/dartz.dart';
import 'package:test/test.dart';
@GenerateNiceMocks([MockSpec<PokemonRemoteDatasourceImpl>()])
void main() {
group('PokemonRepoImpl', () {
final mockPokemonRemoteDatasource = MockPokemonRemoteDatasourceImpl();
final pokemonRepoImplTest = PokemonRepoImpl(mockPokemonRemoteDatasource);
// list
group('should return List<PokemonModel>', () {
test('when pokemonRemoteDatasource return a List<PokemonModel>', () async {
List<PokemonModel> listPokemon = [
PokemonModel(
1,
"bulbasaur",
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png",
const [],
null,
null,
const [],
const [],
),
PokemonModel(
2,
"ivysaur",
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/2.png",
const [],
null,
null,
const [],
const [],
),
PokemonModel(
3,
"venusaur",
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/3.png",
const [],
null,
null,
const [],
const [],
),
];
when(
mockPokemonRemoteDatasource.getListPokemon(),
).thenAnswer(
(realInvocation) => Future.value(listPokemon),
);
final result = await pokemonRepoImplTest.getListPokemon();
expect(result.isLeft(), false);
expect(result.isRight(), true);
expect(result, Right<Failure, List<PokemonModel>>(listPokemon));
verify(mockPokemonRemoteDatasource.getListPokemon()).called(1);
verifyNoMoreInteractions(mockPokemonRemoteDatasource);
});
});
group('should return left with', () {
test('A serverFailure when a ServerException occurs', () async {
when(
mockPokemonRemoteDatasource.getListPokemon(),
).thenThrow(ServerExceptions());
final result = await pokemonRepoImplTest.getListPokemon();
expect(result.isLeft(), true);
expect(result.isRight(), false);
expect(result, Left<Failure, List<PokemonModel>>(ServerFailure()));
});
test('A GeneralFailure on all another exceptions', () async {
when(
mockPokemonRemoteDatasource.getListPokemon(),
).thenThrow(
const SocketException("Test"),
);
final result = await pokemonRepoImplTest.getListPokemon();
expect(result.isLeft(), true);
expect(result.isRight(), false);
expect(result, Left<Failure, List<PokemonModel>>(GeneralFailure()));
});
});
// detail
group('should return a PokemonModel', () {
test('when pokemonRemoteDatasource return a PokemonModel', () async {
PokemonModel pokemonModel = PokemonModel(
150,
"mewtwo",
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/150.png",
[
PokemonTypeModel(1, "psychic"),
],
20,
1220,
[
PokemonStatModel("hp", 106),
PokemonStatModel("attack", 110),
PokemonStatModel("defense", 90),
PokemonStatModel("special-attack", 154),
PokemonStatModel("special-defense", 90),
PokemonStatModel("speed", 130),
],
[
PokemonAbilitiesModel("pressure"),
PokemonAbilitiesModel("unnerve"),
],
);
when(
mockPokemonRemoteDatasource.getPokemon(150),
).thenAnswer(
(realInvocation) => Future.value(pokemonModel),
);
final result = await pokemonRepoImplTest.getPokemon(150);
expect(result.isLeft(), false);
expect(result.isRight(), true);
expect(result, Right<Failure, PokemonModel>(pokemonModel));
verify(mockPokemonRemoteDatasource.getPokemon(150)).called(1);
});
});
group('should return left with', () {
test('A serverFailure when a ServerException occurs', () async {
when(
mockPokemonRemoteDatasource.getPokemon(150),
).thenThrow(ServerExceptions());
final result = await pokemonRepoImplTest.getPokemon(150);
expect(result.isLeft(), true);
expect(result.isRight(), false);
expect(result, Left<Failure, PokemonModel>(ServerFailure()));
});
test('A GeneralFailure on all another exceptions', () async {
when(
mockPokemonRemoteDatasource.getPokemon(150),
).thenThrow(
const SocketException("Test"),
);
final result = await pokemonRepoImplTest.getPokemon(150);
expect(result.isLeft(), true);
expect(result.isRight(), false);
expect(result, Left<Failure, PokemonModel>(GeneralFailure()));
});
});
});
}
| 0
|
mirrored_repositories/pokedex_flutter/test/data
|
mirrored_repositories/pokedex_flutter/test/data/repositories/pokemon_repo_impl_test.mocks.dart
|
// Mocks generated by Mockito 5.4.0 from annotations
// in pokedex/test/data/repositories/pokemon_repo_impl_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i5;
import 'package:http/http.dart' as _i2;
import 'package:mockito/mockito.dart' as _i1;
import 'package:pokedex/data/datasource/pokemon_remote_datasource.dart' as _i4;
import 'package:pokedex/data/models/pokemon_model.dart' as _i3;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeClient_0 extends _i1.SmartFake implements _i2.Client {
_FakeClient_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakePokemonModel_1 extends _i1.SmartFake implements _i3.PokemonModel {
_FakePokemonModel_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [PokemonRemoteDatasourceImpl].
///
/// See the documentation for Mockito's code generation for more information.
class MockPokemonRemoteDatasourceImpl extends _i1.Mock
implements _i4.PokemonRemoteDatasourceImpl {
@override
_i2.Client get client => (super.noSuchMethod(
Invocation.getter(#client),
returnValue: _FakeClient_0(
this,
Invocation.getter(#client),
),
returnValueForMissingStub: _FakeClient_0(
this,
Invocation.getter(#client),
),
) as _i2.Client);
@override
_i5.Future<List<_i3.PokemonModel>> getListPokemon() => (super.noSuchMethod(
Invocation.method(
#getListPokemon,
[],
),
returnValue:
_i5.Future<List<_i3.PokemonModel>>.value(<_i3.PokemonModel>[]),
returnValueForMissingStub:
_i5.Future<List<_i3.PokemonModel>>.value(<_i3.PokemonModel>[]),
) as _i5.Future<List<_i3.PokemonModel>>);
@override
_i5.Future<_i3.PokemonModel> getPokemon(int? id) => (super.noSuchMethod(
Invocation.method(
#getPokemon,
[id],
),
returnValue: _i5.Future<_i3.PokemonModel>.value(_FakePokemonModel_1(
this,
Invocation.method(
#getPokemon,
[id],
),
)),
returnValueForMissingStub:
_i5.Future<_i3.PokemonModel>.value(_FakePokemonModel_1(
this,
Invocation.method(
#getPokemon,
[id],
),
)),
) as _i5.Future<_i3.PokemonModel>);
}
| 0
|
mirrored_repositories/pokedex_flutter/test/domain
|
mirrored_repositories/pokedex_flutter/test/domain/usecases/pokemon_usecase_test.dart
|
// import dos testes
import 'pokemon_usecase_test.mocks.dart';
// import dos domain
import 'package:pokedex/domain/usecases/pokemon_usecase.dart';
import 'package:pokedex/domain/entities/pokemon.dart';
import 'package:pokedex/domain/failures/failure.dart';
// import dos data
import 'package:pokedex/data/repositories/pokemon_repo_impl.dart';
import 'package:pokedex/data/models/pokemon_abilities_model.dart';
import 'package:pokedex/data/models/pokemon_stat_model.dart';
import 'package:pokedex/data/models/pokemon_type_model.dart';
import 'package:pokedex/data/models/pokemon_model.dart';
// import dos pacotes
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:dartz/dartz.dart';
import 'package:test/test.dart';
@GenerateNiceMocks([MockSpec<PokemonRepoImpl>()])
void main() {
group('PokemonUseCases', () {
final mockPokemonRepoImpl = MockPokemonRepoImpl();
final pokemonUseCaseTest = PokemonUseCase(mockPokemonRepoImpl);
// list
group('should return List<PokemonEntity>', () {
test('when pokemonRepoImpl return a List<PokemonEntity>', () async {
List<PokemonModel> listPokemon = [
PokemonModel(
1,
"bulbasaur",
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png",
const [],
null,
null,
const [],
const [],
),
PokemonModel(
2,
"ivysaur",
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/2.png",
const [],
null,
null,
const [],
const [],
),
PokemonModel(
3,
"venusaur",
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/3.png",
const [],
null,
null,
const [],
const [],
),
];
when(
mockPokemonRepoImpl.getListPokemon(),
).thenAnswer(
(realInvocation) => Future.value(
Right( listPokemon ),
),
);
final result = await pokemonUseCaseTest.getListPokemon();
expect(result.isLeft(), false);
expect(result.isRight(), true);
expect(result, Right<Failure, List<PokemonEntity>>(listPokemon));
verify(mockPokemonRepoImpl.getListPokemon()).called(1);
verifyNoMoreInteractions(mockPokemonRepoImpl);
});
});
group('should return left with', () {
test('a ServerFailure', () async {
when(
mockPokemonRepoImpl.getListPokemon(),
).thenAnswer(
(realInvocation) => Future.value(
Left(ServerFailure()),
),
);
final result = await pokemonUseCaseTest.getListPokemon();
expect(result.isLeft(), true);
expect(result.isRight(), false);
expect(result, Left<Failure, List<PokemonEntity>>(ServerFailure()));
verify(mockPokemonRepoImpl.getListPokemon()).called(1);
verifyNoMoreInteractions(mockPokemonRepoImpl);
});
test('a GeneralFailure', () async {
when(
mockPokemonRepoImpl.getListPokemon(),
).thenAnswer(
(realInvocation) => Future.value(
Left(GeneralFailure()),
),
);
final result = await pokemonUseCaseTest.getListPokemon();
expect(result.isLeft(), true);
expect(result.isRight(), false);
expect(result, Left<Failure, List<PokemonEntity>>(GeneralFailure()));
verify(mockPokemonRepoImpl.getListPokemon()).called(1);
verifyNoMoreInteractions(mockPokemonRepoImpl);
});
});
// details
group('should return a PokemonEntity', () {
test('when pokemonRepoImpl return a PokemonEntity', () async {
PokemonModel pokemonModel = PokemonModel(
150,
"mewtwo",
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/150.png",
[
PokemonTypeModel(1, "psychic"),
],
20,
1220,
[
PokemonStatModel("hp", 106),
PokemonStatModel("attack", 110),
PokemonStatModel("defense", 90),
PokemonStatModel("special-attack", 154),
PokemonStatModel("special-defense", 90),
PokemonStatModel("speed", 130),
],
[
PokemonAbilitiesModel("pressure"),
PokemonAbilitiesModel("unnerve"),
],
);
when(
mockPokemonRepoImpl.getPokemon(150),
).thenAnswer(
(realInvocation) => Future.value(
Right( pokemonModel ),
),
);
final result = await pokemonUseCaseTest.getPokemon(150);
expect(result.isLeft(), false);
expect(result.isRight(), true);
expect(result, Right<Failure, PokemonEntity>(pokemonModel));
verify(mockPokemonRepoImpl.getPokemon(150)).called(1);
verifyNoMoreInteractions(mockPokemonRepoImpl);
});
});
group('should return left with', () {
test('a ServerFailure', () async {
when(
mockPokemonRepoImpl.getPokemon(150),
).thenAnswer(
(realInvocation) => Future.value(
Left(ServerFailure()),
),
);
final result = await pokemonUseCaseTest.getPokemon(150);
expect(result.isLeft(), true);
expect(result.isRight(), false);
expect(result, Left<Failure, PokemonEntity>(ServerFailure()));
verify(mockPokemonRepoImpl.getPokemon(150)).called(1);
verifyNoMoreInteractions(mockPokemonRepoImpl);
});
test('a GeneralFailure', () async {
when(
mockPokemonRepoImpl.getPokemon(150),
).thenAnswer(
(realInvocation) => Future.value(
Left(GeneralFailure()),
),
);
final result = await pokemonUseCaseTest.getPokemon(150);
expect(result.isLeft(), true);
expect(result.isRight(), false);
expect(result, Left<Failure, PokemonEntity>(GeneralFailure()));
verify(mockPokemonRepoImpl.getPokemon(150)).called(1);
verifyNoMoreInteractions(mockPokemonRepoImpl);
});
});
});
}
| 0
|
mirrored_repositories/pokedex_flutter/test/domain
|
mirrored_repositories/pokedex_flutter/test/domain/usecases/pokemon_usecase_test.mocks.dart
|
// Mocks generated by Mockito 5.4.0 from annotations
// in pokedex/test/domain/usecases/pokemon_usecase_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i5;
import 'package:dartz/dartz.dart' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'package:pokedex/data/datasource/pokemon_remote_datasource.dart' as _i2;
import 'package:pokedex/data/models/pokemon_model.dart' as _i7;
import 'package:pokedex/data/repositories/pokemon_repo_impl.dart' as _i4;
import 'package:pokedex/domain/failures/failure.dart' as _i6;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakePokemonRemoteDatasource_0 extends _i1.SmartFake
implements _i2.PokemonRemoteDatasource {
_FakePokemonRemoteDatasource_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeEither_1<L, R> extends _i1.SmartFake implements _i3.Either<L, R> {
_FakeEither_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [PokemonRepoImpl].
///
/// See the documentation for Mockito's code generation for more information.
class MockPokemonRepoImpl extends _i1.Mock implements _i4.PokemonRepoImpl {
@override
_i2.PokemonRemoteDatasource get pokemonRemoteDatasource =>
(super.noSuchMethod(
Invocation.getter(#pokemonRemoteDatasource),
returnValue: _FakePokemonRemoteDatasource_0(
this,
Invocation.getter(#pokemonRemoteDatasource),
),
returnValueForMissingStub: _FakePokemonRemoteDatasource_0(
this,
Invocation.getter(#pokemonRemoteDatasource),
),
) as _i2.PokemonRemoteDatasource);
@override
_i5.Future<
_i3
.Either<_i6.Failure, List<_i7.PokemonModel>>> getListPokemon() =>
(super.noSuchMethod(
Invocation.method(
#getListPokemon,
[],
),
returnValue:
_i5.Future<_i3.Either<_i6.Failure, List<_i7.PokemonModel>>>.value(
_FakeEither_1<_i6.Failure, List<_i7.PokemonModel>>(
this,
Invocation.method(
#getListPokemon,
[],
),
)),
returnValueForMissingStub:
_i5.Future<_i3.Either<_i6.Failure, List<_i7.PokemonModel>>>.value(
_FakeEither_1<_i6.Failure, List<_i7.PokemonModel>>(
this,
Invocation.method(
#getListPokemon,
[],
),
)),
) as _i5.Future<_i3.Either<_i6.Failure, List<_i7.PokemonModel>>>);
@override
_i5.Future<_i3.Either<_i6.Failure, _i7.PokemonModel>> getPokemon(int? id) =>
(super.noSuchMethod(
Invocation.method(
#getPokemon,
[id],
),
returnValue:
_i5.Future<_i3.Either<_i6.Failure, _i7.PokemonModel>>.value(
_FakeEither_1<_i6.Failure, _i7.PokemonModel>(
this,
Invocation.method(
#getPokemon,
[id],
),
)),
returnValueForMissingStub:
_i5.Future<_i3.Either<_i6.Failure, _i7.PokemonModel>>.value(
_FakeEither_1<_i6.Failure, _i7.PokemonModel>(
this,
Invocation.method(
#getPokemon,
[id],
),
)),
) as _i5.Future<_i3.Either<_i6.Failure, _i7.PokemonModel>>);
}
| 0
|
mirrored_repositories/Personal-Expenses-Manager
|
mirrored_repositories/Personal-Expenses-Manager/lib/main.dart
|
import 'package:flutter/material.dart';
import './models/transaction.dart';
import './widgets/new_transaction.dart';
import 'package:flutter/services.dart';
import './widgets/transaction_list.dart';
import './widgets/chart.dart';
void main() {
// WidgetsFlutterBinding.ensureInitialized();
// SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp,DeviceOrientation.portraitDown]);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Personal Expenses',
theme: ThemeData(
primarySwatch: Colors.amber,
accentColor: Colors.purple,
fontFamily: 'Quicksand',
textTheme: ThemeData.light().textTheme.copyWith(
title: TextStyle(
fontFamily: 'Open Sans',
fontWeight: FontWeight.bold,
fontSize: 18,
),
button: TextStyle(color: Colors.white),
),
appBarTheme: AppBarTheme(
textTheme: ThemeData.light().textTheme.copyWith(
title: TextStyle(
fontFamily: 'Open Sans',
fontSize: 20,
)),
),
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
//String titleInput;
//String amountInput;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final List<Transaction> _userTransactions = [
// // Transaction(
// // id: 't1',
// // title: 'New Shoes',
// // amount: 69.99,
// // date: DateTime.now(),
// // ),
// // Transaction(
// // id: 't2',
// // title: 'Weekely Groceries',
// // amount: 16.53,
// // date: DateTime.now(),
// // ),
];
bool _showChart=false;
List<Transaction> get _recentTransactions {
return _userTransactions.where((tx) {
return tx.date.isAfter(
DateTime.now().subtract(
Duration(days: 7),
),
);
}).toList();
}
void _addNewTransaction(
String txTitle, double txAmount, DateTime chosenDate) {
final newTx = Transaction(
title: txTitle,
amount: txAmount,
date: chosenDate,
id: DateTime.now().toString(),
);
setState(() {
_userTransactions.add(newTx);
});
}
void _startAddNewTransaction(BuildContext ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return GestureDetector(
onTap: () {},
child: NewTransaction(_addNewTransaction),
behavior: HitTestBehavior.opaque,
);
},
);
}
void _deleteTransaction(String id) {
setState(() {
_userTransactions.removeWhere((tx) {
return tx.id == id;
});
});
}
@override
Widget build(BuildContext context) {
final isLandscape=MediaQuery.of(context).orientation==Orientation.landscape;
final appBar = AppBar(
title: Text(
'Personal Expenses',
style: TextStyle(fontFamily: 'Open Sans'),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
)
],
);
final txListWidget= Container(height: (MediaQuery.of(context).size.height-appBar.preferredSize.height-MediaQuery.of(context).padding.top)*0.7,child: TransactionList(_userTransactions, _deleteTransaction));
return Scaffold(
appBar: appBar,
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
if(isLandscape) Row(mainAxisAlignment: MainAxisAlignment.center ,children:<Widget>[Text('Show Chart'),Switch(value: _showChart,onChanged: (val){setState(() {
_showChart=val;
});},)],),
if (!isLandscape)
Container(
height: (MediaQuery.of(context).size.height -
appBar.preferredSize.height-MediaQuery.of(context).padding.top) *
0.3,
child: Chart(_recentTransactions),),
if (!isLandscape) txListWidget,
_showChart ?Container(
height: (MediaQuery.of(context).size.height -
appBar.preferredSize.height-MediaQuery.of(context).padding.top) *
0.7,
child: Chart(_recentTransactions)) : txListWidget
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
),
);
}
}
| 0
|
mirrored_repositories/Personal-Expenses-Manager/lib
|
mirrored_repositories/Personal-Expenses-Manager/lib/widgets/new_transaction.dart
|
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class NewTransaction extends StatefulWidget {
final Function addTx;
NewTransaction(this.addTx);
@override
_NewTransactionState createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final titleController = TextEditingController();
final amountController = TextEditingController();
DateTime _selectedDate;
void _submitData() {
if(amountController.text.isEmpty){
return;
}
final enteredTitle = titleController.text;
final enteredAmount = double.parse(amountController.text);
if (enteredTitle.isEmpty || enteredAmount <= 0 || _selectedDate==null) {
return;
}
widget.addTx(
enteredTitle,
enteredAmount,
_selectedDate,
);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now(),
).then((pickedDate){
if(pickedDate==null)
{return;}
setState(() {
_selectedDate=pickedDate;
});
});
}
@override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: titleController,
//onChanged: (val){
//titleInput=val;
// },
),
TextField(
decoration: InputDecoration(labelText: 'Amount'),
controller: amountController,
keyboardType: TextInputType.number,
onSubmitted: (_) => _submitData(),
//onChanged: (val)=>amountInput=val,
),
Container(
height: 70,
child: Row(
children: <Widget>[
Expanded(child: Text(_selectedDate==null?'No date chosen':DateFormat.yMd().format(_selectedDate))),
FlatButton(
textColor: Theme.of(context).primaryColor,
child: Text('Choose Date',
style: TextStyle(
fontWeight: FontWeight.bold,
)),
onPressed: _presentDatePicker,
)
],
),
),
RaisedButton(
child: Text('Add Transaction'),
color: Colors.purple,
textColor: Colors.white,
onPressed: _submitData,
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/Personal-Expenses-Manager/lib
|
mirrored_repositories/Personal-Expenses-Manager/lib/widgets/transaction_list.dart
|
import 'package:flutter/material.dart';
import '../models/transaction.dart';
import 'package:intl/intl.dart';
class TransactionList extends StatelessWidget {
final List<Transaction> transactions;
final Function deleteTx;
TransactionList(this.transactions,this.deleteTx);
@override
Widget build(BuildContext context) {
return transactions.isEmpty
? LayoutBuilder(builder:(ctx,constraints){
return Column(children: <Widget>[
Text(
'No Transaction added yet!',
style: Theme.of(context).textTheme.title,
),
SizedBox(
height: 10,
),
Container(
height: constraints.maxHeight*0.6,
child: Image.asset(
'assets/images/waiting.png',
fit: BoxFit.cover,
))
],);
})
: ListView.builder(
itemBuilder: (ctx, index) {
return Card(
elevation:5,
margin: EdgeInsets.symmetric(vertical:8,horizontal:5),
child: ListTile(
leading: CircleAvatar(
radius: 30,
child: Padding(
padding: EdgeInsets.all(6),
child: FittedBox(
child: Text(
'\$${transactions[index].amount}',
),
),
),
),
title: Text(
transactions[index].title,
style: Theme.of(context).textTheme.title,
),
subtitle: Text(
DateFormat.yMMMd().format(transactions[index].date),
),
trailing:IconButton(icon:Icon(Icons.delete),color:Theme.of(context).errorColor, onPressed:()=>deleteTx(transactions[index].id)) ,
),
);
},
itemCount: transactions.length,
);
}
}
| 0
|
mirrored_repositories/Personal-Expenses-Manager/lib
|
mirrored_repositories/Personal-Expenses-Manager/lib/widgets/chart.dart
|
import 'package:flutter/material.dart';
import '../widgets/chart_bar.dart';
import '../models/transaction.dart';
import 'package:intl/intl.dart';
class Chart extends StatelessWidget {
final List<Transaction> recentTransactions;
Chart(this.recentTransactions);
List<Map<String, Object>> get groupedTransactionValues {
return List.generate(7, (index) {
final weekDay = DateTime.now().subtract(
Duration(days: index),
);
var totalSum=0.0;
for (var i = 0; i < recentTransactions.length; i++) {
if (recentTransactions[i].date.day == weekDay.day &&
recentTransactions[i].date.month == weekDay.month &&
recentTransactions[i].date.year == weekDay.year) {
totalSum+=recentTransactions[i].amount;
}
}
return {'day': DateFormat.E().format(weekDay).substring(0,1), 'amount': totalSum};
}).reversed.toList();
}
double get totalSpending{
return groupedTransactionValues.fold(0.0,(sum,item){
return sum+item['amount'];
});
}
@override
Widget build(BuildContext context) {
return Card(
elevation: 6,
margin: EdgeInsets.all(20),
child: Container(
padding:EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children:groupedTransactionValues.map((data){
return Flexible(
fit: FlexFit.tight,
child: ChartBar(data['day'],data['amount'],
totalSpending==0.0?0.0:(data['amount']as double)/totalSpending,),
);
}).toList(),
),
),
);
}
}
| 0
|
mirrored_repositories/Personal-Expenses-Manager/lib
|
mirrored_repositories/Personal-Expenses-Manager/lib/widgets/chart_bar.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class ChartBar extends StatelessWidget {
final String label;
final double spendingAmount;
final double spendingPctOfTotal;
ChartBar(this.label, this.spendingAmount, this.spendingPctOfTotal);
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder:(ctx,constraints){
return Column(
children: <Widget>[
Container(
height:constraints.maxHeight*0.15,
child: FittedBox(
child: Text('\$${spendingAmount.toStringAsFixed(0)}'))),
SizedBox(
height: constraints.maxHeight*0.05,
),
Container(
height: constraints.maxHeight*0.6,
width: 10,
child: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey, width: 1.0),
color: Color.fromRGBO(220, 220, 220, 1),
borderRadius: BorderRadius.circular(10),
),
),
FractionallySizedBox(
heightFactor: spendingPctOfTotal,
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10),
),
),
),
],
),
),
SizedBox(
height: constraints.maxHeight*0.05,
),
Container(height:constraints.maxHeight*0.15,child: FittedBox(child: Text(label))),
],
);
},);
}
}
| 0
|
mirrored_repositories/Personal-Expenses-Manager/lib
|
mirrored_repositories/Personal-Expenses-Manager/lib/models/transaction.dart
|
import 'package:flutter/foundation.dart';
class Transaction {
final String id;
final String title;
final double amount;
final DateTime date;
Transaction({
@required this.id,
@required this.title,
@required this.amount,
@required this.date,
});
}
| 0
|
mirrored_repositories/Personal-Expenses-Manager
|
mirrored_repositories/Personal-Expenses-Manager/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:flutterapp/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/My-profile
|
mirrored_repositories/My-profile/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:my_profile/ui/company_details_animator.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: new CompanyDetailsAnimator(),
);
}
}
| 0
|
mirrored_repositories/My-profile/lib
|
mirrored_repositories/My-profile/lib/model/company.dart
|
import 'package:meta/meta.dart';
class Company {
Company({
@required this.name,
@required this.location,
@required this.logo,
@required this.backdropPhoto,
@required this.about,
@required this.projects
});
final String name;
final String location;
final String logo;
final String backdropPhoto;
final String about;
final List<Projects> projects;
}
class Projects {
Projects({
@required this.title,
@required this.thumbnail,
@required this.url
});
final String title;
final String thumbnail;
final String url;
}
| 0
|
mirrored_repositories/My-profile/lib
|
mirrored_repositories/My-profile/lib/repo/repo.dart
|
import 'package:my_profile/model/company.dart';
class RepoData {
static final Company jlgc = new Company(
name: 'JeguLabs',
about:
'Cupidatat reprehenderit eiusmod in in sit culpa laborum anim reprehenderit exercitation amet consectetur tempor fugiat. Occaecat officia laborum non veniam mollit anim et veniam. Cillum in cillum exercitation sunt ut sunt reprehenderit ex non.',
backdropPhoto: 'assets/jeguDrop.png',
projects: <Projects>[
new Projects(
title: 'JeguLabs',
thumbnail: 'assets/jegulabs.png',
url: 'https://twitter.com/chuiizeet'
),
new Projects(
title: 'Github',
thumbnail: 'assets/github.png',
url: 'https://github.com/chuiizeet'
),
new Projects(
title: 'Google Play',
thumbnail: 'assets/google-play.png',
url: 'https://play.google.com/store/apps/developer?id=JeguLabs'
),
new Projects(
title: 'App Store',
thumbnail: 'assets/app-store.jpg',
url: 'https://itunes.apple.com/us/developer/jesus-guerra/id1231353703'
),
],
location: 'Nuevo León, MX',
logo: 'assets/j.png'
);
}
| 0
|
mirrored_repositories/My-profile/lib
|
mirrored_repositories/My-profile/lib/ui/company_details_page.dart
|
import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
import 'package:my_profile/model/company.dart';
import 'package:my_profile/ui/company_details_intro_animation.dart';
import 'dart:ui' as ui;
import 'package:my_profile/ui/project_card.dart';
class CompanyDetailsPage extends StatelessWidget {
CompanyDetailsPage({
@required this.company, @required AnimationController controller})
:animation = new CompanyDetailsIntroAnimation(controller);
final Company company;
final CompanyDetailsIntroAnimation animation;
Widget _createAnimation(BuildContext context, Widget child) {
return new Stack(
fit: StackFit.expand,
children: <Widget>[
Opacity(
opacity: animation.bgDropOpacity.value,
child: Image.asset(company.backdropPhoto, fit: BoxFit.cover,),
),
BackdropFilter(
filter: ui.ImageFilter.blur(
sigmaX: animation.bgDropBlur.value,
sigmaY: animation.bgDropBlur.value
),
child: new Container(
color: Colors.black.withOpacity(0.3),
child: _createContent(),
),
)
],
);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new AnimatedBuilder(animation: animation.controller,
builder: _createAnimation),
);
}
Widget _createContent() {
return new SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
_createLogoAvatar(),
_createAboutCompany(),
_createProjectScroller()
],
),
);
}
Widget _createLogoAvatar() {
return new Transform(transform: new Matrix4.diagonal3Values(
animation.avatarSize.value, animation.avatarSize.value, 1.0),
alignment: Alignment.center,
child: Container(
width: double.infinity,
height: 110.0,
margin: const EdgeInsets.only(top: 32.0, left: 20.0),
padding: const EdgeInsets.all(3.0),
child: Row(
children: <Widget>[
CircleAvatar(
backgroundColor: Colors.white,
child: new Image.asset(company.logo, width: 100.0, height: 100.0,),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("Chuy, Flutter enthusiast",
style: new TextStyle(
fontSize: 21 * animation.avatarSize.value + 2.0,
color: Colors.white,
),
),
)
],
),
),);
}
Widget _createAboutCompany() {
return new Padding(padding: const EdgeInsets.only(top: 14.0,
left: 14.0, right: 14.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Text(
company.name,
style: new TextStyle(
color: Colors.white.withOpacity(animation.nameOpacity.value),
fontSize: 30.0 * animation.avatarSize.value + 2.0,
fontWeight: FontWeight.bold
),
),
new Text(
company.location,
style: new TextStyle(
color: Colors.white.withOpacity(animation.locationOpacity.value),
fontWeight: FontWeight.w500
),
),
//LineDivider
new Container(
color: Colors.white.withOpacity(0.8),
margin: const EdgeInsets.symmetric(vertical: 14.0),
width: animation.dividerWidth.value,
height: 1.0,
),
new Text(
company.about,
style: new TextStyle(
color: Colors.white.withOpacity(animation.aboutOpacity.value),
height: 1.4,
),
)
],
),
);
}
Widget _createProjectScroller() {
return new Padding(
padding: const EdgeInsets.only(top: 14.0),
child: Transform(transform: new Matrix4.translationValues(animation.projectScrollerXTranslation.value,
0.0, 0.0),
child: new SizedBox.fromSize(
size: new Size.fromHeight(250),
child: ListView.builder(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 5.0),
itemCount: company.projects.length,
itemBuilder: (BuildContext context, int index){
var project = company.projects[index];
return new ProjectCard(project);
}),
),
),
);
}
}
| 0
|
mirrored_repositories/My-profile/lib
|
mirrored_repositories/My-profile/lib/ui/company_details_intro_animation.dart
|
import 'package:flutter/material.dart';
class CompanyDetailsIntroAnimation {
CompanyDetailsIntroAnimation(this.controller)
: bgDropOpacity = new Tween(begin: 0.5, end: 1.0)
.animate(new CurvedAnimation(parent: controller,
curve: new Interval(0.000, 0.500,
curve: Curves.ease))),
bgDropBlur = new Tween(begin: 0.0, end: 5.0)
.animate(new CurvedAnimation(parent: controller,
curve: new Interval(0.000, 0.800,
curve: Curves.ease))),
avatarSize = new Tween(begin: 0.0, end: 1.0)
.animate(new CurvedAnimation(parent: controller,
curve: new Interval(0.100, 0.400,
curve: Curves.elasticInOut))),
nameOpacity = new Tween(begin: 0.0, end: 1.0)
.animate(new CurvedAnimation(parent: controller,
curve: new Interval(0.350, 0.450,
curve: Curves.easeIn))),
locationOpacity = new Tween(begin: 0.0, end: 0.8)
.animate(new CurvedAnimation(parent: controller,
curve: new Interval(0.500, 0.600,
curve: Curves.easeIn))),
dividerWidth = new Tween(begin: 0.0, end: 225.0)
.animate(new CurvedAnimation(parent: controller,
curve: new Interval(0.650, 0.750,
curve: Curves.fastOutSlowIn))),
aboutOpacity = new Tween(begin: 0.0, end: 0.850)
.animate(new CurvedAnimation(parent: controller,
curve: new Interval(0.750, 0.900,
curve: Curves.easeIn))),
projectScrollerXTranslation = new Tween(begin: 60.0, end: 0.0)
.animate(new CurvedAnimation(parent: controller,
curve: new Interval(0.830, 1.000,
curve: Curves.ease))),
projecScrollerOpacity = new Tween(begin: 0.0, end: 1.0)
.animate(new CurvedAnimation(parent: controller,
curve: new Interval(0.830, 1.000,
curve: Curves.fastOutSlowIn)));
final AnimationController controller;
final Animation<double> bgDropOpacity;
final Animation<double> bgDropBlur;
final Animation<double> avatarSize;
final Animation<double> nameOpacity;
final Animation<double> locationOpacity;
final Animation<double> dividerWidth;
final Animation<double> aboutOpacity;
final Animation<double> projectScrollerXTranslation;
final Animation<double> projecScrollerOpacity;
}
| 0
|
mirrored_repositories/My-profile/lib
|
mirrored_repositories/My-profile/lib/ui/company_details_animator.dart
|
import 'package:flutter/material.dart';
import 'package:my_profile/repo/repo.dart';
import 'package:my_profile/ui/company_details_page.dart';
class CompanyDetailsAnimator extends StatefulWidget {
@override
_CompanyDetailsAnimatorState createState() => _CompanyDetailsAnimatorState();
}
class _CompanyDetailsAnimatorState extends State<CompanyDetailsAnimator>
with SingleTickerProviderStateMixin {
AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 1780),
vsync: this);
_controller.forward();
}
@override
void dispose() {
super.dispose();
_controller.dispose();
}
@override
Widget build(BuildContext context) {
return new CompanyDetailsPage(company: RepoData.jlgc,
controller: _controller,);
}
}
| 0
|
mirrored_repositories/My-profile/lib
|
mirrored_repositories/My-profile/lib/ui/project_card.dart
|
import 'package:flutter/material.dart';
import 'package:my_profile/model/company.dart';
import 'package:url_launcher/url_launcher.dart';
class ProjectCard extends StatelessWidget {
ProjectCard(this.project);
final Projects project;
BoxDecoration _createShadowRoundCorners() {
return BoxDecoration(
color: Colors.white.withOpacity(0.5),
borderRadius: new BorderRadius.circular(12.0),
boxShadow: <BoxShadow>[
new BoxShadow(
color: Colors.black,
spreadRadius: 2.0,
blurRadius: 10.0
)
]);
}
Widget _createThumbnail() {
return new ClipRRect(
borderRadius: new BorderRadius.circular(10.0),
child: Stack(
children: <Widget>[
Image.asset(project.thumbnail),
new Positioned(
bottom: 12.0,
right: 12.0,
child: _createLinkButton(),)
],
),
);
}
Widget _createLinkButton() {
return new Material(
color: Colors.white24,
type: MaterialType.circle,
child: new IconButton(
icon: Icon(Icons.link),
onPressed: () async {
if(await canLaunch(project.url)) {
await launch(project.url);
}
}),
);
}
@override
Widget build(BuildContext context) {
return Container(
width: 175.0,
padding: const EdgeInsets.all(10.0),
margin: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 15.0),
decoration: _createShadowRoundCorners(),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Flexible(
flex: 3,
child: _createThumbnail()),
Flexible(
flex: 2,
child: _createInfo())
],
),
);
}
Widget _createInfo() {
return new Padding(
padding: const EdgeInsets.only(top: 18.0, right: 4.0, left: 4.0),
child: new Text(
project.title,
style: new TextStyle(
color: Colors.white.withOpacity(0.85)
),
),
);
}
}
| 0
|
mirrored_repositories/My-profile
|
mirrored_repositories/My-profile/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:my_profile/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_first_app
|
mirrored_repositories/flutter_first_app/lib/dogs.dart
|
import 'package:flutter/material.dart';
class Dogs extends StatelessWidget {
final List<String> dogs;
Dogs(this.dogs);
@override
Widget build(BuildContext context) {
return Column(
children: dogs
.map(
(element) => Card(
child: Column(
children: <Widget>[
Image.asset('assets/sammy.jpg'),
Text(element)
],
),
),
)
.toList(),
);
}
}
| 0
|
mirrored_repositories/flutter_first_app
|
mirrored_repositories/flutter_first_app/lib/main.dart
|
import 'package:flutter/material.dart';
import './dog_manager.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('The Dog List'),
),
body: DogManager('Sammy the Samoyed'),
),
);
}
}
| 0
|
mirrored_repositories/flutter_first_app
|
mirrored_repositories/flutter_first_app/lib/dog_manager.dart
|
import 'package:flutter/material.dart';
import './dogs.dart';
class DogManager extends StatefulWidget {
final String startingDog;
DogManager(this.startingDog);
@override
State<StatefulWidget> createState() {
return _DogManagerState();
}
}
class _DogManagerState extends State<DogManager> {
List<String> _dogs = [];
@override
void initState() {
_dogs.add(widget.startingDog);
super.initState();
}
@override
Widget build(BuildContext context) {
return Column(children: [Container(
margin: EdgeInsets.all(10.0),
child: RaisedButton(
onPressed: () {
setState(() {
_dogs.add('Ronnie the Rhodesian Ridgeback');
print(_dogs);
});
},
child: Text('Add Dog')),
),
Dogs(_dogs)
],);
}
}
| 0
|
mirrored_repositories/flutter_first_app
|
mirrored_repositories/flutter_first_app/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_first_app/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/MealApp
|
mirrored_repositories/MealApp/lib/dummy_data.dart
|
import 'package:flutter/material.dart';
import './models/category.dart';
import './models/meal.dart';
const DUMMY_CATEGORIES = const [
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,
),
];
const DUMMY_MEALS = const [
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/MealApp
|
mirrored_repositories/MealApp/lib/main.dart
|
import 'package:flutter/material.dart';
import './dummy_data.dart';
import './screens/tabs_screen.dart';
import './screens/meal_detail_screen.dart';
import './screens/category_meals_screen.dart';
import './screens/filters_screen.dart';
import './screens/categories_screen.dart';
import './models/meal.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Map<String, bool> _filters = {
'gluten': false,
'lactose': false,
'vegan': false,
'vegetarian': false,
};
List<Meal> _availableMeals = DUMMY_MEALS;
List<Meal> _favoriteMeals = [];
void _setFilters(Map<String, bool> filterData) {
setState(() {
_filters = filterData;
_availableMeals = DUMMY_MEALS.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 mealId) {
final existingIndex =
_favoriteMeals.indexWhere((meal) => meal.id == mealId);
if (existingIndex >= 0) {
setState(() {
_favoriteMeals.removeAt(existingIndex);
});
} else {
setState(() {
_favoriteMeals.add(
DUMMY_MEALS.firstWhere((meal) => meal.id == mealId),
);
});
}
}
bool _isMealFavorite(String id) {
return _favoriteMeals.any((meal) => meal.id == id);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'DeliMeals',
theme: ThemeData(
primarySwatch: Colors.pink,
accentColor: Colors.amber,
canvasColor: Color.fromRGBO(255, 254, 229, 1),
fontFamily: 'Raleway',
textTheme: ThemeData.light().textTheme.copyWith(
body1: TextStyle(
color: Color.fromRGBO(20, 51, 51, 1),
),
body2: TextStyle(
color: Color.fromRGBO(20, 51, 51, 1),
),
title: TextStyle(
fontSize: 20,
fontFamily: 'RobotoCondensed',
fontWeight: FontWeight.bold,
)),
),
// home: CategoriesScreen(),
initialRoute: '/', // default is '/'
routes: {
'/': (ctx) => TabsScreen(_favoriteMeals),
CategoryMealsScreen.routeName: (ctx) =>
CategoryMealsScreen(_availableMeals),
MealDetailScreen.routeName: (ctx) => MealDetailScreen(_toggleFavorite, _isMealFavorite),
FiltersScreen.routeName: (ctx) => FiltersScreen(_filters, _setFilters),
},
onGenerateRoute: (settings) {
print(settings.arguments);
// if (settings.name == '/meal-detail') {
// return ...;
// } else if (settings.name == '/something-else') {
// return ...;
// }
// return MaterialPageRoute(builder: (ctx) => CategoriesScreen(),);
},
onUnknownRoute: (settings) {
return MaterialPageRoute(
builder: (ctx) => CategoriesScreen(),
);
},
);
}
}
| 0
|
mirrored_repositories/MealApp/lib
|
mirrored_repositories/MealApp/lib/widgets/meal_item.dart
|
import 'package:flutter/material.dart';
import '../screens/meal_detail_screen.dart';
import '../models/meal.dart';
class MealItem extends StatelessWidget {
final String id;
final String title;
final String imageUrl;
final int duration;
final Complexity complexity;
final Affordability affordability;
MealItem(
{@required this.id,
@required this.title,
@required this.imageUrl,
@required this.affordability,
@required this.complexity,
@required this.duration,});
String get complexityText {
switch (complexity) {
case Complexity.Simple:
return 'Simple';
break;
case Complexity.Challenging:
return 'Challenging';
break;
case Complexity.Hard:
return 'Hard';
break;
default:
return 'Unknown';
}
}
String get affordabilityText {
switch (affordability) {
case Affordability.Affordable:
return 'Affordable';
break;
case Affordability.Pricey:
return 'Pricey';
break;
case Affordability.Luxurious:
return 'Expensive';
break;
default:
return 'Unknown';
}
}
void selectMeal(BuildContext context) {
Navigator.of(context)
.pushNamed(
MealDetailScreen.routeName,
arguments: id,
)
.then((result) {
if (result != null) {
// removeItem(result);
}
});
}
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () => selectMeal(context),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
elevation: 4,
margin: EdgeInsets.all(10),
child: Column(
children: <Widget>[
Stack(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15),
topRight: Radius.circular(15),
),
child: Image.network(
imageUrl,
height: 250,
width: double.infinity,
fit: BoxFit.cover,
),
),
Positioned(
bottom: 20,
right: 10,
child: Container(
width: 300,
color: Colors.black54,
padding: EdgeInsets.symmetric(
vertical: 5,
horizontal: 20,
),
child: Text(
title,
style: TextStyle(
fontSize: 26,
color: Colors.white,
),
softWrap: true,
overflow: TextOverflow.fade,
),
),
)
],
),
Padding(
padding: EdgeInsets.all(20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Row(
children: <Widget>[
Icon(
Icons.schedule,
),
SizedBox(
width: 6,
),
Text('$duration min'),
],
),
Row(
children: <Widget>[
Icon(
Icons.work,
),
SizedBox(
width: 6,
),
Text(complexityText),
],
),
Row(
children: <Widget>[
Icon(
Icons.attach_money,
),
SizedBox(
width: 6,
),
Text(affordabilityText),
],
),
],
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/MealApp/lib
|
mirrored_repositories/MealApp/lib/widgets/main_drawer.dart
|
import 'package:flutter/material.dart';
import '../screens/filters_screen.dart';
class MainDrawer extends StatelessWidget {
Widget buildListTile(String title, IconData icon, Function tapHandler) {
return ListTile(
leading: Icon(
icon,
size: 26,
),
title: Text(
title,
style: TextStyle(
fontFamily: 'RobotoCondensed',
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
onTap: tapHandler,
);
}
@override
Widget build(BuildContext context) {
return Drawer(
child: Column(
children: <Widget>[
Container(
height: 120,
width: double.infinity,
padding: EdgeInsets.all(20),
alignment: Alignment.centerLeft,
color: Theme.of(context).accentColor,
child: Text(
'Cooking Up!',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 30,
color: Theme.of(context).primaryColor),
),
),
SizedBox(
height: 20,
),
buildListTile('Meals', Icons.restaurant, () {
Navigator.of(context).pushReplacementNamed('/');
}),
buildListTile('Filters', Icons.settings, () {
Navigator.of(context).pushReplacementNamed(FiltersScreen.routeName);
}),
],
),
);
}
}
| 0
|
mirrored_repositories/MealApp/lib
|
mirrored_repositories/MealApp/lib/widgets/category_item.dart
|
import 'package:flutter/material.dart';
import '../screens/category_meals_screen.dart';
class CategoryItem extends StatelessWidget {
final String id;
final String title;
final Color color;
CategoryItem(this.id, this.title, this.color);
void selectCategory(BuildContext ctx) {
Navigator.of(ctx).pushNamed(
CategoryMealsScreen.routeName,
arguments: {
'id': id,
'title': title,
},
);
}
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () => selectCategory(context),
splashColor: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(15),
child: Container(
padding: const EdgeInsets.all(15),
child: Text(
title,
style: Theme.of(context).textTheme.title,
),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
color.withOpacity(0.7),
color,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(15),
),
),
);
}
}
| 0
|
mirrored_repositories/MealApp/lib
|
mirrored_repositories/MealApp/lib/models/meal.dart
|
import 'package:flutter/foundation.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/MealApp/lib
|
mirrored_repositories/MealApp/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/MealApp/lib
|
mirrored_repositories/MealApp/lib/screens/favorites_screen.dart
|
import 'package:flutter/material.dart';
import '../models/meal.dart';
import '../widgets/meal_item.dart';
class FavoritesScreen extends StatelessWidget {
final List<Meal> favoriteMeals;
FavoritesScreen(this.favoriteMeals);
@override
Widget build(BuildContext context) {
if (favoriteMeals.isEmpty) {
return Center(
child: Text('You have no favorites yet - start adding some!'),
);
} else {
return ListView.builder(
itemBuilder: (ctx, index) {
return MealItem(
id: favoriteMeals[index].id,
title: favoriteMeals[index].title,
imageUrl: favoriteMeals[index].imageUrl,
duration: favoriteMeals[index].duration,
affordability: favoriteMeals[index].affordability,
complexity: favoriteMeals[index].complexity,
);
},
itemCount: favoriteMeals.length,
);
}
}
}
| 0
|
mirrored_repositories/MealApp/lib
|
mirrored_repositories/MealApp/lib/screens/tabs_screen.dart
|
import 'package:flutter/material.dart';
import '../widgets/main_drawer.dart';
import './favorites_screen.dart';
import './categories_screen.dart';
import '../models/meal.dart';
class TabsScreen extends StatefulWidget {
final List<Meal> favoriteMeals;
TabsScreen(this.favoriteMeals);
@override
_TabsScreenState createState() => _TabsScreenState();
}
class _TabsScreenState extends State<TabsScreen> {
List<Map<String, Object>> _pages;
int _selectedPageIndex = 0;
@override
void initState() {
_pages = [
{
'page': CategoriesScreen(),
'title': 'Categories',
},
{
'page': FavoritesScreen(widget.favoriteMeals),
'title': 'Your Favorite',
},
];
super.initState();
}
void _selectPage(int index) {
setState(() {
_selectedPageIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_pages[_selectedPageIndex]['title']),
),
drawer: MainDrawer(),
body: _pages[_selectedPageIndex]['page'],
bottomNavigationBar: BottomNavigationBar(
onTap: _selectPage,
backgroundColor: Theme.of(context).primaryColor,
unselectedItemColor: Colors.white,
selectedItemColor: Theme.of(context).accentColor,
currentIndex: _selectedPageIndex,
// type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
backgroundColor: Theme.of(context).primaryColor,
icon: Icon(Icons.category),
title: Text('Categories'),
),
BottomNavigationBarItem(
backgroundColor: Theme.of(context).primaryColor,
icon: Icon(Icons.star),
title: Text('Favorites'),
),
],
),
);
}
}
| 0
|
mirrored_repositories/MealApp/lib
|
mirrored_repositories/MealApp/lib/screens/meal_detail_screen.dart
|
import 'package:flutter/material.dart';
import '../dummy_data.dart';
class MealDetailScreen extends StatelessWidget {
static const routeName = '/meal-detail';
final Function toggleFavorite;
final Function isFavorite;
MealDetailScreen(this.toggleFavorite, this.isFavorite);
Widget buildSectionTitle(BuildContext context, String text) {
return Container(
margin: EdgeInsets.symmetric(vertical: 10),
child: Text(
text,
style: Theme.of(context).textTheme.title,
),
);
}
Widget buildContainer(Widget child) {
return Container(
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(10),
),
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(10),
height: 150,
width: 300,
child: child,
);
}
@override
Widget build(BuildContext context) {
final mealId = ModalRoute.of(context).settings.arguments as String;
final selectedMeal = DUMMY_MEALS.firstWhere((meal) => meal.id == mealId);
return Scaffold(
appBar: AppBar(
title: Text('${selectedMeal.title}'),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
height: 300,
width: double.infinity,
child: Image.network(
selectedMeal.imageUrl,
fit: BoxFit.cover,
),
),
buildSectionTitle(context, 'Ingredients'),
buildContainer(
ListView.builder(
itemBuilder: (ctx, index) => Card(
color: Theme.of(context).accentColor,
child: Padding(
padding: EdgeInsets.symmetric(
vertical: 5,
horizontal: 10,
),
child: Text(selectedMeal.ingredients[index])),
),
itemCount: selectedMeal.ingredients.length,
),
),
buildSectionTitle(context, 'Steps'),
buildContainer(
ListView.builder(
itemBuilder: (ctx, index) => Column(
children: [
ListTile(
leading: CircleAvatar(
child: Text('# ${(index + 1)}'),
),
title: Text(
selectedMeal.steps[index],
),
),
Divider()
],
),
itemCount: selectedMeal.steps.length,
),
),
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(
isFavorite(mealId) ? Icons.star : Icons.star_border,
),
onPressed: () => toggleFavorite(mealId),
),
);
}
}
| 0
|
mirrored_repositories/MealApp/lib
|
mirrored_repositories/MealApp/lib/screens/categories_screen.dart
|
import 'package:flutter/material.dart';
import '../dummy_data.dart';
import '../widgets/category_item.dart';
class CategoriesScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GridView(
padding: const EdgeInsets.all(25),
children: DUMMY_CATEGORIES
.map(
(catData) => CategoryItem(
catData.id,
catData.title,
catData.color,
),
)
.toList(),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
childAspectRatio: 3 / 2,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
),
);
}
}
| 0
|
mirrored_repositories/MealApp/lib
|
mirrored_repositories/MealApp/lib/screens/filters_screen.dart
|
import 'package:flutter/material.dart';
import '../widgets/main_drawer.dart';
class FiltersScreen extends StatefulWidget {
static const routeName = '/filters';
final Function saveFilters;
final Map<String, bool> currentFilters;
FiltersScreen(this.currentFilters, this.saveFilters);
@override
_FiltersScreenState createState() => _FiltersScreenState();
}
class _FiltersScreenState extends State<FiltersScreen> {
bool _glutenFree = false;
bool _vegetarian = false;
bool _vegan = false;
bool _lactoseFree = false;
@override
initState() {
_glutenFree = widget.currentFilters['gluten'];
_lactoseFree = widget.currentFilters['lactose'];
_vegetarian = widget.currentFilters['vegetarian'];
_vegan = widget.currentFilters['vegan'];
super.initState();
}
Widget _buildSwitchListTile(
String title,
String description,
bool currentValue,
Function updateValue,
) {
return SwitchListTile(
title: Text(title),
value: currentValue,
subtitle: Text(
description,
),
onChanged: updateValue,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Your Filters'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.save),
onPressed: () {
final selectedFilters = {
'gluten': _glutenFree,
'lactose': _lactoseFree,
'vegan': _vegan,
'vegetarian': _vegetarian,
};
widget.saveFilters(selectedFilters);
},
)
],
),
drawer: MainDrawer(),
body: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(20),
child: Text(
'Adjust your meal selection.',
style: Theme.of(context).textTheme.title,
),
),
Expanded(
child: ListView(
children: <Widget>[
_buildSwitchListTile(
'Gluten-free',
'Only include gluten-free meals.',
_glutenFree,
(newValue) {
setState(
() {
_glutenFree = newValue;
},
);
},
),
_buildSwitchListTile(
'Lactose-free',
'Only include lactose-free meals.',
_lactoseFree,
(newValue) {
setState(
() {
_lactoseFree = newValue;
},
);
},
),
_buildSwitchListTile(
'Vegetarian',
'Only include vegetarian meals.',
_vegetarian,
(newValue) {
setState(
() {
_vegetarian = newValue;
},
);
},
),
_buildSwitchListTile(
'Vegan',
'Only include vegan meals.',
_vegan,
(newValue) {
setState(
() {
_vegan = newValue;
},
);
},
)
],
),
),
],
),
);
}
}
| 0
|
mirrored_repositories/MealApp/lib
|
mirrored_repositories/MealApp/lib/screens/category_meals_screen.dart
|
import 'package:flutter/material.dart';
import '../widgets/meal_item.dart';
import '../models/meal.dart';
class CategoryMealsScreen extends StatefulWidget {
static const routeName = '/category-meals';
final List<Meal> availableMeals;
CategoryMealsScreen(this.availableMeals);
@override
_CategoryMealsScreenState createState() => _CategoryMealsScreenState();
}
class _CategoryMealsScreenState extends State<CategoryMealsScreen> {
String categoryTitle;
List<Meal> displayedMeals;
var _loadedInitData = false;
@override
void initState() {
// ...
super.initState();
}
@override
void didChangeDependencies() {
if (!_loadedInitData) {
final routeArgs =
ModalRoute.of(context).settings.arguments as Map<String, String>;
categoryTitle = routeArgs['title'];
final categoryId = routeArgs['id'];
displayedMeals = widget.availableMeals.where((meal) {
return meal.categories.contains(categoryId);
}).toList();
_loadedInitData = true;
}
super.didChangeDependencies();
}
void _removeMeal(String mealId) {
setState(() {
displayedMeals.removeWhere((meal) => meal.id == mealId);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(categoryTitle),
),
body: ListView.builder(
itemBuilder: (ctx, index) {
return MealItem(
id: displayedMeals[index].id,
title: displayedMeals[index].title,
imageUrl: displayedMeals[index].imageUrl,
duration: displayedMeals[index].duration,
affordability: displayedMeals[index].affordability,
complexity: displayedMeals[index].complexity,
);
},
itemCount: displayedMeals.length,
),
);
}
}
| 0
|
mirrored_repositories/MealApp
|
mirrored_repositories/MealApp/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:meal/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/mymood
|
mirrored_repositories/mymood/lib/quiz.dart
|
import 'package:flutter/material.dart';
import './question.dart';
import './answer.dart';
class Quiz extends StatelessWidget {
final List<Map<String, Object>>questions;
final int questionIndex;
final Function answerQuestion;
Quiz({
@required this.questions,
@required this.questionIndex,
@required this.answerQuestion
});
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Center(
child: Row(
children: <Widget>[
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Container(
child: Row(
children: <Widget>[
Question(questions[questionIndex]['questionText']),
],
),
),
),
),
],
),
],
),
),
...(questions[questionIndex]['answers'] as List<Map<String, Object>>)
.map((answer){
return Answer(() => answerQuestion(answer['value']), answer['text']);
}).toList(),
],
),
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/mymood
|
mirrored_repositories/mymood/lib/question.dart
|
import 'package:flutter/material.dart';
class Question extends StatelessWidget {
final String questionText;
Question(this.questionText);
@override
Widget build(BuildContext context) {
return Column(children: [
SizedBox(
height: 24,
),
Container(
width: 414,
height: 250,
child:
Image.asset('assets/images/freedom.png',
fit: BoxFit.cover,
),
),
Container(
width: double.infinity,
margin: EdgeInsets.only(left: 10, top: 10, right: 10, bottom: 0),
child: Text(
questionText,
style: TextStyle(
fontSize: 26,
fontWeight: FontWeight.bold,
color: Colors.white,
),
textAlign: TextAlign.center,
),
),
]);
}
}
| 0
|
mirrored_repositories/mymood
|
mirrored_repositories/mymood/lib/answer.dart
|
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final Function selectHandler;
final String answerText;
Answer(this.selectHandler,this.answerText);
@override
Widget build(BuildContext context) {
return Container(
width: 200,
margin: EdgeInsets.only(left: 60, top: 5, right: 60, bottom: 5),
child: RaisedButton(
elevation: 4.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)
),
color: Colors.yellow[200],
textColor: Colors.green,
child: Text(answerText,
style: TextStyle(fontSize: 20,
fontWeight: FontWeight.w600),),
onPressed: selectHandler,
),
);
}
}
| 0
|
mirrored_repositories/mymood
|
mirrored_repositories/mymood/lib/result.dart
|
import 'package:flutter/material.dart';
class Result extends StatelessWidget {
final Function resetHandler;
final List<String> answerText;
Result(this.answerText, this.resetHandler);
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 10, top: 30, right: 10, bottom: 0),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(10),
height: 250,
width: 250,
child: ShaderMask(
shaderCallback: (img) {
return LinearGradient(
begin: Alignment(0.0, 0.0),
end: Alignment.bottomRight,
colors: [ Colors.transparent,Colors.lightGreen[400]],
).createShader(Rect.fromLTRB(0, 0, img.width, img.height));
},
blendMode: BlendMode.multiply,
child: Image.asset('assets/images/pic2.png',
fit: BoxFit.cover,)),
),
Container(
padding: EdgeInsets.all(10),
child: Text(
'Today you are:',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
],
),
),
Expanded(
child: ListView.builder(
itemCount: answerText.length,
itemBuilder: (context, index) {
return Container(
margin:
EdgeInsets.only(left: 60, top: 0, right: 60, bottom: 0),
child: Card(
elevation: 5.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)
),
margin: EdgeInsets.all(5),
child: Container(
height: 40,
child: Center(
child: Text(
answerText[index],
style: TextStyle(fontSize: 20,
fontWeight: FontWeight.w600,
color: Colors.green,
),
textAlign: TextAlign.center,
),
),
),
));
},
),
),
Container(
width: 200,
height: 100,
margin: EdgeInsets.all(10),
child: FlatButton(
child: Text(
'Reset Quiz',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
onPressed: resetHandler),
),
],
);
}
}
| 0
|
mirrored_repositories/mymood
|
mirrored_repositories/mymood/lib/main.dart
|
import 'package:flutter/material.dart';
import './quiz.dart';
import './result.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
final _questions = const [
{
'questionText': 'What color do you like today?',
'answers': [
{'text': 'Blue', 'value': 'Calm'},
{'text': 'Red', 'value': 'Bold'},
{'text': 'Orange', 'value': 'Friendly'},
{'text': 'Brown', 'value': 'Simple'},
{'text': 'White', 'value': 'Innocent'},
{'text': 'Black', 'value': 'Part mood'}
]
},
{
'questionText': 'What music do you like to today?',
'answers': [
{'text': 'Pop', 'value': 'A high self-esteem'},
{'text': 'Rap', 'value': 'Sensing'},
{'text': 'Rock', 'value': 'Debater'},
{'text': 'Metal', 'value': 'Creative'},
{'text': 'Classical', 'value': 'Intuition'},
{'text': 'R&B', 'value': 'Emotional'}
]
},
{
'questionText': 'What sport do you like today?',
'answers': [
{'text': 'Football', 'value': 'Future'},
{'text': 'Soccer', 'value': 'Organized'},
{'text': 'Baseball', 'value': 'Patient'},
{'text': 'Tennis', 'value': 'Aggressive'},
{'text': 'Golf', 'value': 'Smartest'},
{'text': 'Basketball', 'value': 'Like Praise'}
]
},
{
'questionText': 'How do you look today?',
'answers': [
{'text': 'Sporty', 'value': 'Optimistic'},
{'text': 'Clean and Simple', 'value': 'Kind'},
{'text': 'Make a Statement', 'value': 'Charismatic'},
{'text': 'Free - Spirited', 'value': 'Enthusiastic'},
{'text': 'Trend - Setter', 'value': 'Helpful'},
{'text': 'Homestead Chic', 'value': 'Productive'}
]
},
{
'questionText': 'What car you would drive today?',
'answers': [
{'text': 'Mercedes', 'value': 'King'},
{'text': 'BMW', 'value': 'Rumbling engine'},
{'text': 'Ferrari', 'value': 'Refined'},
{'text': 'Nissan', 'value': 'Practical'},
{'text': 'Lomborghini', 'value': 'Exotic'},
{'text': 'Porsche', 'value': 'Boss'}
]
},
];
List<String> _answers = List<String>();
var _questionIndex = 0;
void _resetQuiz(){
setState(() {
_questionIndex = 0;
_answers.clear();
});
}
void _answerQuestion(String answerText) {
setState(() {
_questionIndex = _questionIndex + 1;
_answers.add(answerText);
});
print(_questionIndex);
print(answerText);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.lightGreen[400],
body: _questionIndex < _questions.length
? Quiz(
questions: _questions,
questionIndex: _questionIndex,
answerQuestion: _answerQuestion)
: Result(_answers, _resetQuiz),
),
);
}
}
| 0
|
mirrored_repositories/mymood
|
mirrored_repositories/mymood/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:my_mood/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/juice-bar
|
mirrored_repositories/juice-bar/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:juicebar/models/cart_model.dart';
import 'package:juicebar/ui/screens/onboardings/display_screen.dart';
import 'package:provider/provider.dart';
void main(List<String> args) {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => CartModel(),
child: const GetMaterialApp(
debugShowCheckedModeBanner: false,
home: DisplayScreen(),
),
);
// this one is for multiple provider
/*
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => CounterProvider()),
ChangeNotifierProvider(create: (_) => ExampleOneProvider()),
],
child: const Scaffold(
body: CounterExample(),
));
*/
// this one is for single provider
/*
return ChangeNotifierProvider(
create: (context) => CounterProvider(),
child: const MaterialApp(
debugShowCheckedModeBanner: false,
home: ExampleOneScreen(),
),
);
*/
}
}
| 0
|
mirrored_repositories/juice-bar/lib
|
mirrored_repositories/juice-bar/lib/constants/text_styles.dart
|
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
TextStyle homeScreenBannerText = GoogleFonts.redHatDisplay(
fontWeight: FontWeight.bold,
fontSize: 30,
color: Colors.grey.shade800,
);
TextStyle onboardingText = GoogleFonts.varelaRound();
TextStyle recommendedTitleText = GoogleFonts.ubuntu(fontSize: 18);
| 0
|
mirrored_repositories/juice-bar/lib
|
mirrored_repositories/juice-bar/lib/constants/responsive.dart
|
import 'package:flutter/material.dart';
double height(BuildContext context) {
return MediaQuery.of(context).size.height;
}
double width(BuildContext context) {
return MediaQuery.of(context).size.width;
}
| 0
|
mirrored_repositories/juice-bar/lib
|
mirrored_repositories/juice-bar/lib/constants/colors.dart
|
import 'package:flutter/material.dart';
Color grey = Colors.grey;
| 0
|
mirrored_repositories/juice-bar/lib
|
mirrored_repositories/juice-bar/lib/controllers/cart_controllers.dart
|
import 'package:get/get.dart';
class CartController extends GetxController {
var price = 0.obs;
addMoney(value) {
price.value++;
}
}
| 0
|
mirrored_repositories/juice-bar/lib
|
mirrored_repositories/juice-bar/lib/models/items_model.dart
|
class JuiceJson {
List<Juices>? juices;
JuiceJson({this.juices});
JuiceJson.fromJson(Map<String, dynamic> json) {
if (json['juices'] != null) {
juices = <Juices>[];
json['juices'].forEach((v) {
juices!.add(Juices.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
if (juices != null) {
data['juices'] = juices!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Juices {
String? imagePath;
String? juiceName;
String? juiceDescription;
double? price;
Juices({this.imagePath, this.juiceName, this.juiceDescription, this.price});
Juices.fromJson(Map<String, dynamic> json) {
imagePath = json['imagePath'];
juiceName = json['juiceName'];
juiceDescription = json['juiceDescription'];
price = json['price'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['imagePath'] = imagePath;
data['juiceName'] = juiceName;
data['juiceDescription'] = juiceDescription;
data['price'] = price;
return data;
}
}
| 0
|
mirrored_repositories/juice-bar/lib
|
mirrored_repositories/juice-bar/lib/models/cart_model.dart
|
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
class CartModel with ChangeNotifier {
static List _list = [].obs;
static Future<void> readJson() async {
final String response =
await rootBundle.loadString('assets/juiceshop.json');
final data = await json.decode(response);
_list = data['juices'];
}
get list => _list;
}
| 0
|
mirrored_repositories/juice-bar/lib/ui
|
mirrored_repositories/juice-bar/lib/ui/widgets/recommended_widgets.dart
|
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../controllers/cart_controllers.dart';
class RecommendedWidget extends StatelessWidget {
final String title;
final String subtitle;
final String price;
final String img;
final VoidCallback onTap;
RecommendedWidget({
super.key,
required this.title,
required this.subtitle,
required this.price,
required this.img,
required this.onTap,
});
// getx cart controller initialize
final CartController cartController = Get.put(CartController());
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
height: 280,
width: 200,
color: Colors.yellow.shade100,
child: Stack(
children: [
Align(
alignment: Alignment.bottomCenter,
child: Container(
height: 200,
width: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.white,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(top: 40, left: 20),
child: Text(
title,
style: GoogleFonts.ubuntu(
fontWeight: FontWeight.bold, fontSize: 20),
),
),
Padding(
padding: const EdgeInsets.only(top: 10, left: 20),
child: Text(
subtitle,
style: GoogleFonts.ubuntu(fontSize: 12),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: const EdgeInsets.only(top: 10, left: 20),
child: Text(
"\$$price",
style: GoogleFonts.ubuntu(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
),
Padding(
padding: const EdgeInsets.only(right: 20, top: 10),
child: Container(
height: 40,
width: 40,
decoration: BoxDecoration(
color: Colors.brown,
borderRadius: BorderRadius.circular(10)),
child: IconButton(
color: Colors.white,
onPressed: onTap,
icon: const Icon(Icons.add)),
),
),
],
),
],
),
),
),
Positioned(
top: 15,
right: 55,
child: CircleAvatar(
backgroundColor: Colors.yellow.shade100,
maxRadius: 50,
child: Image.asset(
img,
height: 70,
width: 70,
),
),
),
],
),
),
],
);
}
}
| 0
|
mirrored_repositories/juice-bar/lib/ui
|
mirrored_repositories/juice-bar/lib/ui/widgets/popular_widgets.dart
|
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class PopularWidgets extends StatelessWidget {
const PopularWidgets({
super.key,
});
@override
Widget build(BuildContext context) {
return Column(
children: const [
PopularInsideWidget(
imgPath: 'assets/images/pomegranate.png',
juiceName: 'Pomegranate\nJuice',
juicePrice: '3.50'),
SizedBox(height: 10),
PopularInsideWidget(
imgPath: 'assets/images/apple.png',
juiceName: 'Apple Juice',
juicePrice: '3.00'),
SizedBox(height: 10),
PopularInsideWidget(
imgPath: 'assets/images/grapefruit.png',
juiceName: 'Grapefruit Juice',
juicePrice: '3.00'),
SizedBox(height: 10),
PopularInsideWidget(
imgPath: 'assets/images/mango.png',
juiceName: 'Mango Juice',
juicePrice: '4.00'),
SizedBox(height: 10),
],
);
}
}
class PopularInsideWidget extends StatelessWidget {
const PopularInsideWidget({
super.key,
required this.imgPath,
required this.juiceName,
required this.juicePrice,
});
final String imgPath;
final String juiceName;
final String juicePrice;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Container(
height: 100,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.green.shade400,
borderRadius: BorderRadius.circular(15)),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Padding(
padding: const EdgeInsets.all(15.0),
child: Image.asset(imgPath),
),
Padding(
padding: const EdgeInsets.only(top: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
juiceName,
style: GoogleFonts.ubuntu(
fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 10),
Text(
'\$$juicePrice',
style: GoogleFonts.ubuntu(fontWeight: FontWeight.bold),
),
],
),
),
],
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Container(
height: 40,
width: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.white),
child: IconButton(
icon: const Icon(
Icons.add,
color: Colors.black,
),
onPressed: () => {},
),
),
)
],
),
),
);
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.