repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/ambrish/lib/view/projects
|
mirrored_repositories/ambrish/lib/view/projects/components/project_link.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../model/project_model.dart';
class ProjectLinks extends StatelessWidget {
final int index;
const ProjectLinks({super.key, required this.index});
@override
Widget build(BuildContext context) {
return Row(
children: [
Row(
children: [
const Text('Check on Github',style: TextStyle(color: Colors.white),overflow: TextOverflow.ellipsis),
IconButton(onPressed: () {launchUrl(Uri.parse(projectList[index].link));}, icon: SvgPicture.asset('assets/icons/github.svg')),
],
),
const Spacer(),
TextButton(
onPressed: () {
launchUrl(Uri.parse(projectList[index].link));
}, child: const Text('Read More>>',overflow: TextOverflow.ellipsis,style: TextStyle(color: Colors.amber,fontWeight: FontWeight.bold,fontSize: 10),))
],
);
}
}
| 0
|
mirrored_repositories/ambrish/lib/view/projects
|
mirrored_repositories/ambrish/lib/view/projects/components/project_info.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_portfolio/view/projects/components/project_deatail.dart';
import 'package:get/get.dart';
import '../../../model/project_model.dart';
import '../../../res/constants.dart';
import '../../../view model/getx_controllers/projects_controller.dart';
import 'image_viewer.dart';
class ProjectStack extends StatelessWidget {
final controller = Get.put(ProjectController());
ProjectStack({super.key, required this.index});
final int index;
@override
Widget build(BuildContext context) {
return InkWell(
onHover: (value) {
controller.onHover(index, value);
},
onTap: () {
ImageViewer(context,projectList[index].image);
},
borderRadius: BorderRadius.circular(30),
child: AnimatedContainer(
padding: const EdgeInsets.only(left: defaultPadding,right: defaultPadding,top: defaultPadding),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: bgColor),
duration: const Duration(milliseconds: 500),
child: ProjectDetail(index: index,),
),
);
}
}
| 0
|
mirrored_repositories/ambrish/lib/view/projects
|
mirrored_repositories/ambrish/lib/view/projects/components/title_text.dart
|
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import '../../../view model/responsive.dart';
class TitleText extends StatelessWidget {
const TitleText({super.key, required this.prefix, required this.title});
final String prefix;
final String title;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'$prefix ',
style: Theme.of(context).textTheme.titleMedium!.copyWith(
color: Colors.white,
fontSize: !Responsive.isDesktop(context)
? Responsive.isLargeMobile(context)
? 20
: 30
: 50,
fontWeight: FontWeight.bold),
),
kIsWeb && Responsive.isDesktop(context)
? ShaderMask(
shaderCallback: (bounds) {
return const LinearGradient(
end: Alignment.centerRight,
begin: Alignment.centerLeft,
colors: [
Colors.pink,
Colors.cyanAccent,
]).createShader(bounds);
},
child: Text(
title,
style: Theme.of(context).textTheme.titleMedium!.copyWith(
color: Colors.white,
fontSize: !Responsive.isDesktop(context)
? Responsive.isLargeMobile(context)
? 20
: 30
: 50,
fontWeight: FontWeight.bold),
),
)
: Text(
title,
style: Theme.of(context).textTheme.titleMedium!.copyWith(
color: Colors.white,
fontSize: !Responsive.isDesktop(context)
? Responsive.isLargeMobile(context)
? 20
: 30
: 50,
fontWeight: FontWeight.bold),
),
],
);
}
}
| 0
|
mirrored_repositories/ambrish/lib/view/projects
|
mirrored_repositories/ambrish/lib/view/projects/components/project_deatail.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_portfolio/view/projects/components/project_link.dart';
import '../../../model/project_model.dart';
import '../../../res/constants.dart';
import '../../../view model/responsive.dart';
class ProjectDetail extends StatelessWidget {
final int index;
const ProjectDetail({super.key, required this.index});
@override
Widget build(BuildContext context) {
var size=MediaQuery.sizeOf(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Align(alignment: Alignment.topCenter,child: Text(
projectList[index].name,
style: Theme.of(context)
.textTheme
.headlineSmall!
.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),),
Responsive.isMobile(context) ? const SizedBox(height: defaultPadding/2,) : const SizedBox(height: defaultPadding,),
Text(projectList[index].description,style: const TextStyle(color: Colors.grey,height: 1.5),maxLines: size.width>700 && size.width< 750 ? 3: size.width<470 ? 2 : size.width>600 && size.width<700 ? 6: size.width>900 && size.width <1060 ? 6: 4 ,overflow: TextOverflow.ellipsis,),
const Spacer(),
ProjectLinks(index: index,),
const SizedBox(height: defaultPadding/2,),
],
);
}
}
| 0
|
mirrored_repositories/ambrish/lib/view/projects
|
mirrored_repositories/ambrish/lib/view/projects/components/image_viewer.dart
|
import 'package:photo_view/photo_view.dart';
import 'package:flutter/material.dart';
class ImageViewer {
ImageViewer(BuildContext context, String image) {
showGeneralDialog(
barrierColor: Colors.black,
transitionDuration: Duration(milliseconds: 500),
barrierDismissible: true,
barrierLabel: 'Barrier',
context: context,
pageBuilder: (context, animation, secondaryAnimation) {
return Center(
child: Hero(
tag: 'IMAGEVIEW',
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Scaffold(
backgroundColor: Colors.black,
body: Container(
color: Colors.white,
child: Center(
child: PhotoView(imageProvider: AssetImage(image))
),
)),
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/ambrish/lib/view
|
mirrored_repositories/ambrish/lib/view/certifications/certifications.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_portfolio/view%20model/getx_controllers/certification_controller.dart';
import 'package:flutter_portfolio/view/projects/components/title_text.dart';
import 'package:get/get.dart';
import '../../res/constants.dart';
import '../../view model/responsive.dart';
import 'components/certification_grid.dart';
class Certifications extends StatelessWidget {
final controller=Get.put(CertificationController());
Certifications({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if(Responsive.isLargeMobile(context))const SizedBox(
height: defaultPadding,
),
const TitleText(prefix: 'Certifications & ', title: 'License'),
const SizedBox(
height: defaultPadding,
),
Expanded(
child: Responsive(
desktop: CertificateGrid(crossAxisCount: 3,ratio: 1.5,),
extraLargeScreen: CertificateGrid(crossAxisCount: 4,ratio: 1.6),
largeMobile: CertificateGrid(crossAxisCount: 1,ratio: 1.8),
mobile: CertificateGrid(crossAxisCount: 1,ratio: 1.4),
tablet: CertificateGrid(ratio: 1.7,crossAxisCount: 2,)))
],
),
);
}
}
| 0
|
mirrored_repositories/ambrish/lib/view/certifications
|
mirrored_repositories/ambrish/lib/view/certifications/components/certification_grid.dart
|
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../model/certificate_model.dart';
import '../../../res/constants.dart';
import '../../../view model/getx_controllers/certification_controller.dart';
import 'certificates_details.dart';
class CertificateGrid extends StatelessWidget {
final int crossAxisCount;
final double ratio;
CertificateGrid({super.key, this.crossAxisCount = 3, this.ratio=1.3});
final controller = Get.put(CertificationController());
@override
Widget build(BuildContext context) {
return GridView.builder(
padding: const EdgeInsets.symmetric(horizontal: 30),
itemCount: certificateList.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: crossAxisCount, childAspectRatio: ratio),
itemBuilder: (context, index) {
return Obx(() => AnimatedContainer(
duration: const Duration(milliseconds: 200),
margin: const EdgeInsets.symmetric(
vertical: defaultPadding, horizontal: defaultPadding),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
gradient: const LinearGradient(colors: [
Colors.pinkAccent,
Colors.blue,
]),
boxShadow: [
BoxShadow(
color: Colors.pink,
offset: const Offset(-2, 0),
blurRadius: controller.hovers[index] ? 20 : 10,
),
BoxShadow(
color: Colors.blue,
offset: const Offset(2, 0),
blurRadius: controller.hovers[index] ? 20 : 10,),
]),
child: CertificateStack(index: index)
));
},
);
}
}
| 0
|
mirrored_repositories/ambrish/lib/view/certifications
|
mirrored_repositories/ambrish/lib/view/certifications/components/certificates_details.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../model/certificate_model.dart';
import '../../../res/constants.dart';
import '../../../view model/getx_controllers/certification_controller.dart';
class CertificateStack extends StatelessWidget {
final controller = Get.put(CertificationController());
CertificateStack({super.key, required this.index});
final int index;
@override
Widget build(BuildContext context) {
return InkWell(
onHover: (value) {
controller.onHover(index, value);
},
onTap: () {
},
borderRadius: BorderRadius.circular(30),
child: AnimatedContainer(
padding: const EdgeInsets.all(defaultPadding),
height: double.infinity,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: bgColor),
duration: const Duration(milliseconds: 500),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
certificateList[index].name,
style: Theme.of(context)
.textTheme
.subtitle2!
.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: defaultPadding,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(certificateList[index].organization,style: const TextStyle(color: Colors.amber),),
Text(certificateList[index].date,style: const TextStyle(color: Colors.grey,fontSize: 12),),
],
),
const SizedBox(height: defaultPadding/2,),
Text.rich(
maxLines: 1,
TextSpan(
text: 'Skills : ',style: const TextStyle(color: Colors.white,),
children: [
TextSpan(
text: certificateList[index].skills,style: const TextStyle(color: Colors.grey,overflow: TextOverflow.ellipsis),)
]
),),
const SizedBox(height: defaultPadding,),
InkWell(
onTap: () {
launchUrl(Uri.parse(certificateList[index].credential));
},
child: Container(
height: 40,
width: 150,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
gradient: LinearGradient(
colors: [
Colors.pink,
Colors.blue.shade900,
]
),
boxShadow:const [
BoxShadow(color: Colors.blue,offset: Offset(0, -1),blurRadius: 5),
BoxShadow(color: Colors.red,offset: Offset(0, 1),blurRadius: 5),
]
),
child: const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Credentials',style: TextStyle(color: Colors.white,fontSize: 10),),
SizedBox(width: 5,),
Icon(
CupertinoIcons.arrow_turn_up_right,color: Colors.white,size: 10,
)
],
),
),
),
],
),
)),
);
}
}
| 0
|
mirrored_repositories/ambrish/lib/view
|
mirrored_repositories/ambrish/lib/view/home/home.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_portfolio/view/certifications/certifications.dart';
import 'package:flutter_portfolio/view/intro/introduction.dart';
import 'package:flutter_portfolio/view/main/main_view.dart';
import 'package:flutter_portfolio/view/projects/project_view.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return MainView(pages: [
const Introduction(),
ProjectsView(),
Certifications(),
]);
}
}
| 0
|
mirrored_repositories/ambrish/lib/view
|
mirrored_repositories/ambrish/lib/view/splash/splash_view.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_portfolio/res/constants.dart';
import 'package:flutter_portfolio/view/home/home.dart';
import 'package:flutter_portfolio/view/intro/components/animated_texts_componenets.dart';
import 'package:flutter_portfolio/view/splash/componenets/animated_loading_text.dart';
class SplashView extends StatefulWidget {
const SplashView({super.key});
@override
State<SplashView> createState() => _SplashViewState();
}
class _SplashViewState extends State<SplashView> {
@override
void initState() {
// TODO: implement initState
super.initState();
Timer(const Duration(seconds: 3), () {
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => const HomePage(),));
});
}
@override
Widget build(BuildContext context) {
return const Scaffold(
backgroundColor: bgColor,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
AnimatedImageContainer(width: 100,height: 100,),
SizedBox(height: defaultPadding,),
AnimatedLoadingText(),
],
),
),
);
}
}
| 0
|
mirrored_repositories/ambrish/lib/view/splash
|
mirrored_repositories/ambrish/lib/view/splash/componenets/animated_loading_text.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_portfolio/res/constants.dart';
class AnimatedLoadingText extends StatelessWidget {
const AnimatedLoadingText({super.key});
@override
Widget build(BuildContext context) {
return SizedBox(
width: defaultPadding * 5,
child: TweenAnimationBuilder(duration: const Duration(seconds: 2),builder: (context, value, child) => Column(
children: [
LinearProgressIndicator(
backgroundColor: Colors.black,
color: Colors.deepPurpleAccent,
value: value,
),
const SizedBox(height: defaultPadding/2,),
Text(
'${(value * 100).toInt()}%',style: const TextStyle(color: Colors.white,fontWeight: FontWeight.bold,shadows: [
Shadow(color: Colors.pink,blurRadius: 10 , offset: Offset(2,2)),
Shadow(color: Colors.blue,blurRadius: 10 , offset: Offset(-2,-2)),
]),)
],
), tween: Tween(begin: 0.0,end: 1.0),),
);
}
}
| 0
|
mirrored_repositories/ambrish/lib
|
mirrored_repositories/ambrish/lib/res/constants.dart
|
import 'package:flutter/material.dart';
const primaryColor = Colors.white;
const secondaryColor = Color(0xFF242430);
const darkColor = Color(0xFF191923);
const bodyTextColor = Color(0xFF8B8B8D);
const bgColor = Color(0xFF000515);
const defaultPadding = 20.0;
| 0
|
mirrored_repositories/ambrish/lib
|
mirrored_repositories/ambrish/lib/model/project_model.dart
|
class Project {
final String name;
final String description;
final String image;
final String link;
Project(this.name, this.description, this.image, this.link);
}
List<Project> projectList = [
Project(
'Foody Application',
'Presenting "Foods" - a Flutter UI application that invites you to indulge in a delightful foody adventure. Immerse yourself in the world of rich aroma and flavor as you browse through an exquisite selection of specialty foods. With a user-friendly interface, exploring different blends and discovering their unique details becomes a delightful experience.',
'assets/images/food.png',
'https://github.com/AmbrishTripathi6974/FoodyApp',
),
Project(
'RentX Application UI',
'RentX: Your Complete Estate Management Solution. RentX is the ultimate estate management app, simplifying property management tasks. Effectively manage rent collection, maintenance requests, and tenant communication. Access financial reports and lease agreements effortlessly. Optimize your real estate investments with ease, all within the user-friendly RentX app.',
'assets/images/rentx.png',
'https://github.com/AmbrishTripathi6974/RentX',
),
Project(
'Task Management Application',
'Organiza is a powerful task management app designed to streamline your daily life. With intuitive features, it allows you to effortlessly organize, prioritize, and track tasks. Enhance productivity through task categorization, due date reminders, and collaborative sharing. Say goodbye to chaos and hello to efficient task management with Organiza.',
'assets/images/task1.png',
'https://github.com/AmbrishTripathi6974/TaskOrganiza'),
];
| 0
|
mirrored_repositories/ambrish/lib
|
mirrored_repositories/ambrish/lib/model/certificate_model.dart
|
class CertificateModel {
final String name;
final String organization;
final String date;
final String skills;
final String credential;
CertificateModel({
required this.name,
required this.organization,
required this.date,
required this.skills,
required this.credential,
});
}
List<CertificateModel> certificateList = [
CertificateModel(
name: 'Google x AMD Solving for India Hackathon',
organization: 'GeekforGeeks',
date: 'MAY 2023',
skills: 'Kotlin . Flutter . Dart',
credential: 'https://drive.google.com/file/d/1dcbjnSz6yOeEKXCy90l9kRF04V3YW_HK/view?usp=drive_link',
),
];
| 0
|
mirrored_repositories/ambrish/lib
|
mirrored_repositories/ambrish/lib/view model/responsive.dart
|
import 'package:flutter/material.dart';
class Responsive extends StatelessWidget {
const Responsive({super.key, required this.desktop, required this.largeMobile,required this.mobile,required this.tablet, this.extraLargeScreen});
final Widget desktop;
final Widget? largeMobile;
final Widget mobile;
final Widget? tablet;
final Widget? extraLargeScreen;
static bool isMobile(BuildContext context){
return MediaQuery.sizeOf(context).width <= 500;
}
static bool isLargeMobile(BuildContext context){
return MediaQuery.sizeOf(context).width <=700;
}
static bool isTablet(BuildContext context){
return MediaQuery.sizeOf(context).width < 1080;
}
static bool isDesktop(BuildContext context){
return MediaQuery.sizeOf(context).width > 1024;
}
static bool isExtraLargeScreen(BuildContext context){
return MediaQuery.sizeOf(context).width > 1400;
}
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
if (size.width > 1400 && extraLargeScreen!=null) {
return extraLargeScreen!;
}
else if (size.width >= 1080) {
return desktop;
} else if (size.width >= 700 && tablet != null) {
return tablet!;
} else if (size.width >= 500 && largeMobile != null) {
return largeMobile!;
} else {
return mobile;
}
}
}
| 0
|
mirrored_repositories/ambrish/lib
|
mirrored_repositories/ambrish/lib/view model/controller.dart
|
import 'package:flutter/material.dart';
final PageController controller=PageController();
| 0
|
mirrored_repositories/ambrish/lib/view model
|
mirrored_repositories/ambrish/lib/view model/getx_controllers/projects_controller.dart
|
import 'package:get/get.dart';
class ProjectController extends GetxController{
RxList<bool> hovers =[
false,
false,
false,
false,
false,
false,
false,
false,
false,
].obs;
onHover(int index,bool value){
hovers[index]=value;
}
}
| 0
|
mirrored_repositories/ambrish/lib/view model
|
mirrored_repositories/ambrish/lib/view model/getx_controllers/certification_controller.dart
|
import 'package:get/get.dart';
class CertificationController extends GetxController{
RxList<bool> hovers=[
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
].obs;
onHover(int index,bool value){
hovers[index]=value;
}
}
| 0
|
mirrored_repositories/ambrish
|
mirrored_repositories/ambrish/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_portfolio/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/Car-Enthusiast
|
mirrored_repositories/Car-Enthusiast/lib/main.dart
|
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'app/routes/app_pages.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
title: "Car Enthusiast",
initialRoute: Routes.LOGIN,
getPages: AppPages.routes,
);
}
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app
|
mirrored_repositories/Car-Enthusiast/lib/app/routes/app_routes.dart
|
part of 'app_pages.dart';
// DO NOT EDIT. This is code generated via package:get_cli/get_cli.dart
abstract class Routes {
Routes._();
static const HOME = _Paths.HOME;
static const LOGIN = _Paths.LOGIN;
static const REGISTER = _Paths.REGISTER;
static const PROFIL = _Paths.PROFIL;
static const CART = _Paths.CART;
}
abstract class _Paths {
_Paths._();
static const HOME = '/home';
static const LOGIN = '/login';
static const REGISTER = '/register';
static const PROFIL = '/profil';
static const CART = '/cart';
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app
|
mirrored_repositories/Car-Enthusiast/lib/app/routes/app_pages.dart
|
import 'package:get/get.dart';
import '../modules/Cart/bindings/cart_binding.dart';
import '../modules/Cart/views/cart_view.dart';
import '../modules/Login/bindings/login_binding.dart';
import '../modules/Login/bindings/login_binding.dart';
import '../modules/Login/views/login_view.dart';
import '../modules/Login/views/login_view.dart';
import '../modules/Profil/bindings/profil_binding.dart';
import '../modules/Profil/views/profil_view.dart';
import '../modules/home/bindings/home_binding.dart';
import '../modules/home/views/home_view.dart';
import '../modules/register/bindings/register_binding.dart';
import '../modules/register/views/register_view.dart';
part 'app_routes.dart';
class AppPages {
AppPages._();
static const INITIAL = Routes.HOME;
static final routes = [
GetPage(
name: _Paths.HOME,
page: () => const HomeView(),
binding: HomeBinding(),
),
GetPage(
name: _Paths.LOGIN,
page: () => LoginView(),
binding: LoginBinding(),
),
GetPage(
name: _Paths.REGISTER,
page: () => RegisterView(),
binding: RegisterBinding(),
),
GetPage(
name: _Paths.PROFIL,
page: () => ProfilView(),
binding: ProfilBinding(),
),
GetPage(
name: _Paths.CART,
page: () => CartView(),
binding: CartBinding(),
),
];
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Cart
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Cart/views/cart_view.dart
|
import 'package:car_enthusiast/app/modules/home/views/home_view.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/cart_controller.dart';
class CartView extends StatefulWidget {
const CartView({Key? key}) : super(key: key);
@override
State<CartView> createState() => _CartViewState();
}
class _CartViewState extends State<CartView> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
void _decrementCounter() {
setState(() {
_counter--;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
'Cart',
style: TextStyle(fontFamily: 'KanitEB'),
),
centerTitle: true,
backgroundColor: Color(0xff19DE21),
),
body: Column(
children: [
const SizedBox(
height: 20.0,
),
ListView.builder(
itemCount: 4,
shrinkWrap: true,
itemBuilder: (context, index) {
return Card(
child: ListTile(
leading: CircleAvatar(
backgroundColor: Colors.grey[200],
backgroundImage: const NetworkImage(
"https://i.ibb.co/5xh0jrf/istrfry-marcus-9m-QHr1-Ws-EK0-unsplash-1.png",
),
),
title: const Text("Rocket Bunny Body Kits"),
subtitle: const Text("704,74 USD"),
trailing: SizedBox(
width: 150.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Card(
color: Colors.grey[800],
child: IconButton(
iconSize: 20,
onPressed: _decrementCounter,
icon: Icon(Icons.remove),
color: Colors.white,
),
),
Text(
"$_counter",
style: TextStyle(
fontFamily: 'Kanit',
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
Card(
color: Colors.grey[800],
child: IconButton(
onPressed: _incrementCounter,
icon: Icon(
Icons.add,
color: Colors.white,
),
),
),
],
),
),
),
);
},
),
],
),
bottomNavigationBar: Padding(
padding: const EdgeInsets.only(right: 30.0),
child: BottomNavigationBar(
elevation: 0,
type: BottomNavigationBarType.fixed,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Add To',
style: TextStyle(
fontFamily: 'Kanit',
fontSize: 15,
fontWeight: FontWeight.bold,
color: Color(0xff19DE21)),
),
Text(
'Cart',
style: TextStyle(
fontFamily: 'Kanit',
fontSize: 15,
fontWeight: FontWeight.bold,
color: Color(0xff19DE21)),
),
],
),
label: '',
),
BottomNavigationBarItem(
icon: Column(
children: [
Container(
width: 226,
height: 60,
child: TextButton(
style: TextButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)),
backgroundColor: Color(0xff19DE21)),
onPressed: () {
Get.to(() => convexbottombar(),
transition: Transition.zoom,
duration: Duration(seconds: 1));
},
child: Text(
'Checkout',
style: TextStyle(
fontFamily: 'Kanit',
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.white),
)),
),
],
),
label: '',
),
],
),
),
);
}
}
// class CartView extends GetView<CartController> {
// const CartView({Key? key}) : super(key: key);
// @override
// Widget build(BuildContext context) {
// }
// }
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Cart
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Cart/controllers/cart_controller.dart
|
import 'package:get/get.dart';
class CartController extends GetxController {
//TODO: Implement CartController
final count = 0.obs;
@override
void onInit() {
super.onInit();
}
@override
void onReady() {
super.onReady();
}
@override
void onClose() {
super.onClose();
}
void increment() => count.value++;
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Cart
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Cart/bindings/cart_binding.dart
|
import 'package:get/get.dart';
import '../controllers/cart_controller.dart';
class CartBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut<CartController>(
() => CartController(),
);
}
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Login
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Login/views/login_view.dart
|
import 'package:car_enthusiast/app/modules/home/views/home_view.dart';
import 'package:car_enthusiast/app/modules/register/views/register_view.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/login_controller.dart';
class LoginView extends GetView<LoginController> {
static Future<User?> loginUsingEmailPassword(
//fungsi dibawah ini digunakan untuk autentication email yaitu membutuhkan email dan password
// dengan type data string
{required String email,
required String password,
required BuildContext context}) async {
FirebaseAuth auth = FirebaseAuth.instance;
User? user;
try {
UserCredential userCredential = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
user = userCredential.user;
} on FirebaseAuthException catch (e) {
if (e.code == "user-not-found") {
print("No user found for that email");
}
}
return user;
}
// untuk controll text dalam form agar dapat memasukkan data valid
final emailController = TextEditingController();
final passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Container(
height: 1000,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/bg1.png'),
fit: BoxFit.cover,
opacity: 10,
),
),
),
const SizedBox(
height: 20.0,
),
Container(
child: ListView(
children: <Widget>[
const SizedBox(
height: 30.0,
),
Container(
height: 200,
child: Image.asset('assets/car.png'),
),
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Car Enthusiast",
style: TextStyle(
fontSize: 40.0,
fontFamily: 'KanitEB',
color: Colors.white,
fontWeight: FontWeight.bold),
),
Text(
" .",
style: TextStyle(
fontSize: 40.0,
fontFamily: 'KanitEB',
color: Colors.green,
fontWeight: FontWeight.bold),
),
],
),
),
Center(
child: Text(
"Sign In",
style: TextStyle(
fontSize: 40.0,
fontFamily: 'KanitEB',
color: Color(0xff19DE21),
),
),
),
const SizedBox(
height: 20.0,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 35.0),
child: TextFormField(
controller: emailController,
decoration: InputDecoration(
floatingLabelBehavior: FloatingLabelBehavior.never,
fillColor: Color.fromARGB(71, 255, 255, 255),
filled: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(35),
borderSide: const BorderSide(
width: 0, style: BorderStyle.none)),
// labelText: 'Masukkan Email',
hintText: 'Email',
hintStyle: TextStyle(
fontFamily: 'Kanit',
color: Color.fromARGB(173, 255, 255, 255),
),
labelStyle: TextStyle(
color: Colors.blueGrey,
),
),
onChanged: (value) {},
),
),
const SizedBox(
height: 20.0,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 35.0),
child: Container(
child: TextFormField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(
floatingLabelBehavior: FloatingLabelBehavior.never,
fillColor: Color.fromARGB(71, 255, 255, 255),
filled: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(35),
borderSide: const BorderSide(
width: 0, style: BorderStyle.none)),
labelText: 'Password',
labelStyle: TextStyle(
color: Color.fromARGB(173, 255, 255, 255),
),
)),
),
),
const SizedBox(
height: 20.0,
),
GestureDetector(
onTap: () {},
child: Center(
child: Text(
'Forgot Password?',
style: TextStyle(
color: Colors.white,
decoration: TextDecoration.underline,
),
),
),
),
const SizedBox(
height: 20.0,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 40.0),
child: ElevatedButton(
onPressed: () async {
User? user = await loginUsingEmailPassword(
email: emailController.text,
password: passwordController.text,
context: context);
print(user);
if (user != null) {
Get.to(() => convexbottombar(),
transition: Transition.zoom,
duration: Duration(seconds: 1));
}
},
child: Container(
height: 55,
child: Center(
child: Text(
'Login',
style: TextStyle(fontFamily: 'KanitEB', fontSize: 18),
),
),
),
style: ElevatedButton.styleFrom(
primary: Color(0xff19DE21),
)),
),
const SizedBox(
height: 20.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Text(
'Dont Have an Account? ',
style: TextStyle(
color: Colors.white,
),
),
),
GestureDetector(
onTap: () {
Get.to(() => RegisterView(),
transition: Transition.zoom,
duration: Duration(seconds: 1));
},
child: Center(
child: Text(
'Create Account',
style: TextStyle(
color: Color(0xff19DE21),
),
),
),
),
],
)
],
)),
],
),
);
}
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Login
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Login/controllers/login_controller.dart
|
import 'package:get/get.dart';
class LoginController extends GetxController {
//TODO: Implement LoginController
final count = 0.obs;
@override
void onInit() {
super.onInit();
}
@override
void onReady() {
super.onReady();
}
@override
void onClose() {
super.onClose();
}
void increment() => count.value++;
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Login
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Login/bindings/login_binding.dart
|
import 'package:get/get.dart';
import '../controllers/login_controller.dart';
class LoginBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut<LoginController>(
() => LoginController(),
);
}
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Profil
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Profil/views/profil_view.dart
|
// import 'dart:html';
import 'package:car_enthusiast/app/modules/Cart/views/cart_view.dart';
import 'package:car_enthusiast/app/modules/Login/views/login_view.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/profil_controller.dart';
class ProfilView extends GetView<ProfilController> {
final user = FirebaseAuth.instance.currentUser!;
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Stack(
children: [
Container(
height: 140,
width: 400,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/bg1.png'),
fit: BoxFit.cover,
opacity: 40,
),
),
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 20.0,
),
CircleAvatar(
radius: 35,
),
const SizedBox(
width: 10.0,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Hi!!',
style: TextStyle(
fontSize: 18,
fontFamily: 'Kanit',
color: Colors.white),
),
Text(
user.email!,
style: TextStyle(
fontSize: 20,
fontFamily: 'KanitEB',
color: Colors.white),
),
],
)
]),
),
),
Container(
child: ListView(
children: <Widget>[
const SizedBox(
height: 160.0,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Text(
'My Order',
style: TextStyle(
fontSize: 20,
fontFamily: 'Kanit',
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(
height: 20.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Column(
children: [
IconButton(
onPressed: () {
Get.to(() => CartView(),
transition: Transition.zoom,
duration: Duration(seconds: 1));
},
icon: Icon(Icons.card_travel)),
Text('Cart')
],
),
const SizedBox(
width: 40.0,
),
Column(
children: [
IconButton(
onPressed: () {}, icon: Icon(Icons.payment)),
Text('Payment')
],
),
const SizedBox(
width: 40.0,
),
Column(
children: [
IconButton(
onPressed: () {},
icon: Icon(Icons.send_to_mobile)),
Text('Send')
],
),
const SizedBox(
width: 40.0,
),
Column(
children: [
IconButton(
onPressed: () {}, icon: Icon(Icons.star_rate)),
Text('Rating')
],
)
],
),
const SizedBox(
height: 40.0,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Text(
'History',
style: TextStyle(
fontSize: 20,
fontFamily: 'Kanit',
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(
height: 20.0,
),
SizedBox(
height: 140.0,
child: ListView.builder(
itemCount: 10,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Container(
width: 140,
margin: const EdgeInsets.only(right: 10.0),
decoration: BoxDecoration(
image: const DecorationImage(
image: NetworkImage(
"https://images.unsplash.com/photo-1482049016688-2d3e1b311543?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=710&q=80",
),
fit: BoxFit.cover,
),
borderRadius: const BorderRadius.all(
Radius.circular(16.0),
),
color: Colors.blue[400],
),
child: Stack(
children: [
Container(
padding: const EdgeInsets.all(6.0),
margin: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.green[800],
borderRadius: const BorderRadius.all(
Radius.circular(
12.0,
),
),
),
child: const Text(
"PROMO",
style: TextStyle(
color: Colors.white,
fontSize: 8.0,
),
),
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
padding: const EdgeInsets.all(12.0),
decoration: const BoxDecoration(
color: Colors.black38,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(16.0),
bottomRight: Radius.circular(16.0),
),
),
child: const Text(
"Rocket Bunny Body Kits",
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11.0,
color: Colors.white,
),
),
),
),
],
),
);
},
),
),
const SizedBox(
height: 60.0,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 100.0),
child: Container(
height: 50,
child: ElevatedButton(
onPressed: () {
FirebaseAuth.instance.signOut().then((value) {
print("Signed Out");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoginView()));
});
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.logout),
const SizedBox(
width: 10.0,
),
Text(
'Logout',
style:
TextStyle(fontFamily: 'Kanit', fontSize: 18),
),
],
),
style: ElevatedButton.styleFrom(
primary: Colors.grey,
),
),
),
)
],
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Profil
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Profil/controllers/profil_controller.dart
|
import 'package:get/get.dart';
class ProfilController extends GetxController {
//TODO: Implement ProfilController
final count = 0.obs;
@override
void onInit() {
super.onInit();
}
@override
void onReady() {
super.onReady();
}
@override
void onClose() {
super.onClose();
}
void increment() => count.value++;
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Profil
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/Profil/bindings/profil_binding.dart
|
import 'package:get/get.dart';
import '../controllers/profil_controller.dart';
class ProfilBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut<ProfilController>(
() => ProfilController(),
);
}
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/home
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/home/views/home_view.dart
|
import 'package:car_enthusiast/app/modules/Profil/views/profil_view.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_nav_bar/google_nav_bar.dart';
import '../controllers/home_controller.dart';
class convexbottombar extends StatefulWidget {
convexbottombar({Key? key}) : super(key: key);
@override
State<convexbottombar> createState() => _convexbottombarState();
}
class _convexbottombarState extends State<convexbottombar> {
final _pgno = [HomeView(), ProfilView()];
int _pilihtabbar = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.w600);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Home',
style: optionStyle,
),
Text(
'Profile',
style: optionStyle,
),
];
void _changetabbar(int index) {
setState(() {
_pilihtabbar = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _pgno[_pilihtabbar],
bottomNavigationBar: Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
blurRadius: 20,
color: Colors.black.withOpacity(.1),
)
],
),
child: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 8),
child: GNav(
rippleColor: Colors.grey[300]!,
hoverColor: Colors.grey[100]!,
gap: 8,
activeColor: Colors.black,
iconSize: 24,
padding: EdgeInsets.symmetric(horizontal: 40, vertical: 18),
duration: Duration(milliseconds: 400),
tabBackgroundColor: Colors.grey[100]!,
color: Colors.black,
tabs: [
GButton(
icon: Icons.car_repair,
text: 'Car Ite',
),
GButton(
icon: Icons.person,
text: 'Profile',
),
],
selectedIndex: _pilihtabbar,
onTabChange: (index) {
setState(() {
_pilihtabbar = index;
});
},
),
),
),
),
);
}
}
class HomeView extends GetView<HomeController> {
const HomeView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: ListView(children: [
const SizedBox(
height: 40.0,
),
Container(
padding: const EdgeInsets.symmetric(
vertical: 6.0,
horizontal: 12.0,
),
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: const BorderRadius.all(
Radius.circular(12.0),
),
border: Border.all(
width: 1.0,
color: Colors.grey[400]!,
),
),
child: Row(
children: [
const Padding(
padding: EdgeInsets.all(8.0),
child: Icon(Icons.search),
),
Expanded(
child: TextFormField(
initialValue: null,
decoration: const InputDecoration.collapsed(
filled: true,
fillColor: Colors.transparent,
hoverColor: Colors.transparent,
hintText: "Search",
hintStyle: TextStyle(fontFamily: 'Kanit')),
onFieldSubmitted: (value) {},
),
),
],
),
),
const SizedBox(
height: 20.0,
),
SizedBox(
height: 40.0,
child: ListView.builder(
itemCount: 5,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Container(
width: 100.0,
padding: const EdgeInsets.all(10.0),
margin: const EdgeInsets.only(right: 10.0),
decoration: BoxDecoration(
color: Color(0xff19DE21),
borderRadius: const BorderRadius.all(
Radius.circular(16.0),
),
),
child: Center(
child: Text(
"Categori ${index + 1}",
style: const TextStyle(
color: Colors.white,
fontSize: 11.0,
fontFamily: 'Kanit'),
),
),
);
},
),
),
const SizedBox(
height: 20.0,
),
Builder(
builder: (context) {
List items = [
{
"id": 1,
"photo":
"https://i.ibb.co/19nQxhQ/erik-mclean-ZRns2-R5azu0-unsplash.png",
"onTap": (item) {},
},
{
"id": 2,
"photo":
"https://i.ibb.co/f8RWPZW/Modified-Bmw-E30-M3-Evo-Dtm-Sony-Xperia-X-XZ-Z5-Pr-1.png",
"onTap": (item) {},
},
{
"id": 3,
"photo":
"https://i.ibb.co/HgBhPdG/haidong-liang-hc-YPu-Ek-X5-Bc-unsplash-1-1.png",
"onTap": (item) {},
}
];
return SizedBox(
height: 120.0,
child: ListView.builder(
itemCount: items.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
var item = items[index];
return Container(
height: 100.0,
width: MediaQuery.of(context).size.width * 0.7,
margin: const EdgeInsets.only(right: 16.0),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
item["photo"],
),
fit: BoxFit.cover,
),
borderRadius: const BorderRadius.all(
Radius.circular(
16.0,
),
),
),
);
},
),
);
},
),
const SizedBox(
height: 20.0,
),
Text(
'Top Seller',
style: TextStyle(
fontSize: 25, fontFamily: 'KanitEB', color: Color(0xff19DE21)),
),
const SizedBox(
height: 20.0,
),
SizedBox(
height: 140.0,
child: ListView.builder(
itemCount: 10,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Container(
width: 140,
margin: const EdgeInsets.only(right: 10.0),
decoration: BoxDecoration(
image: const DecorationImage(
image: NetworkImage(
"https://i.ibb.co/60QTbgs/bereczki-domokos-qki-Nciu69t-Y-unsplash-1.png",
),
fit: BoxFit.cover,
),
borderRadius: const BorderRadius.all(
Radius.circular(16.0),
),
color: Colors.blue[400],
),
child: Stack(
children: [
Container(
padding: const EdgeInsets.all(6.0),
margin: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.green[800],
borderRadius: const BorderRadius.all(
Radius.circular(
12.0,
),
),
),
child: const Text(
"Top",
style: TextStyle(
color: Colors.white,
fontSize: 8.0,
),
),
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
padding: const EdgeInsets.all(12.0),
decoration: const BoxDecoration(
color: Colors.black38,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(16.0),
bottomRight: Radius.circular(16.0),
),
),
child: const Text(
"Rocket Bunny Body Kits",
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11.0,
color: Colors.white,
),
),
),
),
],
),
);
},
),
),
const SizedBox(
height: 40.0,
),
Text(
'Recomended',
style: TextStyle(
fontSize: 25, fontFamily: 'KanitEB', color: Color(0xff19DE21)),
),
const SizedBox(
height: 20.0,
),
SizedBox(
height: 140.0,
child: ListView.builder(
itemCount: 10,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Container(
width: 140,
margin: const EdgeInsets.only(right: 10.0),
decoration: BoxDecoration(
image: const DecorationImage(
image: NetworkImage(
"https://i.ibb.co/5xh0jrf/istrfry-marcus-9m-QHr1-Ws-EK0-unsplash-1.png",
),
fit: BoxFit.cover,
),
borderRadius: const BorderRadius.all(
Radius.circular(16.0),
),
color: Colors.blue[400],
),
child: Stack(
children: [
Container(
padding: const EdgeInsets.all(6.0),
margin: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.green[800],
borderRadius: const BorderRadius.all(
Radius.circular(
12.0,
),
),
),
child: const Text(
"Promo",
style: TextStyle(
color: Colors.white,
fontSize: 8.0,
),
),
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
padding: const EdgeInsets.all(12.0),
decoration: const BoxDecoration(
color: Colors.black38,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(16.0),
bottomRight: Radius.circular(16.0),
),
),
child: const Text(
"Rocket Bunny Body Kits - Nissan GTR 35R 2018 PnP (Build In)",
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11.0,
color: Colors.white,
),
),
),
),
],
),
);
},
),
),
]),
)));
}
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/home
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/home/controllers/home_controller.dart
|
import 'package:get/get.dart';
class HomeController extends GetxController {
//TODO: Implement HomeController
final count = 0.obs;
@override
void onInit() {
super.onInit();
}
@override
void onReady() {
super.onReady();
}
@override
void onClose() {
super.onClose();
}
void increment() => count.value++;
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/home
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/home/bindings/home_binding.dart
|
import 'package:get/get.dart';
import '../controllers/home_controller.dart';
class HomeBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut<HomeController>(
() => HomeController(),
);
}
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/register
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/register/views/register_view.dart
|
import 'package:car_enthusiast/app/modules/Login/views/login_view.dart';
import 'package:car_enthusiast/app/modules/home/views/home_view.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/register_controller.dart';
class RegisterView extends GetView<RegisterController> {
final usernameController = TextEditingController();
final emailController = TextEditingController();
final passwordController = TextEditingController();
final phonenumberController = TextEditingController();
@override
Widget build(BuildContext context) {
FirebaseFirestore firestore = FirebaseFirestore.instance;
CollectionReference users = firestore.collection('users');
return Scaffold(
body: Stack(
children: [
Container(
height: 1000,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/bg1.png'),
fit: BoxFit.cover,
opacity: 10,
),
),
),
const SizedBox(
height: 20.0,
),
Container(
child: ListView(
children: <Widget>[
const SizedBox(
height: 80.0,
),
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Car Enthusiast",
style: TextStyle(
fontSize: 40.0,
fontFamily: 'KanitEB',
color: Colors.white,
fontWeight: FontWeight.bold),
),
Text(
" .",
style: TextStyle(
fontSize: 40.0,
fontFamily: 'KanitEB',
color: Colors.green,
fontWeight: FontWeight.bold),
),
],
),
),
Center(
child: Text(
"Sign Up",
style: TextStyle(
fontSize: 40.0,
fontFamily: 'KanitEB',
color: Color(0xff19DE21),
),
),
),
const SizedBox(
height: 20.0,
),
// Pading agar text dipersempit secara simetris kiri dan kanan sejauh 35px horizontal
Padding(
padding: const EdgeInsets.symmetric(horizontal: 35.0),
child: TextFormField(
controller: usernameController,
decoration: InputDecoration(
floatingLabelBehavior: FloatingLabelBehavior.never,
fillColor: Color.fromARGB(71, 255, 255, 255),
filled: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(35),
borderSide: const BorderSide(
width: 0, style: BorderStyle.none)),
// labelText: 'Masukkan Username',
hintText: 'Username',
hintStyle: TextStyle(
fontFamily: 'Kanit',
color: Color.fromARGB(173, 255, 255, 255),
),
labelStyle: TextStyle(
color: Colors.blueGrey,
),
),
onChanged: (value) {},
),
),
const SizedBox(
height: 20.0,
),
// Pading agar text dipersempit secara simetris kiri dan kanan sejauh 35px horizontal
Padding(
padding: const EdgeInsets.symmetric(horizontal: 35.0),
child: TextFormField(
controller: phonenumberController,
decoration: InputDecoration(
floatingLabelBehavior: FloatingLabelBehavior.never,
fillColor: Color.fromARGB(71, 255, 255, 255),
filled: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(35),
borderSide: const BorderSide(
width: 0, style: BorderStyle.none)),
// labelText: 'Masukkan Username',
hintText: 'Phone Number',
hintStyle: TextStyle(
fontFamily: 'Kanit',
color: Color.fromARGB(173, 255, 255, 255),
),
labelStyle: TextStyle(
color: Colors.blueGrey,
),
),
onChanged: (value) {},
),
),
const SizedBox(
height: 20.0,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 35.0),
child: TextFormField(
controller: emailController,
decoration: InputDecoration(
floatingLabelBehavior: FloatingLabelBehavior.never,
fillColor: Color.fromARGB(71, 255, 255, 255),
filled: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(35),
borderSide: const BorderSide(
width: 0, style: BorderStyle.none)),
// labelText: 'Masukkan Email',
hintText: 'Email',
hintStyle: TextStyle(
fontFamily: 'Kanit',
color: Color.fromARGB(173, 255, 255, 255),
),
labelStyle: TextStyle(
color: Colors.blueGrey,
),
),
onChanged: (value) {},
),
),
const SizedBox(
height: 20.0,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 35.0),
child: Container(
child: TextFormField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(
floatingLabelBehavior: FloatingLabelBehavior.never,
fillColor: Color.fromARGB(71, 255, 255, 255),
filled: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(35),
borderSide: const BorderSide(
width: 0, style: BorderStyle.none)),
labelText: 'Password',
labelStyle: TextStyle(
color: Color.fromARGB(173, 255, 255, 255),
),
)),
),
),
const SizedBox(
height: 20.0,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 40.0),
child: ElevatedButton(
onPressed: () {
users.add({
'username': usernameController.text,
'phone': int.tryParse(phonenumberController.text) ?? 0
});
usernameController.text = '';
phonenumberController.text = '';
FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: emailController.text,
password: passwordController.text)
.then((value) {
FirebaseFirestore.instance
.collection('users')
.doc(value.user!.uid)
.set({"email": value.user!.email});
Get.to(() => convexbottombar(),
transition: Transition.zoom,
duration: Duration(seconds: 1));
}).onError((error, stackTrace) {
print("Error ${error.toString()}");
});
},
child: Container(
height: 55,
child: Center(
child: Text(
'Create Account',
style: TextStyle(fontFamily: 'KanitEB', fontSize: 18),
),
),
),
style: ElevatedButton.styleFrom(
primary: Color(0xff19DE21),
)),
),
const SizedBox(
height: 20.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Text(
'Have an Account? ',
style: TextStyle(
color: Colors.white,
),
),
),
GestureDetector(
onTap: () {
Get.to(() => LoginView(),
transition: Transition.zoom,
duration: Duration(seconds: 1));
},
child: Center(
child: Text(
'Login',
style: TextStyle(
color: Color(0xff19DE21),
),
),
),
),
],
)
],
)),
],
),
);
}
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/register
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/register/controllers/register_controller.dart
|
import 'package:get/get.dart';
class RegisterController extends GetxController {
//TODO: Implement RegisterController
final count = 0.obs;
@override
void onInit() {
super.onInit();
}
@override
void onReady() {
super.onReady();
}
@override
void onClose() {
super.onClose();
}
void increment() => count.value++;
}
| 0
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/register
|
mirrored_repositories/Car-Enthusiast/lib/app/modules/register/bindings/register_binding.dart
|
import 'package:get/get.dart';
import '../controllers/register_controller.dart';
class RegisterBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut<RegisterController>(
() => RegisterController(),
);
}
}
| 0
|
mirrored_repositories/Car-Enthusiast
|
mirrored_repositories/Car-Enthusiast/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:car_enthusiast/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-BabyStepsQuiz
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/routeGenerator.dart
|
import 'package:flutter/material.dart';
import 'package:quiz_app/ui/Transitions.dart';
import 'package:quiz_app/ui/screens/SplashScreen.dart';
import 'package:quiz_app/ui/screens/IntroScreen.dart';
import 'package:quiz_app/ui/screens/HomeScreen.dart';
import 'package:quiz_app/ui/screens/ProgressScreen.dart';
import 'package:quiz_app/ui/screens/AboutScreen.dart';
import 'package:quiz_app/ui/screens/CategoryMenuScreen.dart';
import 'package:quiz_app/ui/screens/CategoryScreen.dart';
import 'package:quiz_app/ui/screens/ResultScreen.dart';
class RouteGenerator {
static Route<dynamic> generateRoute(RouteSettings settings) {
final args = settings.arguments;
switch (settings.name) {
case '/Splash':
return FadeRoute(page: SplashScreen());
case '/Intro':
return FadeRoute(page: IntroScreen());
case '/Home':
return ScaleRoute(page: HomeScreen());
case '/MyProgress':
return FadeRoute(page: ProgressScreen());
case '/About':
return FadeRoute(page: AboutScreen());
case '/Menu':
return FadeRoute(page: CategoryMenuScreen());
case '/Category':
return SizeRoute(page: CategoryScreen(category: args));
case '/Result':
return ScaleRoute(page: ResultScreen(correct: args));
default:
return _errorRoute();
}
}
static Route<dynamic> _errorRoute() {
return MaterialPageRoute(builder: (_) {
return Scaffold(
appBar: AppBar(
title: Text('Error'),
),
body: Center(
child: Text('ERROR'),
),
);
});
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:quiz_app/routeGenerator.dart';
void main() {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
return runApp(QuizApp());
}
class QuizApp extends StatefulWidget {
@override
_QuizAppState createState() => _QuizAppState();
}
class _QuizAppState extends State<QuizApp> {
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
fontFamily: 'Blad',
),
title: 'Baby Steps Quiz',
// Initially display FirstPage
initialRoute: '/Splash',
onGenerateRoute: RouteGenerator.generateRoute,
debugShowCheckedModeBanner: false,
);
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/models/Categories.dart
|
enum Categories {
Animal,
Food,
Transportation,
Job,
Flag,
Weather,
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/models/Category.dart
|
import 'package:quiz_app/models/Quiz.dart';
class Category {
Category(this.name, this.question, List<Quiz> others) {
others.shuffle();
quizs = others;
}
String question;
String name;
List<Quiz> quizs;
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/models/CurrentCategory.dart
|
import 'package:quiz_app/models/Category.dart';
import 'package:quiz_app/ui/widgets/Progress.dart';
class CurrentCategory{
CurrentCategory(this.category, this.current, this.progress);
final int current;
final Category category;
final Progress progress;
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/models/Quiz.dart
|
class Quiz {
Quiz(this.correct, List<String> others, this.image, [this.secondImage]) {
others = List.from(others);
others.remove(correct);
others = others.sublist(0, 3);
others.add(correct);
others.shuffle();
others.shuffle();
candidates = others;
}
String correct;
String image;
String secondImage;
List<String> candidates;
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/strings/Strings.dart
|
import 'package:quiz_app/models/Category.dart';
import 'package:quiz_app/models/Quiz.dart';
class Strings {
Strings._();
static String categoryMenu ="Categories";
static String correct = "Correct";
static String wrong = "Wrong";
static String next = "Next";
static String result = "Result";
static String answer = "Answer";
static String win = "Good Job all correct !";
static String loose = "Good luck next time !";
static String playAgain = "Play Again";
static const List<String> animals = [
'Cow',
'Dog',
'Duck',
'Elephant',
'Bull',
'Giraffe',
'Lion',
'Monkey',
'Mouse',
'Tiger'
];
static const List<String> weathers = [
'Cloud',
'Cloudy',
'Lightning',
'Moon',
'Rain',
'Rainbow',
'Rainy',
'Snow',
'Snowy',
'Sun'
];
static const List<String> foods = [
'Apple',
'Bread',
'Cheese',
'Donut',
'Egg',
'Fries',
'Grapes',
'Mushroom',
'Pizza',
'Steak'
];
static const List<String> flags = [
'Belgium',
'France',
'Germany',
'Iceland',
'Ireland',
'Italy',
'Japan',
'Netherlands',
'Russia',
'Sweden'
];
static const List<String> transportations = [
'Airplane',
'Ambulance',
'Boat',
'Car',
'Helicopter',
'Metro',
'Rocket',
'Scooter',
'Ship',
'Truck'
];
static const List<String> jobs = [
'Artist',
'Astronaut',
'Cook',
'Doctor',
'Farmer',
'Firefighter',
'Judge',
'Pilot',
'Scientist',
'Singer'
];
static getCategory(String name) {
Category category;
List<Quiz> quizs = List<Quiz>();
switch (name) {
case 'animal':
for (var i = 0; i < animals.length; i++) {
quizs.add(Quiz(animals[i], animals,
"assets/images/animals/" + animals[i] + ".svg"));
}
category =
new Category('Animals', 'What is this animal called ?', quizs);
return category;
case 'weather':
for (var i = 0; i < weathers.length; i++) {
quizs.add(Quiz(weathers[i], weathers,
"assets/images/weathers/" + weathers[i] + ".svg"));
}
category = new Category('Weathers', 'What is this called ?', quizs);
return category;
case 'food':
for (var i = 0; i < foods.length; i++) {
quizs.add(Quiz(
foods[i], foods, "assets/images/foods/" + foods[i] + ".svg"));
}
category = new Category('Foods', 'What is this food called ?', quizs);
return category;
case 'flag':
for (var i = 0; i < flags.length; i++) {
quizs.add(Quiz(
flags[i], flags, "assets/images/flags/" + flags[i] + ".svg"));
}
category =
new Category('Countries', 'What is this country Named ?', quizs);
return category;
case 'transportation':
for (var i = 0; i < transportations.length; i++) {
quizs.add(Quiz(transportations[i], transportations,
"assets/images/transportations/" + transportations[i] + ".svg"));
}
category = new Category(
'Transportations', 'What is this transportation called ?', quizs);
return category;
case 'job':
for (var i = 0; i < jobs.length; i++) {
quizs.add(Quiz(
jobs[i],
jobs,
"assets/images/jobs/male/" + jobs[i] + "_male.svg",
"assets/images/jobs/female/" + jobs[i] + "_female.svg"));
}
category = new Category('Jobs', 'What is this job called ?', quizs);
return category;
}
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/strings/StringsLoader.dart
|
import 'package:quiz_app/strings/Strings.dart';
import 'package:quiz_app/strings/StringsFR.dart';
import 'package:quiz_app/strings/StringsES.dart';
import 'package:quiz_app/strings/StringsAR.dart';
class StringsLoader {
String lang ;
StringsLoader(String lang){
this.lang = lang;
}
loadWinLoose(bool nx){
switch (lang) {
case "":
switch (nx) {
case true:
return(Strings.win);
case false:
return(Strings.loose);
}
break;
case "FR":
switch (nx) {
case true:
return(StringsFR.win);
case false:
return(StringsFR.loose);
}
break;
case "ES":
switch (nx) {
case true:
return(StringsES.win);
case false:
return(StringsES.loose);
}
break;
case "AR":
switch (nx) {
case true:
return(StringsAR.win);
case false:
return(StringsAR.loose);
}
break;
}
}
loadNext(bool nx){
switch (lang) {
case "":
switch (nx) {
case true:
return(Strings.next);
case false:
return(Strings.result);
}
break;
case "FR":
switch (nx) {
case true:
return(StringsFR.next);
case false:
return(StringsFR.result);
}
break;
case "ES":
switch (nx) {
case true:
return(StringsES.next);
case false:
return(StringsES.result);
}
break;
case "AR":
switch (nx) {
case true:
return(StringsAR.next);
case false:
return(StringsAR.result);
}
break;
}
}
loadResult(bool answer){
switch (lang) {
case "":
switch (answer) {
case true:
return(Strings.correct);
case false:
return(Strings.wrong);
}
break;
case "FR":
switch (answer) {
case true:
return(StringsFR.correct);
case false:
return(StringsFR.wrong);
}
break;
case "ES":
switch (answer) {
case true:
return(StringsES.correct);
case false:
return(StringsES.wrong);
}
break;
case "AR":
switch (answer) {
case true:
return(StringsAR.correct);
case false:
return(StringsAR.wrong);
}
break;
}
}
loadPlayAgain(){
switch (lang) {
case "":
return(Strings.playAgain);
break;
case "FR":
return(StringsFR.playAgain);
break;
case "ES":
return(StringsES.playAgain);
break;
case "AR":
return(StringsAR.playAgain);
break;
}
}
loadCategoryMenu(){
switch (lang) {
case "":
return(Strings.categoryMenu);
break;
case "FR":
return(StringsFR.categoryMenu);
break;
case "ES":
return(StringsES.categoryMenu);
break;
case "AR":
return(StringsAR.categoryMenu);
break;
}
}
loadAnswer(){
switch (lang) {
case "":
return(Strings.answer);
break;
case "FR":
return(StringsFR.answer);
break;
case "ES":
return(StringsES.answer);
break;
case "AR":
return(StringsAR.answer);
break;
}
}
loadCategories(String name) {
switch (lang) {
case "":
return(Strings.getCategory(name));
break;
case "FR":
return(StringsFR.getCategory(name));
break;
case "ES":
return(StringsES.getCategory(name));
break;
case "AR":
return(StringsAR.getCategory(name));
break;
}
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/strings/SVGs.dart
|
const List<String> animalsSVG = [
'Cow',
'Dog',
'Duck',
'Elephant',
'Bull',
'Giraffe',
'Lion',
'Monkey',
'Mouse',
'Tiger'
];
const List<String> weathersSVG = [
'Cloud',
'Cloudy',
'Lightning',
'Moon',
'Rain',
'Rainbow',
'Rainy',
'Snow',
'Snowy',
'Sun'
];
const List<String> foodsSVG = [
'Apple',
'Bread',
'Cheese',
'Donut',
'Egg',
'Fries',
'Grapes',
'Mushroom',
'Pizza',
'Steak'
];
const List<String> flagsSVG = [
'Belgium',
'France',
'Germany',
'Iceland',
'Ireland',
'Italy',
'Japan',
'Netherlands',
'Russia',
'Sweden'
];
const List<String> transportationsSVG = [
'Airplane',
'Ambulance',
'Boat',
'Car',
'Helicopter',
'Metro',
'Rocket',
'Scooter',
'Ship',
'Truck'
];
const List<String> jobsSVG = [
'Artist',
'Astronaut',
'Cook',
'Doctor',
'Farmer',
'Firefighter',
'Judge',
'Pilot',
'Scientist',
'Singer'
];
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/strings/StringsFR.dart
|
import 'package:quiz_app/models/Category.dart';
import 'package:quiz_app/models/Quiz.dart';
import 'package:quiz_app/strings/SVGs.dart';
class StringsFR {
StringsFR._();
static String categoryMenu ="Catégories";
static String correct = "Correct";
static String wrong = "Faux";
static String next = "Suivant";
static String result = "Résultat";
static String answer = "Répondre";
static String win = "Bon travail tout est correct!";
static String loose = "Bonne chance la prochaine fois!";
static String playAgain = "Rejouer";
static const List<String> animals = [
'Vache',
'Chien',
'Canard',
'Eléphant',
'Taureau',
'Girafe',
'Lion',
'Singe',
'Souris',
'Tigre'
];
static const List<String> weathers = [
'Nuage',
'Nuageux',
'Foudre',
'Lune',
'Pluie',
'Arc en ciel',
'Pluvieux',
'Neige',
'Neigeux',
'Soleil'
];
static const List<String> foods = [
'Pomme',
'Pain',
'Fromage',
'Donut',
'Oeuf',
'Frites',
'Raisins',
'Champignon',
'Pizza',
'Steak'
];
static const List<String> flags = [
'Belgique',
'France',
'Allemagne',
'Islande',
'Irlande',
'Italie',
'Japon',
'Pays-Bas',
'Russie',
'Suède'
];
static const List<String> transportations = [
'Avion',
'Ambulance',
'Bateau',
'Voiture',
'Hélicoptère',
'Métro',
'Fusée',
'Scooter',
'Navire',
'Camion'
];
static const List<String> jobs = [
'Artiste',
'Astronaute',
'Cuisinier',
'Médecin',
'Fermier',
'Pompier',
'Juge',
'Pilote',
'Scientifique',
'Chanteur'
];
static getCategory(String name) {
Category category;
List<Quiz> quizs = List<Quiz>();
switch (name) {
case 'animal':
for (var i = 0; i < animals.length; i++) {
quizs.add(Quiz(animals[i], animals,
"assets/images/animals/" + animalsSVG[i] + ".svg"));
}
category =
new Category('Animaux', 'Comment s\'appelle cet animal?', quizs);
return category;
case 'weather':
for (var i = 0; i < weathers.length; i++) {
quizs.add(Quiz(weathers[i], weathers,
"assets/images/weathers/" + weathersSVG[i] + ".svg"));
}
category = new Category('Météo', 'Qu\'est-ce que c\'est ?', quizs);
return category;
case 'food':
for (var i = 0; i < foods.length; i++) {
quizs.add(Quiz(
foods[i], foods, "assets/images/foods/" + foodsSVG[i] + ".svg"));
}
category = new Category('Nourriture', 'Comment s\'appelle cette nourriture?', quizs);
return category;
case 'flag':
for (var i = 0; i < flags.length; i++) {
quizs.add(Quiz(
flags[i], flags, "assets/images/flags/" + flagsSVG[i] + ".svg"));
}
category =
new Category('Pays', 'Quel est ce pays?', quizs);
return category;
case 'transportation':
for (var i = 0; i < transportations.length; i++) {
quizs.add(Quiz(transportations[i], transportations,
"assets/images/transportations/" + transportationsSVG[i] + ".svg"));
}
category = new Category(
'Transports', 'Comment s\'appelle ce transport?', quizs);
return category;
case 'job':
for (var i = 0; i < jobs.length; i++) {
quizs.add(Quiz(
jobs[i],
jobs,
"assets/images/jobs/male/" + jobsSVG[i] + "_male.svg",
"assets/images/jobs/female/" + jobsSVG[i] + "_female.svg"));
}
category = new Category('Métiers', 'Comment s\'appelle ce travail?', quizs);
return category;
}
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/strings/StringsES.dart
|
import 'package:quiz_app/models/Category.dart';
import 'package:quiz_app/models/Quiz.dart';
import 'package:quiz_app/strings/SVGs.dart';
class StringsES {
StringsES._();
static String categoryMenu ="Categorías";
static String correct = "Correcto";
static String wrong = "Incorrecto";
static String next = "Siguiente";
static String result = "Resultado";
static String answer = "Responder";
static String win = "Buen trabajo todo correcto!";
static String loose = "Buena suerte la próxima vez !";
static String playAgain = "Juega de nuevo";
static const List<String> animals = [
'Vaca',
'Perro',
'Pato',
'Elefante',
'Toro',
'Jirafa',
'León',
'Mono',
'Ratón',
'Tigre'
];
static const List<String> weathers = [
'Nube',
'Nublado',
'Relámpago',
'Luna',
'Lluvia',
'Arco iris',
'Lluvioso',
'Nieve',
'Nevado',
'Dom'
];
static const List<String> foods = [
'Manzana',
'Un pan',
'Queso',
'Rosquilla',
'Huevo',
'Papas fritas',
'Uvas',
'Seta',
'Pizza',
'Filete'
];
static const List<String> flags = [
'Bélgica',
'Francia',
'Alemania',
'Islandia',
'Irlanda',
'Italia',
'Japón',
'Países Bajos',
'Rusia',
'Suecia'
];
static const List<String> transportations = [
'Avión',
'Ambulancia',
'Bote',
'Coche',
'Helicóptero',
'Metro',
'Cohete',
'Scooter',
'Enviar',
'Camión'
];
static const List<String> jobs = [
'Artista',
'Astronauta',
'Cocinar',
'Médico',
'Granjero',
'Bombero',
'Juez',
'Piloto',
'Científico',
'Cantante'
];
static getCategory(String name) {
Category category;
List<Quiz> quizs = List<Quiz>();
switch (name) {
case 'animal':
for (var i = 0; i < animals.length; i++) {
quizs.add(Quiz(animals[i], animals,
"assets/images/animals/" + animalsSVG[i] + ".svg"));
}
category =
new Category('Animales', '¿Cómo se llama este animal?', quizs);
return category;
case 'weather':
for (var i = 0; i < weathers.length; i++) {
quizs.add(Quiz(weathers[i], weathers,
"assets/images/weathers/" + weathersSVG[i] + ".svg"));
}
category = new Category('Climas', '¿Como se llama esto ?', quizs);
return category;
case 'food':
for (var i = 0; i < foods.length; i++) {
quizs.add(Quiz(
foods[i], foods, "assets/images/foods/" + foodsSVG[i] + ".svg"));
}
category = new Category('Alimentos', '¿Cómo se llama esta comida?', quizs);
return category;
case 'flag':
for (var i = 0; i < flags.length; i++) {
quizs.add(Quiz(
flags[i], flags, "assets/images/flags/" + flagsSVG[i] + ".svg"));
}
category =
new Category('Países', '¿Cómo se llama este país?', quizs);
return category;
case 'transportation':
for (var i = 0; i < transportations.length; i++) {
quizs.add(Quiz(transportations[i], transportations,
"assets/images/transportations/" + transportationsSVG[i] + ".svg"));
}
category = new Category(
'Transportes', '¿Cómo se llama este transporte?', quizs);
return category;
case 'job':
for (var i = 0; i < jobs.length; i++) {
quizs.add(Quiz(
jobs[i],
jobs,
"assets/images/jobs/male/" + jobsSVG[i] + "_male.svg",
"assets/images/jobs/female/" + jobsSVG[i] + "_female.svg"));
}
category = new Category('Trabajos', '¿Cómo se llama este trabajo?', quizs);
return category;
}
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/strings/StringsAR.dart
|
import 'package:quiz_app/models/Category.dart';
import 'package:quiz_app/models/Quiz.dart';
import 'package:quiz_app/strings/SVGs.dart';
class StringsAR {
StringsAR._();
static String categoryMenu ="فئاة";
static String correct = "صحيح";
static String wrong = "خاطئ";
static String next = "التالي";
static String result = "نتيجة";
static String answer = "أجب";
static String win = "! عمل الجيد الكل صحيح";
static String loose = "! حظ سعيد في المرة القادمة";
static String playAgain = "العب مرة أخرى";
static const List<String> animals = [
'بقرة',
'كلب',
'بطة',
'فيل',
'ثور',
'زرافة',
'أسد',
'قرد',
'فأر',
'نمر'
];
static const List<String> weathers = [
'غيم',
'غائم',
'برق',
'القمر',
'تمطر',
'قوس قزح',
'مطر',
'ثلج',
'مثلج',
'شمس'
];
static const List<String> foods = [
'تفاحة',
'خبز',
'جبن',
'كعكة',
'بيضة',
'بطاطا',
'عنب',
'فطر',
'بيتزا',
'لحم'
];
static const List<String> flags = [
'بلجيكا',
'فرنسا',
'ألمانيا',
'أيسلندا',
"أيرلندا",
'إيطاليا',
'اليابان',
'هولندا',
'روسيا',
'السويد'
];
static const List<String> transportations = [
'طائرة',
'سياره اسعاف',
'قارب',
'سيارة',
'طائرة عامودية',
'قطار',
'صاروخ',
'دراجة بخارية ',
'سفينة',
'شاحنة'
];
static const List<String> jobs = [
'فنان',
'رائد فضاء',
'طباخ',
'طبيب',
'فلاح',
'إطفائي',
'قاضي',
'قائد الطائرة',
'عالم',
'مغني'
];
static getCategory(String name) {
Category category;
List<Quiz> quizs = List<Quiz>();
switch (name) {
case 'animal':
for (var i = 0; i < animals.length; i++) {
quizs.add(Quiz(animals[i], animals,
"assets/images/animals/" + animalsSVG[i] + ".svg"));
}
category =
new Category('الحيوانات', 'ماذا يسمى هذا الحيوان؟', quizs);
return category;
case 'weather':
for (var i = 0; i < weathers.length; i++) {
quizs.add(Quiz(weathers[i], weathers,
"assets/images/weathers/" + weathersSVG[i] + ".svg"));
}
category = new Category('طقس', 'ماذا يدعى ؟', quizs);
return category;
case 'food':
for (var i = 0; i < foods.length; i++) {
quizs.add(Quiz(
foods[i], foods, "assets/images/foods/" + foodsSVG[i] + ".svg"));
}
category = new Category('طعام', 'ماذا يسمى هذا الطعام؟', quizs);
return category;
case 'flag':
for (var i = 0; i < flags.length; i++) {
quizs.add(Quiz(
flags[i], flags, "assets/images/flags/" + flagsSVG[i] + ".svg"));
}
category =
new Category('بلدان', 'ما اسم هذا البلد؟', quizs);
return category;
case 'transportation':
for (var i = 0; i < transportations.length; i++) {
quizs.add(Quiz(transportations[i], transportations,
"assets/images/transportations/" + transportationsSVG[i] + ".svg"));
}
category = new Category(
'نقل', 'ماذا يسمى هذا النقل؟', quizs);
return category;
case 'job':
for (var i = 0; i < jobs.length; i++) {
quizs.add(Quiz(
jobs[i],
jobs,
"assets/images/jobs/male/" + jobsSVG[i] + "_male.svg",
"assets/images/jobs/female/" + jobsSVG[i] + "_female.svg"));
}
category = new Category('وظائف', 'ماذا يسمى هذا العمل؟', quizs);
return category;
}
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/Transitions.dart
|
import 'package:flutter/material.dart';
class ScaleRoute extends PageRouteBuilder {
final Widget page;
ScaleRoute({this.page})
: super(
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
page,
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
ScaleTransition(
scale: Tween<double>(
begin: 0.0,
end: 1.0,
).animate(
CurvedAnimation(
parent: animation,
curve: Curves.fastOutSlowIn,
),
),
child: child,
),
);
}
class SizeRoute extends PageRouteBuilder {
final Widget page;
SizeRoute({this.page})
: super(
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
page,
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
Align(
child: SizeTransition(
sizeFactor: animation,
child: child,
),
),
);
}
class FadeRoute extends PageRouteBuilder {
final Widget page;
FadeRoute({this.page})
: super(
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
page,
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
FadeTransition(
opacity: animation,
child: child,
),
);
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/widgets/EmptyAppBar.dart
|
import 'package:flutter/material.dart';
class EmptyAppBar extends StatelessWidget implements PreferredSizeWidget {
@override
Widget build(BuildContext context) {
return Container();
}
@override
Size get preferredSize => Size(0.0, 0.0);
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/widgets/Progress.dart
|
import 'package:flutter/material.dart';
class Progress extends StatelessWidget {
List<ProgressKind> progress;
Progress({
Key key,
this.progress,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: progress.map((kind) {
return Text(_convertToStringFromProgressKind(kind));
}).toList(),
),
);
}
String _convertToStringFromProgressKind(ProgressKind kind) {
switch (kind) {
case ProgressKind.correct:
return '⭕️️️';
case ProgressKind.incorrect:
return '❌';
case ProgressKind.notYet:
return '▫️';
case ProgressKind.current:
return '🔷';
}
assert(false, 'invalid kind: $kind');
return '';
}
}
enum ProgressKind {
correct,
incorrect,
current,
notYet,
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/widgets
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/widgets/chooser/ArcChooser.dart
|
import 'dart:math';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:quiz_app/ui/widgets/chooser/ChooserPainter.dart';
class ArcChooser extends StatefulWidget {
ArcSelectedCallback arcSelectedCallback;
List<String> arcNames;
ArcChooser({
Key key,
this.arcNames,
}) : super(key: key);
@override
State<StatefulWidget> createState() {
return ChooserState(arcSelectedCallback,this.arcNames);
}
}
class ChooserState extends State<ArcChooser>
with SingleTickerProviderStateMixin {
var slideValue = 200;
Offset centerPoint;
double userAngle = 0.0;
double startAngle;
static double center = 280.0;
static double centerInRadians = degreeToRadians(center);
static double angle = 45.0;
static double angleInRadians = degreeToRadians(angle);
static double angleInRadiansByTwo = angleInRadians / 2;
static double centerItemAngle = degreeToRadians(center - (angle / 2));
List<ArcItem> arcItems;
List<String> arcNames;
AnimationController animation;
double animationStart;
double animationEnd = 0.0;
int currentPosition = 0;
Offset startingPoint;
Offset endingPoint;
ArcSelectedCallback arcSelectedCallback;
ChooserState(this.arcSelectedCallback,this.arcNames);
static double degreeToRadians(double degree) {
return degree * (pi / 180);
}
static double radianToDegrees(double radian) {
return radian * (180 / pi);
}
@override
void initState() {
arcNames = this.arcNames;
arcItems = List<ArcItem>();
arcItems.add(ArcItem(arcNames[0], [Color(0xFFF9D976), Color(0xfff39f86)],
angleInRadiansByTwo + userAngle));
arcItems.add(ArcItem(arcNames[1], [Color(0xFF21e1fa), Color(0xff3bb8fd)],
angleInRadiansByTwo + userAngle + (angleInRadians)));
arcItems.add(ArcItem(arcNames[2], [Color(0xFF3ee98a), Color(0xFF41f7c7)],
angleInRadiansByTwo + userAngle + (2 * angleInRadians)));
arcItems.add(ArcItem(arcNames[3], [Color(0xFFfe0944), Color(0xFFfeae96)],
angleInRadiansByTwo + userAngle + (3 * angleInRadians)));
arcItems.add(ArcItem(arcNames[0], [Color(0xFFF9D976), Color(0xfff39f86)],
angleInRadiansByTwo + userAngle + (4 * angleInRadians)));
arcItems.add(ArcItem(arcNames[1], [Color(0xFF21e1fa), Color(0xff3bb8fd)],
angleInRadiansByTwo + userAngle + (5 * angleInRadians)));
arcItems.add(ArcItem(arcNames[2], [Color(0xFF3ee98a), Color(0xFF41f7c7)],
angleInRadiansByTwo + userAngle + (6 * angleInRadians)));
arcItems.add(ArcItem(arcNames[3], [Color(0xFFfe0944), Color(0xFFfeae96)],
angleInRadiansByTwo + userAngle + (7 * angleInRadians)));
animation = new AnimationController(
duration: const Duration(milliseconds: 200), vsync: this);
animation.addListener(() {
userAngle = lerpDouble(animationStart, animationEnd, animation.value);
setState(() {
for (int i = 0; i < arcItems.length; i++) {
arcItems[i].startAngle =
angleInRadiansByTwo + userAngle + (i * angleInRadians);
}
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
double centerX = MediaQuery.of(context).size.width / 2;
double centerY = MediaQuery.of(context).size.height * 1.5;
centerPoint = Offset(centerX, centerY);
return new GestureDetector(
// onTap: () {
// print('ChooserState.build ONTAP');
// animationStart = touchAngle;
// animationEnd = touchAngle + angleInRadians;
// animation.forward(from: 0.0);
// },
onPanStart: (DragStartDetails details) {
startingPoint = details.globalPosition;
var deltaX = centerPoint.dx - details.globalPosition.dx;
var deltaY = centerPoint.dy - details.globalPosition.dy;
startAngle = atan2(deltaY, deltaX);
},
onPanUpdate: (DragUpdateDetails details) {
endingPoint = details.globalPosition;
var deltaX = centerPoint.dx - details.globalPosition.dx;
var deltaY = centerPoint.dy - details.globalPosition.dy;
var freshAngle = atan2(deltaY, deltaX);
userAngle += freshAngle - startAngle;
setState(() {
for (int i = 0; i < arcItems.length; i++) {
arcItems[i].startAngle =
angleInRadiansByTwo + userAngle + (i * angleInRadians);
}
});
startAngle = freshAngle;
},
onPanEnd: (DragEndDetails details) {
//find top arc item with Magic!!
bool rightToLeft = startingPoint.dx < endingPoint.dx;
// Animate it from this values
animationStart = userAngle;
if (rightToLeft) {
animationEnd += angleInRadians;
currentPosition--;
if (currentPosition < 0) {
currentPosition = arcItems.length - 1;
}
} else {
animationEnd -= angleInRadians;
currentPosition++;
if (currentPosition >= arcItems.length) {
currentPosition = 0;
}
}
if (arcSelectedCallback != null) {
arcSelectedCallback(
currentPosition,
arcItems[(currentPosition >= (arcItems.length - 1))
? 0
: currentPosition + 1]);
}
animation.forward(from: 0.0);
},
child: CustomPaint(
size: Size(MediaQuery.of(context).size.width,
MediaQuery.of(context).size.width * 1 / 1.5),
painter: ChooserPainter(arcItems, angleInRadians),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/widgets
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/widgets/chooser/ChooserPainter.dart
|
import 'dart:math';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:quiz_app/ui/widgets/chooser/ArcChooser.dart';
typedef void ArcSelectedCallback(int position, ArcItem arcitem);
class ArcItem {
String text;
List<Color> colors;
double startAngle;
ArcItem(this.text, this.colors, this.startAngle);
}
// draw the arc and other stuff
class ChooserPainter extends CustomPainter {
//debugging Paint
final debugPaint = new Paint()
..color = Colors.red.withAlpha(100) //0xFFF9D976
..strokeWidth = 1.0
..style = PaintingStyle.stroke;
final linePaint = new Paint()
..color = Colors.black.withAlpha(65) //0xFFF9D976
..strokeWidth = 2.0
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.square;
final whitePaint = new Paint()
..color = Colors.deepPurpleAccent //0xFFF9D976
..strokeWidth = 1.0
..style = PaintingStyle.fill;
List<ArcItem> arcItems;
double angleInRadians;
double angleInRadiansByTwo;
double angleInRadians1;
double angleInRadians2;
double angleInRadians3;
double angleInRadians4;
ChooserPainter(List<ArcItem> arcItems, double angleInRadians) {
this.arcItems = arcItems;
this.angleInRadians = angleInRadians;
this.angleInRadiansByTwo = angleInRadians / 2;
angleInRadians1 = angleInRadians / 6;
angleInRadians2 = angleInRadians / 3;
angleInRadians3 = angleInRadians * 4 / 6;
angleInRadians4 = angleInRadians * 5 / 6;
}
@override
void paint(Canvas canvas, Size size) {
//common calc
double centerX = size.width / 2;
double centerY = size.height * 1.6;
Offset center = Offset(centerX, centerY);
double radius = sqrt((size.width * size.width) / 2);
// var mainRect = Rect.fromLTRB(0.0, 0.0, size.width, size.height);
// canvas.drawRect(mainRect, debugPaint);
//for white arc at bottom
double leftX = centerX - radius;
double topY = centerY - radius;
double rightX = centerX + radius;
double bottomY = centerY + radius;
//for items
double radiusItems = radius * 1.5;
double leftX2 = centerX - radiusItems;
double topY2 = centerY - radiusItems;
double rightX2 = centerX + radiusItems;
double bottomY2 = centerY + radiusItems;
//for shadow
double radiusShadow = radius * 1.13;
double leftX3 = centerX - radiusShadow;
double topY3 = centerY - radiusShadow;
double rightX3 = centerX + radiusShadow;
double bottomY3 = centerY + radiusShadow;
double radiusText = radius * 1.35;
double radius4 = radius * 1.12;
double radius5 = radius * 1.06;
var arcRect = Rect.fromLTRB(leftX2, topY2, rightX2, bottomY2);
var dummyRect = Rect.fromLTRB(0.0, 0.0, size.width, size.height);
canvas.clipRect(dummyRect, clipOp: ClipOp.intersect);
for (int i = 0; i < arcItems.length; i++) {
canvas.drawArc(
arcRect,
arcItems[i].startAngle,
angleInRadians,
true,
new Paint()
..style = PaintingStyle.fill
..shader = new LinearGradient(
colors: arcItems[i].colors,
).createShader(dummyRect));
//Draw text
TextSpan span = new TextSpan(
style: new TextStyle(
fontWeight: FontWeight.normal,
fontSize: 32.0,
fontFamily: 'Blad',
color: Colors.white),
text: arcItems[i].text);
TextPainter tp = new TextPainter(
text: span,
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
);
tp.layout();
//find additional angle to make text in center
double f = tp.width / 2;
double t = sqrt((radiusText * radiusText) + (f * f));
double additionalAngle = acos(
((t * t) + (radiusText * radiusText) - (f * f)) /
(2 * t * radiusText));
double tX = center.dx +
radiusText *
cos(arcItems[i].startAngle +
angleInRadiansByTwo -
additionalAngle); // - (tp.width/2);
double tY = center.dy +
radiusText *
sin(arcItems[i].startAngle +
angleInRadiansByTwo -
additionalAngle); // - (tp.height/2);
canvas.save();
canvas.translate(tX, tY);
// canvas.rotate(arcItems[i].startAngle + angleInRadiansByTwo);
canvas.rotate(arcItems[i].startAngle +
angleInRadians +
angleInRadians +
angleInRadiansByTwo);
tp.paint(canvas, new Offset(0.0, 0.0));
canvas.restore();
//big lines
canvas.drawLine(
new Offset(center.dx + radius4 * cos(arcItems[i].startAngle),
center.dy + radius4 * sin(arcItems[i].startAngle)),
center,
linePaint);
canvas.drawLine(
new Offset(
center.dx +
radius4 * cos(arcItems[i].startAngle + angleInRadiansByTwo),
center.dy +
radius4 * sin(arcItems[i].startAngle + angleInRadiansByTwo)),
center,
linePaint);
//small lines
canvas.drawLine(
new Offset(
center.dx +
radius5 * cos(arcItems[i].startAngle + angleInRadians1),
center.dy +
radius5 * sin(arcItems[i].startAngle + angleInRadians1)),
center,
linePaint);
canvas.drawLine(
new Offset(
center.dx +
radius5 * cos(arcItems[i].startAngle + angleInRadians2),
center.dy +
radius5 * sin(arcItems[i].startAngle + angleInRadians2)),
center,
linePaint);
canvas.drawLine(
new Offset(
center.dx +
radius5 * cos(arcItems[i].startAngle + angleInRadians3),
center.dy +
radius5 * sin(arcItems[i].startAngle + angleInRadians3)),
center,
linePaint);
canvas.drawLine(
new Offset(
center.dx +
radius5 * cos(arcItems[i].startAngle + angleInRadians4),
center.dy +
radius5 * sin(arcItems[i].startAngle + angleInRadians4)),
center,
linePaint);
}
//shadow
Path shadowPath = new Path();
shadowPath.addArc(
Rect.fromLTRB(leftX3, topY3, rightX3, bottomY3),
ChooserState.degreeToRadians(180.0),
ChooserState.degreeToRadians(180.0));
canvas.drawShadow(shadowPath, Colors.black, 18.0, true);
//bottom white arc
canvas.drawArc(
Rect.fromLTRB(leftX, topY, rightX, bottomY),
ChooserState.degreeToRadians(180.0),
ChooserState.degreeToRadians(180.0),
true,
whitePaint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/widgets
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/widgets/chooser/ChooserWidget.dart
|
import 'package:flutter/material.dart';
import 'package:quiz_app/ui/widgets/chooser/ArcChooser.dart';
import 'package:quiz_app/ui/widgets/chooser/ChooserPainter.dart';
class ChooserWidget extends StatefulWidget {
List<String> arcNames;
@override
State<StatefulWidget> createState() {
return _ChooserWidgetState(arcNames);
}
}
class _ChooserWidgetState extends State<ChooserWidget>
with TickerProviderStateMixin {
final PageController pageControl = new PageController(
initialPage: 2,
keepPage: false,
viewportFraction: 0.2,
);
_ChooserWidgetState(List<String> arcNames) {
this.arcNames = arcNames;
}
int slideValue = 200;
int lastAnimPosition = 2;
int answer = 2;
AnimationController animation;
List<String> arcNames;
Color startColor;
Color endColor;
@override
void initState() {
super.initState();
startColor = Color(0xFF21e1fa);
endColor = Color(0xff3bb8fd);
animation = new AnimationController(
value: 0.0,
lowerBound: 0.0,
upperBound: 400.0,
duration: const Duration(milliseconds: 800),
vsync: this,
)..addListener(() {
setState(() {
slideValue = animation.value.toInt();
double ratio;
if (slideValue <= 100) {
ratio = animation.value / 100;
startColor =
Color.lerp(Color(0xFFfe0944), Color(0xFFF9D976), ratio);
endColor =
Color.lerp(Color(0xFFfeae96), Color(0xfff39f86), ratio);
} else if (slideValue <= 200) {
ratio = (animation.value - 100) / 100;
startColor =
Color.lerp(Color(0xFFF9D976), Color(0xFF21e1fa), ratio);
endColor =
Color.lerp(Color(0xfff39f86), Color(0xff3bb8fd), ratio);
} else if (slideValue <= 300) {
ratio = (animation.value - 200) / 100;
startColor =
Color.lerp(Color(0xFF21e1fa), Color(0xFF3ee98a), ratio);
endColor =
Color.lerp(Color(0xff3bb8fd), Color(0xFF41f7c7), ratio);
} else if (slideValue <= 400) {
ratio = (animation.value - 300) / 100;
startColor =
Color.lerp(Color(0xFF3ee98a), Color(0xFFfe0944), ratio);
endColor =
Color.lerp(Color(0xFF41f7c7), Color(0xFFfeae96), ratio);
}
});
});
animation.animateTo(slideValue.toDouble());
}
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Container(
color: Colors.red,
width: size.width,
child:ArcChooser()
..arcNames = arcNames
..arcSelectedCallback = (int pos, ArcItem item) {
int animPosition = pos - 2;
if (animPosition > 3) {
animPosition = animPosition - 4;
}
if (animPosition < 0) {
animPosition = 4 + animPosition;
}
if (lastAnimPosition == 3 && animPosition == 0) {
animation.animateTo(4 * 100.0);
} else if (lastAnimPosition == 0 && animPosition == 3) {
animation.forward(from: 4 * 100.0);
animation.animateTo(animPosition * 100.0);
} else if (lastAnimPosition == 0 && animPosition == 1) {
animation.forward(from: 0.0);
animation.animateTo(animPosition * 100.0);
} else {
animation.animateTo(animPosition * 100.0);
}
lastAnimPosition = animPosition;
setState(() {
answer = lastAnimPosition;
});
},
);
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/screens/AboutScreen.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:url_launcher/url_launcher.dart';
class AboutScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
leading: new IconButton(
icon: new Icon(Icons.arrow_back, color: Colors.black),
onPressed: () => Navigator.of(context).pop(),
),
backgroundColor: Colors.white,
elevation: 0,
title: Text(
"About",
style: TextStyle(
color: Colors.black,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
centerTitle: true,
),
body: Container(
color: Colors.white,
height: size.height,
width: size.width,
padding: new EdgeInsets.all(10.0),
child: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Text("The purpose of this app is to help beginners understand basic, somewhat esential words of some languages like French, English, Arabic and Spanish.",
textAlign : TextAlign.left,
style: TextStyle(
color: Colors.black,
fontSize: 20,),
),
Divider(
indent: size.width * 0.2,
endIndent: size.width * 0.2,
color: Colors.black,
height: size.height * 0.04,
),
Row(
children: <Widget>[
Text("Credits",
textAlign : TextAlign.left,
style: TextStyle(
color: Colors.black,
fontSize: 24,
fontWeight: FontWeight.bold),
),Spacer(),
],
),
Divider(
indent: 0,
endIndent: 0,
color: Colors.transparent,
height: size.height * 0.02,
),
Container(
padding: new EdgeInsets.all(size.width * 0.02),
height: size.height * 0.14,
width: size.width * 0.9,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(99),
boxShadow: [
new BoxShadow(
color: Colors.grey,
offset: new Offset(1.0, 1.0),
blurRadius: 4.0,
spreadRadius: 0.0)
],
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Colors.orange,
Colors.orangeAccent,
Colors.yellow,
Colors.yellow[100],
],
),
),
child: Row(
children: <Widget>[
Container(
width: size.width * .2,
height: size.width * .2,
decoration: BoxDecoration(
color: Colors.black,
shape: BoxShape.circle,
image: new DecorationImage(
fit: BoxFit.fill,
image: new NetworkImage(
"https://avatars0.githubusercontent.com/u/44686277")
),
),
),
Container(
width: size.width * .05,
height: size.width * .2,),
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Skender Lahdhiri',
style: TextStyle(
color: Colors.black,
fontSize: 24,
fontWeight: FontWeight.bold),
),
Text('For creating the app.',
style: TextStyle(
color: Colors.grey[700],
fontSize: 12,
fontWeight: FontWeight.bold),
),
Row(
children: <Widget>[
InkWell(
onTap: () {
launch('https://github.com/skenderl');
},
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
child:
SizedBox(
width: size.width * 0.05,
height: size.width * 0.05,
child: SvgPicture.asset('assets/images/github.svg',semanticsLabel: 'Github',color:Colors.black),
),
),Container(
width: size.width * .05,
),
InkWell(
onTap: () {
launch('https://twitter.com/skenderl');
},
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
child:
SizedBox(
width: size.width * 0.05,
height: size.width * 0.05,
child: SvgPicture.asset('assets/images/twitter.svg',semanticsLabel: 'Twitter',color:Colors.black),
),
),Container(
width: size.width * .05,
),
InkWell(
onTap: () {
launch('mailto:lahdhiriskender@gmail.com?subject=BSQApp&body=BSQ:');
},
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
child:
SizedBox(
width: size.width * 0.05,
height: size.width * 0.05,
child: SvgPicture.asset('assets/images/gmail.svg',semanticsLabel: 'Mail',color:Colors.black),
),
),
],
),
],
),
],
),
),
Divider(
indent: size.width * 0.2,
endIndent: size.width * 0.2,
color: Colors.grey,
height: 20,
),
Container(
padding: new EdgeInsets.all(size.width * 0.02),
height: size.height * 0.14,
width: size.width * 0.9,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(99),
boxShadow: [
new BoxShadow(
color: Colors.grey,
offset: new Offset(1.0, 1.0),
blurRadius: 4.0,
spreadRadius: 0.0)
],
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Colors.indigo,
Colors.deepPurple,
Colors.purple,
Colors.purpleAccent,
],
),
),
child: Row(
children: <Widget>[
Container(
width: size.width * .2 ,
height: size.width * .2,
decoration: BoxDecoration(
color: Colors.black,
shape: BoxShape.circle,
image: new DecorationImage(
fit: BoxFit.fill,
image: new NetworkImage(
"https://media.licdn.com/dms/image/C5603AQEJqj10l_ApIg/profile-displayphoto-shrink_800_800/0?e=1572480000&v=beta&t=CsczP9d_P94Z7tES_YsnJW1TddyE9tnXxe2M8mB2Rj4")
)),
),
Container(
width: size.width * .05,
height: size.width * .2,),
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Youssef Tarzi',
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold),
),
Text('For creating the music.',
style: TextStyle(
color: Colors.grey[350],
fontSize: 12,
fontWeight: FontWeight.bold),
),
Row(
children: <Widget>[
InkWell(
onTap: () {
launch('https://github.com/syyoussef');
},
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
child:
SizedBox(
width: size.width * 0.05,
height: size.width * 0.05,
child: SvgPicture.asset('assets/images/github.svg',semanticsLabel: 'Github'),
),
),Container(
width: size.width * .05,
),
InkWell(
onTap: () {
launch('https://twitter.com/Ryoukugyu');
},
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
child:
SizedBox(
width: size.width * 0.05,
height: size.width * 0.05,
child: SvgPicture.asset('assets/images/twitter.svg',semanticsLabel: 'Twitter'),
),
),Container(
width: size.width * .05,
),
InkWell(
onTap: () {
launch('mailto:youssefterzi@gmail.com?subject=BSQApp&body=BSQ:');
},
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
child:
SizedBox(
width: size.width * 0.05,
height: size.width * 0.05,
child: SvgPicture.asset('assets/images/gmail.svg',semanticsLabel: 'Mail'),
),
),
],
),
],
),
],
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/screens/ProgressScreen.dart
|
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ProgressScreen extends StatefulWidget {
ProgressScreen({Key key}) : super(key: key);
@override
ProgressScreenState createState() => new ProgressScreenState();
}
class ProgressScreenState extends State<ProgressScreen> {
Container noTrophy = new Container(
padding:
const EdgeInsets.only(left: 10, top: 10),
color:Colors.white,
height:60,
width: 200,
child: Icon(Icons.more_horiz),
);
Future<List<Widget>> getAllPrefs(String lang) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
List<Widget> items;
Iterable<String> itemsSet;
itemsSet = prefs
.getKeys()
.where((String key) => key != "_sound" && key != "lang" && key != "intro");
switch (lang) {
case "":
itemsSet = itemsSet
.where((String key) => key == "Animals" || key == "Weathers" || key == "Foods" || key == "Countries" || key == "Transportations" || key == "Jobs");
break;
case "fr":
itemsSet = itemsSet
.where((String key) => key == "Animaux" || key == "Météo" || key == "Nourriture" || key == "Pays" || key == "Transports" || key == "Métiers");
break;
case "es":
itemsSet = itemsSet
.where((String key) => key == "Animales" || key == "Climas" || key == "Alimentos" || key == "Países" || key == "Transportes" || key == "Trabajos");
break;
case "ar":
itemsSet = itemsSet
.where((String key) => key == "الحيوانات" || key == "طقس" || key == "طعام" || key == "بلدان" || key == "نقل" || key == "وظائف");
break;
}
items = itemsSet
.map<Widget>((key) =>
ListTile(
title: Text(key,
style: TextStyle(
color: Colors.black,
fontSize: 20,),),
leading: Text("🏅",
style: TextStyle(
color: Colors.black,
fontSize: 30,),),
)
)
.toList(growable: false);
if (items.length != 0){
return items;
}else{
return null;
}
}
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
leading: new IconButton(
icon: new Icon(Icons.arrow_back, color: Colors.black),
onPressed: () => Navigator.of(context).pop(),
),
backgroundColor: Colors.white,
elevation: 2,
title: Text(
"🏆🏆🏆🏆",
style: TextStyle(
color: Colors.black,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
centerTitle: true,
),
body:
SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
// ---------------- english
Container(
padding:
const EdgeInsets.only(left: 10, top: 10),
color:Colors.white,
height:60,
width: size.width,
child:
Text("English 🇬🇧 ",
textAlign : TextAlign.center,
style: TextStyle(
color: Colors.black,
fontSize: 30,),
),
),
FutureBuilder<List<Widget>>(
future: getAllPrefs(""),
builder: (context, snapshot) {
if (!snapshot.hasData) return noTrophy;
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: snapshot.data,
);
}),
Divider(
indent: size.width * 0.02,
endIndent: size.width * 0.02,
color: Colors.black,
height: size.height * 0.04,
),
// ---------------- french
Container(
padding:
const EdgeInsets.only(left: 10, top: 10),
color:Colors.white,
height:60,
width: size.width,
child:
Text("Français 🇫🇷 ",
textAlign : TextAlign.center,
style: TextStyle(
color: Colors.black,
fontSize: 30,),
),
),
FutureBuilder<List<Widget>>(
future: getAllPrefs("fr"),
builder: (context, snapshot) {
if (!snapshot.hasData) return noTrophy;
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: snapshot.data,
);
}),
Divider(
indent: size.width * 0.02,
endIndent: size.width * 0.02,
color: Colors.black,
height: size.height * 0.04,
),
// ---------------- spanish
Container(
padding:
const EdgeInsets.only(left: 10, top: 10),
color:Colors.white,
height:60,
width: size.width,
child:
Text("español 🇪🇸 ",
textAlign : TextAlign.center,
style: TextStyle(
color: Colors.black,
fontSize: 30,),
),
),
FutureBuilder<List<Widget>>(
future: getAllPrefs("es"),
builder: (context, snapshot) {
if (!snapshot.hasData) return noTrophy;
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: snapshot.data,
);
}),
Divider(
indent: size.width * 0.02,
endIndent: size.width * 0.02,
color: Colors.black,
height: size.height * 0.04,
),
// ---------------- arabic
Container(
padding:
const EdgeInsets.only(right: 10, top: 10),
color:Colors.white,
height:60,
width: size.width,
child:
Text(" 🇹🇳 العربية",
textAlign : TextAlign.center,
style: TextStyle(
color: Colors.black,
fontSize: 30,),
),
),
FutureBuilder<List<Widget>>(
future: getAllPrefs("ar"),
builder: (context, snapshot) {
if (!snapshot.hasData) return noTrophy;
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: snapshot.data,
);
}),
Divider(
indent: size.width * 0.02,
endIndent: size.width * 0.02,
color: Colors.black,
height: size.height * 0.04,
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/screens/IntroScreen.dart
|
import 'package:flutter/material.dart';
import 'package:intro_slider/intro_slider.dart';
import 'package:intro_slider/slide_object.dart';
import 'package:shared_preferences/shared_preferences.dart';
class IntroScreen extends StatefulWidget {
IntroScreen({Key key}) : super(key: key);
@override
IntroScreenState createState() => new IntroScreenState();
}
class IntroScreenState extends State<IntroScreen> {
List<Slide> slides = new List();
SharedPreferences prefs;
Function goToTab;
@override
void initState() {
super.initState();
//var size = MediaQuery.of(context).size;
slides.add(
new Slide(
title: " 🇬🇧 🇫🇷 🇪🇸 🇹🇳 ",
description: "Select your language !",
pathImage: "assets/images/intros/lang.png",
colorBegin: Color(0xffFFDAB9),
colorEnd: Color(0xff40E0D0),
directionColorBegin: Alignment.topLeft,
directionColorEnd: Alignment.bottomRight,
),
);
slides.add(
new Slide(
title: "Category",
description: "Select a category !",
pathImage: "assets/images/intros/categ.png",
colorBegin: Colors.redAccent,
colorEnd: Colors.pink,
directionColorBegin: Alignment.topLeft,
directionColorEnd: Alignment.bottomRight,
),
);
slides.add(
new Slide(
title: "Win",
description: "Answer all correct and complete !",
pathImage: "assets/images/intros/win.png",
colorBegin: Colors.purpleAccent,
colorEnd: Colors.red,
directionColorBegin: Alignment.topLeft,
directionColorEnd: Alignment.bottomRight,
),
);
slides.add(
new Slide(
title: "Reward Badge",
description: "Get a reward badge for every category you complete !",
pathImage: "assets/images/intros/rew.png",
colorBegin: Colors.deepOrange,
colorEnd: Colors.amber,
directionColorBegin: Alignment.topLeft,
directionColorEnd: Alignment.bottomRight,
),
);
slides.add(
new Slide(
title: "Progress",
description: "View your progress in every language !",
pathImage: "assets/images/intros/prog.png",
colorBegin: Colors.yellow,
colorEnd: Colors.lightGreen,
directionColorBegin: Alignment.topLeft,
directionColorEnd: Alignment.bottomRight,
),
);
}
void onDonePress() async {
prefs = await SharedPreferences.getInstance();
prefs.setBool('intro', true);
Navigator.of(context).pushNamed('/Home');
}
List<Widget> renderListCustomTabs(Size size) {
List<Widget> tabs = new List();
for (int i = 0; i < slides.length; i++) {
Slide currentSlide = slides[i];
tabs.add(
Container(
width: size.width,
height: size.height,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: currentSlide.backgroundColor != null
? [currentSlide.backgroundColor, currentSlide.backgroundColor]
: [
currentSlide.colorBegin ?? Colors.amberAccent,
currentSlide.colorEnd ?? Colors.amberAccent
],
begin: currentSlide.directionColorBegin ?? Alignment.topLeft,
end: currentSlide.directionColorEnd ?? Alignment.bottomRight,
),
),
child: Container(
margin: EdgeInsets.only(bottom: 60.0),
child: ListView(
children: <Widget>[
Container(
// Title
child: Text(
currentSlide.title ?? "",
style: currentSlide.styleTitle ??
TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 30.0,
),
maxLines: 1,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
),
margin: EdgeInsets.only(
top: 70.0, bottom: 50.0, left: 20.0, right: 20.0),
),
// Image or Center widget
GestureDetector(
child: Image.asset(
currentSlide.pathImage,
width: size.width * 0.8,
height: size.height * 0.6,
fit: currentSlide.foregroundImageFit ?? BoxFit.contain,
),
),
// Description
Container(
child: Text(
currentSlide.description ?? "",
style: currentSlide.styleDescription ??
TextStyle(color: Colors.white, fontSize: 18.0),
textAlign: TextAlign.center,
maxLines: 100,
overflow: TextOverflow.ellipsis,
),
margin: EdgeInsets.fromLTRB(20.0, 50.0, 20.0, 50.0),
),
],
),
),
)
);
}
return tabs;
}
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return new IntroSlider(
slides: this.slides,
onDonePress: this.onDonePress,
listCustomTabs: this.renderListCustomTabs(size),
refFuncGoToTab: (refFunc) {
this.goToTab = refFunc;
},
);
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/screens/HomeScreen.dart
|
import 'dart:io';
import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flare_flutter/flare_actor.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:quiz_app/ui/widgets/EmptyAppBar.dart';
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver {
AudioPlayer player;
AudioCache cache;
String lang = "";
SharedPreferences prefs;
Icon _musicIcon = Icon(Icons.volume_up);
Color _musicColor = Colors.white;
final PageController viewController =
PageController(viewportFraction: 0.8, initialPage: 0);
_setPrefs() async {
prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('_sound')) {
prefs.setBool('_sound', true);
}
_playerPref();
if (!prefs.containsKey('lang')) {
prefs.setString('lang', "");
}
lang = prefs.getString('lang');
}
_playerPref() {
if (prefs.getBool('_sound')) {
cache.loop('audio/background.mp3', volume: 0.4);
setState(() {
_musicIcon = Icon(Icons.volume_up);
_musicColor = Colors.white;
});
} else {
setState(() {
_musicIcon = Icon(Icons.volume_off);
_musicColor = Colors.black;
});
}
}
initState() {
super.initState();
player = new AudioPlayer();
cache = new AudioCache(fixedPlayer: player);
cache.load('audio/background.mp3');
_setPrefs();
WidgetsBinding.instance.addObserver(this);
}
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return WillPopScope(
onWillPop: () => _exitApp(context),
child: Center(
child: Stack(
children: <Widget>[
Container(
height: size.height,
width: size.width,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [Colors.deepPurpleAccent, Colors.redAccent]),
),
child: FlareActor(
"assets/animations/background_animation.flr",
alignment: Alignment.center,
fit: BoxFit.cover,
animation: "animate",
),
),
Scaffold(
backgroundColor: Colors.transparent,
appBar: EmptyAppBar(),
body: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
padding:
const EdgeInsets.only(left: kToolbarHeight / 2),
height: size.height * 0.15,
child: Column(children: <Widget>[
IconButton(
padding: const EdgeInsets.only(
top: kToolbarHeight / 2,
bottom: kToolbarHeight / 8),
icon: _musicIcon,
iconSize: size.width * 0.08,
color: _musicColor,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
tooltip: 'Music',
onPressed: () {
if (prefs.getBool('_sound')) {
setState(() {
prefs.setBool('_sound', false);
_musicIcon = Icon(Icons.volume_off);
_musicColor = Colors.black;
});
player.stop();
} else {
cache.loop('audio/background.mp3',
volume: 0.4);
setState(() {
prefs.setBool('_sound', true);
_musicIcon = Icon(Icons.volume_up);
_musicColor = Colors.white;
});
player.resume();
}
},
),
Container(
height: 0.5,
width: size.width * 0.06,
color: _musicColor,
),
]),
),
Container(
padding:
const EdgeInsets.only(left: kToolbarHeight / 2),
height: size.height * 0.15,
child: Column(children: <Widget>[
IconButton(
padding: const EdgeInsets.only(
top: kToolbarHeight / 2,
bottom: kToolbarHeight / 8),
icon: Icon(Icons.language),
iconSize: size.width * 0.08,
color: Colors.white,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
tooltip: 'Language',
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
backgroundColor:Colors.deepPurpleAccent,
content: Container(
width:size.width/2,
child:
FittedBox(
fit:BoxFit.contain,
child:Column(
children:<Widget>[
Container(
width:size.width/2,
child:
Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Radio(
value: '',
groupValue: lang,
activeColor: Colors.red,
onChanged: (String value) {
prefs.setString('lang', value);
setState(() { lang = value; });
Navigator.of(context).pop();
}
),
Spacer(),Text('English',style: TextStyle(
color: Colors.amberAccent,
shadows: [
Shadow(
color: Colors.blue,
blurRadius: 10.0,
offset: Offset(3.0, 3.0),
),
Shadow(
color: Colors.red,
blurRadius: 10.0,
offset: Offset(-2.0, 2.0),
),
],
),),
],
),),Container(
width:size.width/2,
height: 1,color:Colors.grey,),
Container(
width:size.width/2,
child:
Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Radio(
value: 'FR',
groupValue: lang,
activeColor: Colors.red,
onChanged: (String value) {
prefs.setString('lang', value);
setState(() { lang = value; });
Navigator.of(context).pop();
}
),
Spacer(),Text('Français',style: TextStyle(
color: Colors.amberAccent,
shadows: [
Shadow(
color: Colors.blue,
blurRadius: 10.0,
offset: Offset(3.0, 3.0),
),
Shadow(
color: Colors.red,
blurRadius: 10.0,
offset: Offset(-2.0, 2.0),
),
],
),),
],
),),Container(
width:size.width/2,
height: 1,color:Colors.grey,),
Container(
width:size.width/2,
child:
Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Radio(
value: 'AR',
groupValue: lang,
activeColor: Colors.red,
onChanged: (String value) {prefs.setString('lang', value);
setState(() { lang = value; });
Navigator.of(context).pop();
}
),
Spacer(),Text('العربية',style: TextStyle(
color: Colors.amberAccent,
shadows: [
Shadow(
color: Colors.blue,
blurRadius: 10.0,
offset: Offset(3.0, 3.0),
),
Shadow(
color: Colors.red,
blurRadius: 10.0,
offset: Offset(-2.0, 2.0),
),
],
),),
],
),),Container(
width:size.width/2,
height: 1,color:Colors.grey,),
Container(
width:size.width/2,
child:
Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Radio(
value: 'ES',
groupValue: lang,
activeColor: Colors.red,
onChanged: (String value) {prefs.setString('lang', value);
setState(() { lang = value; });
Navigator.of(context).pop();
}
),
Spacer(),Text('español',style: TextStyle(
color: Colors.amberAccent,
shadows: [
Shadow(
color: Colors.blue,
blurRadius: 10.0,
offset: Offset(3.0, 3.0),
),
Shadow(
color: Colors.red,
blurRadius: 10.0,
offset: Offset(-2.0, 2.0),
),
],
),),
],
),),
],
),
),
),
);
},
);
},
),
Container(
height: 0.5,
width: size.width * 0.06,
color: Colors.white,
),
]),
),
Container(
padding:
const EdgeInsets.only(left: kToolbarHeight / 2),
height: size.height * 0.15,
child: Column(children: <Widget>[
IconButton(
padding: const EdgeInsets.only(
top: kToolbarHeight / 2,
bottom: kToolbarHeight / 8),
icon: Icon(Icons.person),
iconSize: size.width * 0.08,
color: Colors.white,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
tooltip: 'Language',
onPressed: () {
Navigator.of(context).pushNamed('/MyProgress');
},
),
Container(
height: 0.5,
width: size.width * 0.06,
color: Colors.white,
),
]),
),
Spacer(),
Container(
padding: const EdgeInsets.only(
right: kToolbarHeight / 2),
height: size.height * 0.15,
child: Column(children: <Widget>[
IconButton(
padding: const EdgeInsets.only(
top: kToolbarHeight / 2,
bottom: kToolbarHeight / 2),
icon: Icon(Icons.info),
iconSize: size.width * 0.08,
color: Colors.white,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
tooltip: 'About',
onPressed: () {
Navigator.of(context).pushNamed('/About');
},
),
]),
),
]),
Container(
width: size.width * 0.9,
height: size.height * 0.1,
child:FittedBox(
fit:BoxFit.contain,
child:Text(
"Baby Steps Quiz",
style: TextStyle(
color: Colors.amberAccent,
shadows: [
Shadow(
color: Colors.blue,
blurRadius: 10.0,
offset: Offset(3.0, 3.0),
),
Shadow(
color: Colors.red,
blurRadius: 10.0,
offset: Offset(-2.0, 2.0),
),
],
),
),
),
),
Spacer(),
Container(
child: InkWell(
onTap: () {
Navigator.of(context).pushNamed('/Menu');
},
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
child: Container(
color: Colors.transparent,
height: size.width * 0.8,
width: size.width * 0.8,
child:
FlareActor(
"assets/animations/click.flr",
alignment: Alignment.center,
fit: BoxFit.contain,
animation: "animate",
),
),
),
),Spacer(),
Container(
padding:
const EdgeInsets.only(bottom: kToolbarHeight / 2),
color: Colors.transparent,
height: size.height * 0.2,
width: size.width ,
child: FlareActor(
"assets/animations/tapp.flr",
color: Colors.white,
alignment: Alignment.center,
fit: BoxFit.contain,
animation: lang == "" ? "animate" : "animate$lang",
),
),
],
),
),
],
),
));
}
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.paused && prefs.getBool('_sound')) {
player.pause();
} else if (prefs.getBool('_sound')) {
player.resume();
}
}
void dispose() {
WidgetsBinding.instance.removeObserver(this);
player.stop();
viewController.dispose();
super.dispose();
}
}
Future<bool> _exitApp(BuildContext context) {
exit(0);
return Future.delayed(Duration(seconds: 0), () => false);
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/screens/CategoryMenuScreen.dart
|
import 'package:flutter/material.dart';
import 'package:flare_flutter/flare_actor.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:quiz_app/models/Category.dart';
import 'package:quiz_app/models/CurrentCategory.dart';
import 'package:quiz_app/models/Categories.dart';
import 'package:quiz_app/strings/StringsLoader.dart';
import 'package:quiz_app/ui/widgets/Progress.dart';
class CategoryMenuScreen extends StatefulWidget {
@override
_CategoryMenuScreenState createState() => _CategoryMenuScreenState();
}
class _CategoryMenuScreenState extends State<CategoryMenuScreen> {
final PageController viewController =
PageController(viewportFraction: 0.8, initialPage: 0);
String lang = "";
SharedPreferences prefs;
StringsLoader myStrings;
initState() {
super.initState();
SharedPreferences.getInstance().then((SharedPreferences sp) {
prefs = sp;
lang = sp.getString('lang');
if (lang == null) {
lang = "";
persistLang(lang);
}
setState(() {});
});
}
void persistLang(String value) {
setState(() {
lang = value;
});
prefs?.setString('lang', value);
}
@override
Widget build(BuildContext context) {
myStrings = new StringsLoader(lang);
var size = MediaQuery.of(context).size;
final double itemHeight = (size.height - kToolbarHeight - 24) - 220;
return Center(
child: Stack(children: <Widget>[
Container(
height: size.height,
width: size.width,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [Colors.deepPurpleAccent, Colors.redAccent]),
),
child: FlareActor(
"assets/animations/background_animation.flr",
alignment: Alignment.center,
fit: BoxFit.cover,
animation: "animate",
),
),
Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
leading: new IconButton(
icon: new Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => Navigator.of(context).pop(),
),
backgroundColor: Colors.transparent,
elevation: 0,
title: Text(
"${myStrings.loadCategoryMenu()}",
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
color: Colors.transparent,
height: size.height * 0.04,
),
Expanded(
child: Container(
height: itemHeight,
child: PageView(
controller: viewController,
children: [
CategoryCard(Categories.Animal,myStrings),
CategoryCard(Categories.Job,myStrings),
CategoryCard(Categories.Weather,myStrings),
CategoryCard(Categories.Food,myStrings),
CategoryCard(Categories.Transportation,myStrings),
CategoryCard(Categories.Flag,myStrings),
],
),
),
),
Container(
color: Colors.transparent,
height: size.height * 0.04,
),
],
),
),
),
]));
}
void dispose() {
super.dispose();
viewController.dispose();
}
}
class CategoryCard extends StatefulWidget {
Categories category;
String categoryName;
String animationPath;
StringsLoader myStrings;
CategoryCard(this.category,this.myStrings) {
switch (category) {
case Categories.Animal:
categoryName = myStrings.loadCategories("animal").name;
animationPath = "assets/animations/animal_animation.flr";
break;
case Categories.Food:
categoryName = myStrings.loadCategories("food").name;
animationPath = "assets/animations/food_animation.flr";
break;
case Categories.Transportation:
categoryName = myStrings.loadCategories("transportation").name;
animationPath = "assets/animations/transportation_animation.flr";
break;
case Categories.Flag:
categoryName = myStrings.loadCategories("flag").name;
animationPath = "assets/animations/flag_animation.flr";
break;
case Categories.Job:
categoryName = myStrings.loadCategories("job").name;
animationPath = "assets/animations/job_animation.flr";
break;
case Categories.Weather:
categoryName = myStrings.loadCategories("weather").name;
animationPath = "assets/animations/weather_animation.flr";
break;
}
}
@override
_CategoryCardState createState() => _CategoryCardState();
}
class _CategoryCardState extends State<CategoryCard> {
SharedPreferences prefs;
bool _award = true;
initState() {
super.initState();
SharedPreferences.getInstance().then((SharedPreferences sp) {
prefs = sp;
_award = sp.containsKey(widget.categoryName);
if (_award == null) {
_award = false;
persist(_award);
}
setState(() {});
});
}
void persist(bool value) {
setState(() {
_award = value;
});
prefs?.setBool(widget.categoryName, value);
}
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Padding(
padding: EdgeInsets.all(8.0),
child: Card(
elevation: 8.0,
color: Colors.purple,
child: Container(
decoration: BoxDecoration(
border: Border.all(width: 8, color: Colors.white),
),
child: InkWell(
onTap: () {
Category category;
List<ProgressKind> prog = new List<ProgressKind>.filled(10,ProgressKind.notYet);
if (widget.category == Categories.Animal) {
category = widget.myStrings.loadCategories('animal');
Navigator.of(context).pushNamed(
'/Category',
arguments: CurrentCategory(category,0,Progress(progress: prog)),
);
} else if (widget.category == Categories.Food) {
category = widget.myStrings.loadCategories('food');
Navigator.of(context).pushNamed(
'/Category',
arguments: CurrentCategory(category,0,Progress(progress: prog)),
);
} else if (widget.category == Categories.Transportation) {
category = widget.myStrings.loadCategories('transportation');
Navigator.of(context).pushNamed(
'/Category',
arguments: CurrentCategory(category,0,Progress(progress: prog)),
);
} else if (widget.category == Categories.Flag) {
category = widget.myStrings.loadCategories('flag');
Navigator.of(context).pushNamed(
'/Category',
arguments: CurrentCategory(category,0,Progress(progress: prog)),
);
} else if (widget.category == Categories.Job) {
category = widget.myStrings.loadCategories('job');
Navigator.of(context).pushNamed(
'/Category',
arguments: CurrentCategory(category,0,Progress(progress: prog)),
);
} else {
category = widget.myStrings.loadCategories('weather');
Navigator.of(context).pushNamed(
'/Category',
arguments: CurrentCategory(category,0,Progress(progress: prog)),
);
}
},
splashColor: Colors.indigo,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(
widget.categoryName,
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: size.width * 0.07,
),
),
_award
? Container(
height:size.height * 0.1,
child:SvgPicture.asset('assets/images/award.svg'),
) : SizedBox(),
Container(
height: 300,
child: FlareActor(
widget.animationPath,
alignment: Alignment.center,
fit: BoxFit.contain,
animation: "animate",
),
),
],
),
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/screens/SplashScreen.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SplashScreen extends StatefulWidget {
@override
SplashScreenState createState() => new SplashScreenState();
}
class SplashScreenState extends State<SplashScreen>
with SingleTickerProviderStateMixin {
var _visible = true;
AnimationController animationController;
Animation<double> animation;
SharedPreferences prefs;
startTime() async {
var _duration = new Duration(seconds: 6);
return new Timer(_duration, navigationPage);
}
void navigationPage() async{
prefs = await SharedPreferences.getInstance();
if(prefs.containsKey('intro')){
Navigator.of(context).pushNamedAndRemoveUntil('/Home',(Route<dynamic> route) => false);
}else{
Navigator.of(context).pushNamedAndRemoveUntil('/Intro',(Route<dynamic> route) => false);
}
}
@override
void initState() {
super.initState();
animationController = new AnimationController(
vsync: this,
duration: new Duration(seconds: 4),
);
animation =
new CurvedAnimation(parent: animationController, curve: Curves.easeOut);
animation.addListener(() => this.setState(() {}));
animationController.forward();
setState(() {
_visible = !_visible;
});
startTime();
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child:Scaffold(
backgroundColor: Colors.black,
body: Stack(
fit: StackFit.expand,
children: <Widget>[
new Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(
padding: EdgeInsets.only(bottom: 30.0),
child: Text(
"all copyrights reserved ©",
style: TextStyle(
color: Colors.amberAccent,
shadows: [
Shadow(
color: Colors.yellowAccent,
blurRadius: 10.0,
offset: Offset(3.0, 3.0),
),
Shadow(
color: Colors.pink[300],
blurRadius: 10.0,
offset: Offset(-2.0, 2.0),
),
],
),
),
)
],
),
new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Image.asset(
"assets/images/dev_icon.png",
width: animation.value * 250,
height: animation.value * 250,
),
],
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/screens/ResultScreen.dart
|
import 'package:flutter/material.dart';
import 'package:flare_flutter/flare_actor.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:quiz_app/strings/StringsLoader.dart';
class ResultScreen extends StatefulWidget {
final int correct;
const ResultScreen({
Key key,
this.correct,
}) : super(key: key);
@override
_ResultScreenState createState() => _ResultScreenState();
}
class _ResultScreenState extends State<ResultScreen> {
String lang = "";
SharedPreferences prefs;
StringsLoader myStrings;
initState() {
super.initState();
SharedPreferences.getInstance().then((SharedPreferences sp) {
prefs = sp;
lang = sp.getString('lang');
if (lang == null) {
lang = "";
}
setState(() {});
});
}
@override
Widget build(BuildContext context) {
myStrings = new StringsLoader(lang);
var size = MediaQuery.of(context).size;
String correct = widget.correct.toString();
String incorrect = (10 - widget.correct).toString();
String anim = widget.correct == 10 ? 'troph' : 'loss';
String res = widget.correct == 10 ? myStrings.loadWinLoose(true) : myStrings.loadWinLoose(false);
Color resColor = widget.correct == 10 ? Colors.amber : Colors.green;
return WillPopScope(
onWillPop: () async => false,
child: Center(
child: Stack(
children: <Widget>[
Container(
height: size.height,
width: size.width,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [Colors.deepPurpleAccent, Colors.redAccent]),
),
child: FlareActor(
"assets/animations/background_animation.flr",
alignment: Alignment.center,
fit: BoxFit.cover,
animation: "animate",
),
),
Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
leading: Container(),
backgroundColor: Colors.transparent,
elevation: 0,
title: Text(
'${myStrings.loadNext(false)}',
style: TextStyle(
decoration: TextDecoration.underline,
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
centerTitle: true,
),
body: Column(
children: <Widget>[
Container(
width:size.width * 2/3,
height:size.height / 3,
child:
FlareActor(
"assets/animations/$anim.flr",
alignment: Alignment.center,
fit: BoxFit.cover,
animation: "animate",
),
),
Container(
color: Colors.transparent,
height: size.height * 0.08,
width: size.width* 0.9 ,
child: FittedBox(
fit:BoxFit.contain,
child:
Center(
child: Text(
'$res',
style: TextStyle(
color: resColor,
fontSize: 38,
fontWeight: FontWeight.bold,
),
),
),),),
Divider(
indent: size.width / 10,
endIndent: size.width / 10,
color: Colors.yellowAccent,
height: size.height * .08,
),
Container(
width: size.width,
decoration: BoxDecoration(
boxShadow: [
new BoxShadow(
color: Colors.white,
offset: new Offset(0.0, 0.0),
blurRadius: 160.0,
spreadRadius: 20.0)
],
color: Colors.transparent,
borderRadius: BorderRadius.circular(99)),
child: Center(
child: Text(
'${myStrings.loadResult(true)}: ⭕️️ $correct',
style: TextStyle(
color: Colors.blue,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
),
Divider(
indent: size.width / 4,
endIndent: size.width / 4,
color: Colors.black,
height: size.height * .08,
),
Container(
width: size.width,
decoration: BoxDecoration(
boxShadow: [
new BoxShadow(
color: Colors.white,
offset: new Offset(0.0, 0.0),
blurRadius: 160.0,
spreadRadius: 20.0)
],
color: Colors.transparent,
borderRadius: BorderRadius.circular(99)),
child: Center(
child: Text(
'${myStrings.loadResult(false)}: ❌ $incorrect',
style: TextStyle(
color: Colors.redAccent[700],
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
),
Spacer(),
Container(
child: InkWell(
onTap: () {
Navigator.of(context).pushNamedAndRemoveUntil('/Home', (Route<dynamic> route) => false);
},
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
child: Container(
width: size.width * 0.8,
height: size.width /5,
decoration:
BoxDecoration(
color: Colors.amberAccent,
border: Border.all(
width: 1.0
),
borderRadius: BorderRadius.all(
Radius.circular(8.0) // <--- border radius here
),
),
child: Center(
child: Text("${myStrings.loadPlayAgain()}",
style: TextStyle(
color: Colors.indigo[900],
fontSize: 48,
fontWeight: FontWeight.bold,
),
),
),
),
),
),Spacer(),
],
),
),
],
),
));
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui
|
mirrored_repositories/Flutter-BabyStepsQuiz/lib/ui/screens/CategoryScreen.dart
|
import 'package:flutter/material.dart';
import 'package:flare_flutter/flare_actor.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:math';
import 'package:quiz_app/ui/widgets/chooser/ArcChooser.dart';
import 'package:quiz_app/ui/widgets/chooser/ChooserPainter.dart';
import 'package:quiz_app/ui/widgets/Progress.dart';
import 'package:quiz_app/models/Category.dart';
import 'package:quiz_app/models/Quiz.dart';
import 'package:quiz_app/models/CurrentCategory.dart';
import 'package:quiz_app/strings/StringsLoader.dart';
class CategoryScreen extends StatefulWidget {
final CurrentCategory category;
const CategoryScreen({
Key key,
this.category,
}) : super(key: key);
@override
_CategoryScreenState createState() => _CategoryScreenState();
}
class _CategoryScreenState extends State<CategoryScreen>
with TickerProviderStateMixin {
final PageController pageControl = new PageController(
initialPage: 2,
keepPage: false,
viewportFraction: 0.2,
);
String lang = "";
SharedPreferences prefs;
StringsLoader myStrings;
int slideValue = 200;
int lastAnimPosition = 2;
int answer = 2;
int quizPage;
Quiz currentQuiz;
int currentCorrect;
List<String> currentCandidates;
AnimationController animation;
Category category;
Progress currentProgress;
Color startColor;
Color endColor;
getSecondImage(size){
if (currentQuiz.secondImage != null){
return SizedBox(
width: size.width/2 - size.width * 0.005,
height: size.height/3,
child: SvgPicture.asset(
currentQuiz.secondImage,
semanticsLabel: currentQuiz.correct,
),
);
}else{
return Container();
}
}
getFirstImage(size){
if (currentQuiz.secondImage != null){
return Row(
children: <Widget>[
SizedBox(
width: size.width/2 - size.width * 0.005,
height: size.height/3,
child: SvgPicture.asset(
currentQuiz.image,
semanticsLabel: currentQuiz.correct,
),
),
Transform.rotate(
angle: pi/20,
child:Container(
height: size.height/4,
width: size.width * 0.01,
color: Colors.white,
),
),
]);
}else{
return SvgPicture.asset(
currentQuiz.image,
semanticsLabel: currentQuiz.correct,
);
}
}
@override
void initState() {
super.initState();
SharedPreferences.getInstance().then((SharedPreferences sp) {
prefs = sp;
lang = sp.getString('lang');
if (lang == null) {
lang = "";
}
setState(() {});
});
category = widget.category.category;
quizPage = widget.category.current;
currentProgress = widget.category.progress;
currentProgress.progress[quizPage] = ProgressKind.current;
currentQuiz = category.quizs[quizPage];
currentCorrect = (currentQuiz.candidates.indexOf(currentQuiz.correct)+1)==4 ?0:(currentQuiz.candidates.indexOf(currentQuiz.correct)+1);
currentCandidates = currentQuiz.candidates;
startColor = Color(0xFF21e1fa);
endColor = Color(0xff3bb8fd);
animation = new AnimationController(
value: 0.0,
lowerBound: 0.0,
upperBound: 400.0,
duration: const Duration(milliseconds: 800),
vsync: this,
)..addListener(() {
setState(() {
slideValue = animation.value.toInt();
double ratio;
if (slideValue <= 100) {
ratio = animation.value / 100;
startColor =
Color.lerp(Color(0xFFfe0944), Color(0xFFF9D976), ratio);
endColor = Color.lerp(Color(0xFFfeae96), Color(0xfff39f86), ratio);
} else if (slideValue <= 200) {
ratio = (animation.value - 100) / 100;
startColor =
Color.lerp(Color(0xFFF9D976), Color(0xFF21e1fa), ratio);
endColor = Color.lerp(Color(0xfff39f86), Color(0xff3bb8fd), ratio);
} else if (slideValue <= 300) {
ratio = (animation.value - 200) / 100;
startColor =
Color.lerp(Color(0xFF21e1fa), Color(0xFF3ee98a), ratio);
endColor = Color.lerp(Color(0xff3bb8fd), Color(0xFF41f7c7), ratio);
} else if (slideValue <= 400) {
ratio = (animation.value - 300) / 100;
startColor =
Color.lerp(Color(0xFF3ee98a), Color(0xFFfe0944), ratio);
endColor = Color.lerp(Color(0xFF41f7c7), Color(0xFFfeae96), ratio);
}
});
});
animation.animateTo(slideValue.toDouble());
}
categoryCompleted() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool(category.name, true);
}
@override
Widget build(BuildContext context) {
myStrings = new StringsLoader(lang);
var size = MediaQuery.of(context).size;
String ans = myStrings.loadAnswer();
return WillPopScope(
onWillPop: () async => false,
child: Center(
child: Stack(children: <Widget>[
Container(
height: size.height,
width: size.width,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [Colors.deepPurpleAccent, Colors.redAccent]),
),
child: FlareActor(
"assets/animations/background_animation.flr",
alignment: Alignment.center,
fit: BoxFit.cover,
animation: "animate",
),
),
Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
leading: Container(),
backgroundColor: Colors.transparent,
elevation: 0,
title: Text(
category.name,
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
child: Container(
color: Colors.transparent,
child: Column(children: <Widget>[
Container(
color: Colors.white,
height: size.height * 0.05,
width: size.width,
child: currentProgress,
),
Divider(
indent: 0,
endIndent: 0,
color: Colors.black,
height: 2,
),
Padding(
padding: EdgeInsets.all(8.0),
child:
Container(
color: Colors.transparent,
height: size.height * 0.04,
width: size.width * 0.9,
child: FittedBox(
fit:BoxFit.contain,
child:Text(
category.question,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
),
),Spacer(),
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: size.width,
minWidth: size.width,
maxHeight: size.height / 3,
minHeight: size.height / 4,
),
child: FittedBox(
fit:BoxFit.contain,
child:
Row(
children: <Widget>[
getFirstImage(size),
getSecondImage(size),
],
),),),
Spacer(),
Container(
color: Colors.transparent,
width: size.width,
child:
Stack(
children: <Widget>[
Container(
color: Colors.transparent,
width: size.width,
child: ArcChooser()
..arcNames = currentCandidates
..arcSelectedCallback = (int pos, ArcItem item) {
int animPosition = pos - 2;
if (animPosition > 3) {
animPosition = animPosition - 4;
}
if (animPosition < 0) {
animPosition = 4 + animPosition;
}
if (lastAnimPosition == 3 && animPosition == 0) {
animation.animateTo(4 * 100.0);
} else if (lastAnimPosition == 0 && animPosition == 3) {
animation.forward(from: 4 * 100.0);
animation.animateTo(animPosition * 100.0);
} else if (lastAnimPosition == 0 && animPosition == 1) {
animation.forward(from: 0.0);
animation.animateTo(animPosition * 100.0);
} else {
animation.animateTo(animPosition * 100.0);
}
lastAnimPosition = animPosition;
setState(() {
answer = lastAnimPosition;
});
},
),
Positioned(
bottom: 0,
left: (size.width - size.width / 2) / 2,
child: InkWell(
onTap: () {
if(currentCorrect == answer){
currentProgress.progress[quizPage] = ProgressKind.correct;
}else{
currentProgress.progress[quizPage] = ProgressKind.incorrect;
}
String res = currentCorrect == answer ? myStrings.loadResult(true) : myStrings.loadResult(false);
String nx = quizPage != currentProgress.progress.length-1 ? myStrings.loadNext(true) : myStrings.loadNext(false);
var anim = currentCorrect == answer ? 'success' : 'fail';
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
content: WillPopScope(
onWillPop: () async => false,
child:Container(
height: size.height/3,
child:
FittedBox(
fit:BoxFit.contain,
child:Column(
children:<Widget>[
Container(
width:size.height/5,
height:size.height/5,
child:
FlareActor(
"assets/animations/$anim.flr",
alignment: Alignment.center,
fit: BoxFit.cover,
animation: "animate",
),
),
Container(
color: Colors.black,
height: 1,
width: size.height/5,
),
Text(
'$res',
style: TextStyle(color: Colors.black,fontSize: 30),
),
Container(
color: Colors.black,
height: 1,
width: size.height/10,
),
FlatButton(
color: Colors.transparent,
textColor: Colors.orange,
padding: EdgeInsets.all(8.0),
splashColor: Colors.transparent,
onPressed: () {
if(quizPage != currentProgress.progress.length-1){
Navigator.of(context).pushNamed(
'/Category',
arguments: CurrentCategory(category,quizPage+1,currentProgress),
);
}else{
int corNum = currentProgress.progress.where((cor) => cor == ProgressKind.correct).length;
if (corNum == 10) {
categoryCompleted();
}
Navigator.of(context).pushNamed(
'/Result',
arguments: corNum,
);
}
},
child: Text('$nx',
style: TextStyle(
color: Colors.orange,
fontSize: 22,),
),
),
]
),
),
),
),
);
},
);
},
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
child: Container(
width: size.width / 2,
height: size.height * 0.135,
decoration: BoxDecoration(
boxShadow: [
new BoxShadow(
color: Colors.grey,
offset: new Offset(0.0, 0.0),
blurRadius: 160.0,
spreadRadius: 20.0)
],
color: Colors.transparent,
borderRadius: BorderRadius.circular(99)),
child: Center(
child: Text("$ans",
style: TextStyle(
color: Colors.white,
fontSize: 38,
shadows: [
Shadow( // bottomLeft
offset: Offset(-1.5, -1.5),
color: Colors.black
),
Shadow( // bottomRight
offset: Offset(1.5, -1.5),
color: Colors.black
),
Shadow( // topRight
offset: Offset(1.5, 1.5),
color: Colors.black
),
Shadow( // topLeft
offset: Offset(-1.5, 1.5),
color: Colors.black
),
],
fontWeight: FontWeight.bold,
)),
)),
),
),
],
),
),
],
),
),
),
],
),
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-BabyStepsQuiz
|
mirrored_repositories/Flutter-BabyStepsQuiz/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:quiz_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(QuizApp());
// 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/PokeDoke
|
mirrored_repositories/PokeDoke/lib/firebase_options.dart
|
// File generated by FlutterFire CLI.
// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
show defaultTargetPlatform, kIsWeb, TargetPlatform;
/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
/// options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
if (kIsWeb) {
return web;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return android;
case TargetPlatform.iOS:
return ios;
case TargetPlatform.macOS:
return macos;
case TargetPlatform.windows:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for windows - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.linux:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for linux - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}
static const FirebaseOptions web = FirebaseOptions(
apiKey: 'AIzaSyDdCgp8SxMHcYRBYhtuNZEi_DdLquMV_Qw',
appId: '1:10924512742:web:97d8680aed41f32aecf227',
messagingSenderId: '10924512742',
projectId: 'pokedoke-75f8d',
authDomain: 'pokedoke-75f8d.firebaseapp.com',
storageBucket: 'pokedoke-75f8d.appspot.com',
);
static const FirebaseOptions android = FirebaseOptions(
apiKey: 'AIzaSyDfQ08sC6KJfHMtd0gR9K0DztU-8LfL_KM',
appId: '1:10924512742:android:4b3d7c70d124a216ecf227',
messagingSenderId: '10924512742',
projectId: 'pokedoke-75f8d',
storageBucket: 'pokedoke-75f8d.appspot.com',
);
static const FirebaseOptions ios = FirebaseOptions(
apiKey: 'AIzaSyB5s_TO9xWXPkJp4zdV1R9wUMONfYqFKsQ',
appId: '1:10924512742:ios:1a49e07fe52a6261ecf227',
messagingSenderId: '10924512742',
projectId: 'pokedoke-75f8d',
storageBucket: 'pokedoke-75f8d.appspot.com',
iosClientId: '10924512742-tobn3r1lhpvls9tc4qjt9vomc9e91qn2.apps.googleusercontent.com',
iosBundleId: 'com.example.pokedoke',
);
static const FirebaseOptions macos = FirebaseOptions(
apiKey: 'AIzaSyB5s_TO9xWXPkJp4zdV1R9wUMONfYqFKsQ',
appId: '1:10924512742:ios:1a49e07fe52a6261ecf227',
messagingSenderId: '10924512742',
projectId: 'pokedoke-75f8d',
storageBucket: 'pokedoke-75f8d.appspot.com',
iosClientId: '10924512742-tobn3r1lhpvls9tc4qjt9vomc9e91qn2.apps.googleusercontent.com',
iosBundleId: 'com.example.pokedoke',
);
}
| 0
|
mirrored_repositories/PokeDoke
|
mirrored_repositories/PokeDoke/lib/main.dart
|
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pokedoke/blocs/favourite%20pokemons/bloc/favourites_bloc.dart';
import 'package:pokedoke/blocs/user%20bloc/bloc/user_bloc.dart';
import 'package:pokedoke/database/cloud/firestore_methods.dart';
import 'package:pokedoke/firebase_options.dart';
import 'package:pokedoke/screens/home_screen.dart';
import 'package:pokedoke/screens/login_screen.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
HydratedBloc.storage = await HydratedStorage.build(
storageDirectory: await getApplicationDocumentsDirectory());
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(create: (context) => UserBloc()),
BlocProvider(lazy: false, create: (context) => FavouritesBloc()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: BlocBuilder<UserBloc, UserState>(
builder: (context, state) {
if (state.user.isLoggedIn) {
return HomeScreen();
} else {
return LoginScreen();
}
},
),
),
);
}
getData() async {}
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/global/global_methods.dart
|
import 'package:pokedoke/models/pokemons.dart';
List<Pokemon> getFilteredFavourites(List<Pokemon> allPokemons, List<String> allUsers,String userId){
List<Pokemon> filtered = [];
for (int i = 0; i < allPokemons.length; i++) {
if (allUsers[i] == userId) {
filtered.add(allPokemons[i]);
}
}
return filtered;
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/constants/colors.dart
|
import 'package:flutter/material.dart';
var scaffoldBackgroundColor = const Color.fromRGBO(244,244,244, 1);
var secondaryColor = const Color.fromRGBO(33,33,33, 1);
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/widgets/favourite_pokemon_tile.dart
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pokedoke/blocs/favourite%20pokemons/bloc/favourites_bloc.dart';
import 'package:pokedoke/constants/colors.dart';
import 'package:pokedoke/models/pokemons.dart';
class FavouritePokemonTile extends StatelessWidget {
final Pokemon pokemon;
const FavouritePokemonTile({required this.pokemon,super.key});
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Row(
children: [
CachedNetworkImage(
imageUrl: pokemon.img!,
height: 70,
fit: BoxFit.fitHeight,
),
const SizedBox(width: 10,),
Column(children: [
Text(pokemon.name!, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),),
Text(pokemon.type![0], style: const TextStyle(fontSize: 16),)
],),
Expanded(child: Container()),
IconButton(onPressed: (){
context.read<FavouritesBloc>().add(DeleteFavourites(pokemon: pokemon));
}, icon: Icon(Icons.delete, color: secondaryColor,))
],
),
Divider(color: secondaryColor,)
],
),
);
}
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/widgets/poke_categories_card.dart
|
import 'package:flutter/material.dart';
class CategoryCard extends StatelessWidget {
final String image;
final String title;
final Function onPressed;
const CategoryCard({required this.image,required this.title, required this.onPressed ,super.key});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
onPressed();
},
child: Container(
child: Stack(
children: [
ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(10)),
child: SizedBox(
height: 110,
width: 180,
child: Image.asset(
'assets/images/$image',
fit: BoxFit.fill,
),
),
),
ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(10)),
child: Container(
height: 110,
width: 180,
color: Colors.black26,
child: Center(
child: Text("${title[0].toUpperCase()}${title.substring(1).toLowerCase()}",
style: const TextStyle(color: Colors.white, fontSize: 18)),
)),
)
],
),
),
);
}
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/widgets/snackbar.dart
|
import 'package:awesome_snackbar_content/awesome_snackbar_content.dart';
import 'package:flutter/material.dart';
displaySnackbar(BuildContext context, String type, String message) {
final snackBar = SnackBar(
/// need to set following properties for best effect of awesome_snackbar_content
elevation: 0,
behavior: SnackBarBehavior.floating,
backgroundColor: Colors.transparent,
content: AwesomeSnackbarContent(
title: type == 'error'? 'Oops!' : "Congratulations!",
message: message,
contentType: type == 'error'? ContentType.failure : ContentType.success,
),
);
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(snackBar);
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/widgets/poke_card.dart
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:pokedoke/models/pokemons.dart';
import 'package:pokedoke/screens/poke_details_screen.dart';
class PokeCard extends StatelessWidget {
final Pokemon pokemon;
const PokeCard({required this.pokemon, super.key});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => PokeDetailsScreen(
pokemon: pokemon,
color: pokemon.type![0] == "Grass"
? Colors.greenAccent
: pokemon.type![0] == "Fire"
? Colors.redAccent
: pokemon.type![0] == "Water"
? Colors.blue
: pokemon.type![0] == "Poison"
? Colors.deepPurpleAccent
: pokemon.type![0] == "Electric"
? Colors.amber
: pokemon.type![0] == "Rock"
? Colors.grey
: pokemon.type![0] == "Ground"
? Colors.brown
: pokemon.type![0] == "Psychic"
? Colors.indigo
: pokemon.type![0] ==
"Fighting"
? Colors.orange
: pokemon.type![0] ==
"Bug"
? Colors
.lightGreenAccent
: pokemon.type![0] ==
"Ghost"
? Colors
.deepPurple
: pokemon.type![
0] ==
"Normal"
? Colors
.black26
: Colors.pink,
)));
},
child: Card(
color: pokemon.type![0] == "Grass"
? Colors.greenAccent
: pokemon.type![0] == "Fire"
? Colors.redAccent
: pokemon.type![0] == "Water"
? Colors.blue
: pokemon.type![0] == "Poison"
? Colors.deepPurpleAccent
: pokemon.type![0] == "Electric"
? Colors.amber
: pokemon.type![0] == "Rock"
? Colors.grey
: pokemon.type![0] == "Ground"
? Colors.brown
: pokemon.type![0] == "Psychic"
? Colors.indigo
: pokemon.type![0] == "Fighting"
? Colors.orange
: pokemon.type![0] == "Bug"
? Colors.lightGreenAccent
: pokemon.type![0] == "Ghost"
? Colors.deepPurple
: pokemon.type![0] ==
"Normal"
? Colors.black26
: Colors.pink,
child: Stack(
children: [
Positioned(top: 30, left: 10, child: Text(pokemon.name!)),
Positioned(top: 45, left: 10, child: Text(pokemon.type![0])),
Positioned(
bottom: 5,
right: -10,
child: CachedNetworkImage(
imageUrl: pokemon.img!,
height: 100,
fit: BoxFit.fitHeight,
))
],
),
),
);
}
}
| 0
|
mirrored_repositories/PokeDoke/lib/database
|
mirrored_repositories/PokeDoke/lib/database/cloud/firestore_methods.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
getUserName(String documentId) async {
String name = "Initial";
await FirebaseFirestore.instance
.collection('users')
.where('id', isEqualTo: documentId)
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
name = doc["name"];
});
});
return name;
}
| 0
|
mirrored_repositories/PokeDoke/lib/blocs/user bloc
|
mirrored_repositories/PokeDoke/lib/blocs/user bloc/bloc/user_event.dart
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
part of 'user_bloc.dart';
@immutable
abstract class UserEvent {}
class LoginUser implements UserEvent {
UserModel user;
BuildContext context;
LoginUser({
required this.user,
required this.context,
});
}
class SignupUser implements UserEvent {
UserModel user;
SignupUser({
required this.user,
});
}
class LogoutUser implements UserEvent {
}
class SetUserNameId implements UserEvent {
String name;
String id;
SetUserNameId({
required this.name,
required this.id,
});
}
class SetUserId implements UserEvent {
String id;
SetUserId({
required this.id,
});
}
| 0
|
mirrored_repositories/PokeDoke/lib/blocs/user bloc
|
mirrored_repositories/PokeDoke/lib/blocs/user bloc/bloc/user_state.dart
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
part of 'user_bloc.dart';
@immutable
class UserState {
UserModel user;
UserState({
required this.user,
});
Map<String, dynamic> toMap() {
return <String, dynamic>{
'user': user.toMap(),
};
}
factory UserState.fromMap(Map<String, dynamic> map) {
return UserState(
user: UserModel.fromMap(map['user'] as Map<String,dynamic>),
);
}
String toJson() => json.encode(toMap());
factory UserState.fromJson(String source) => UserState.fromMap(json.decode(source) as Map<String, dynamic>);
}
| 0
|
mirrored_repositories/PokeDoke/lib/blocs/user bloc
|
mirrored_repositories/PokeDoke/lib/blocs/user bloc/bloc/user_bloc.dart
|
import 'package:bloc/bloc.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:meta/meta.dart';
import 'package:pokedoke/database/cloud/firestore_methods.dart';
import 'package:pokedoke/models/user_model.dart';
import 'dart:convert';
import 'package:pokedoke/services/authentications.dart';
import 'package:pokedoke/widgets/snackbar.dart';
part 'user_event.dart';
part 'user_state.dart';
bool mounted = true;
class UserBloc extends HydratedBloc<UserEvent, UserState> {
UserBloc()
: super(UserState(
user: UserModel(
userId: null,
userName: null,
userEmail: null,
userPassword: null,
isSignedUp: false,
isLoggedIn: false))) {
on<LoginUser>(_loginUser);
on<SignupUser>(_signupUser);
on<SetUserNameId>(_setNameId);
on<LogoutUser>(_logoutUser);
}
_logoutUser(LogoutUser event, Emitter<UserState> emit) async {
await Authentication().signOut();
UserModel user = UserModel(
userEmail: state.user.userEmail,
userPassword: state.user.userPassword,
userName: state.user.userName,
userId: state.user.userId,
isLoggedIn: false,
isSignedUp: true);
emit(UserState(user: user));
}
_setNameId(SetUserNameId event, Emitter<UserState> emit) async {
UserModel user = UserModel(
userEmail: state.user.userEmail,
userPassword: state.user.userPassword,
userName: event.name,
userId: event.id,
isLoggedIn: true,
isSignedUp: true);
emit(UserState(user: user));
}
_loginUser(LoginUser event, Emitter<UserState> emit) async {
String result = await Authentication().login(event.user);
if (result == "success") {
String _name = await getUserName(FirebaseAuth.instance.currentUser!.uid);
String _id = FirebaseAuth.instance.currentUser!.uid;
emit(UserState(
user: UserModel(
userEmail: event.user.userEmail,
userPassword: event.user.userPassword,
userName: _name,
userId: _id,
isLoggedIn: true,
isSignedUp: true)));
if (mounted) {
displaySnackbar(event.context, "success", "Welcome $_name");
}
} else {
emit(UserState(
user: UserModel(
userEmail: event.user.userEmail,
userPassword: event.user.userPassword,
userName: event.user.userName,
userId: event.user.userId,
isLoggedIn: false,
isSignedUp: false)));
if (mounted) {
displaySnackbar(event.context, "error", result);
}
}
}
_signupUser(SignupUser event, Emitter<UserState> emit) async {
String result = await Authentication().signup(event.user);
if (result == 'success') {
emit(UserState(
user: UserModel(
userEmail: event.user.userEmail,
userPassword: event.user.userPassword,
userName: event.user.userName,
userId: event.user.userId,
isLoggedIn: false,
isSignedUp: true)));
} else {
emit(UserState(
user: UserModel(
userEmail: event.user.userEmail,
userPassword: event.user.userPassword,
userName: event.user.userName,
userId: event.user.userId,
isLoggedIn: false,
isSignedUp: false)));
}
}
@override
UserState? fromJson(Map<String, dynamic> json) {
return UserState.fromMap(json);
}
@override
Map<String, dynamic>? toJson(UserState state) {
return state.toMap();
}
}
| 0
|
mirrored_repositories/PokeDoke/lib/blocs/favourite pokemons
|
mirrored_repositories/PokeDoke/lib/blocs/favourite pokemons/bloc/favourites_bloc.dart
|
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:meta/meta.dart';
import 'package:pokedoke/models/pokemons.dart';
import 'dart:convert';
import 'package:pokedoke/widgets/snackbar.dart';
part 'favourites_event.dart';
part 'favourites_state.dart';
bool mounted = true;
class FavouritesBloc extends HydratedBloc<FavouritesEvent, FavouritesState> {
FavouritesBloc() : super(FavouritesState()) {
on<AddToFavourites>(_addToFavourites);
on<DeleteFavourites>(_deleteFavourites);
}
_deleteFavourites(DeleteFavourites event, Emitter<FavouritesState> emit) {
final state = this.state;
var favourites = state.favouritePokemons;
var users = state.uId;
for (int i = 0; i < favourites.length; i++) {
if (favourites[i].isEqual(event.pokemon)) {
favourites.removeAt(i);
users.removeAt(i);
break;
}
}
emit(FavouritesState(favouritePokemons: favourites, uId: users));
}
_addToFavourites(AddToFavourites event, Emitter<FavouritesState> emit) {
final state = this.state;
List<Pokemon> favs = List.from(state.favouritePokemons)..add(event.pokemon);
List<String> users = List.from(state.uId)..add(event.uId);
emit(
FavouritesState(
favouritePokemons: favs,
uId: users
)
);
if (mounted) {
displaySnackbar(event.context, "success", "${event.pokemon.name} has been added to favourites!");
}
}
@override
FavouritesState? fromJson(Map<String, dynamic> json) {
return FavouritesState.fromMap(json);
}
@override
Map<String, dynamic>? toJson(FavouritesState state) {
return state.toMap();
}
}
| 0
|
mirrored_repositories/PokeDoke/lib/blocs/favourite pokemons
|
mirrored_repositories/PokeDoke/lib/blocs/favourite pokemons/bloc/favourites_state.dart
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
part of 'favourites_bloc.dart';
class FavouritesState {
final List<Pokemon> favouritePokemons;
final List<String> uId;
FavouritesState(
{this.favouritePokemons = const <Pokemon>[],
this.uId = const <String>[]});
// Map<String, dynamic> toMap() {
// return <String, dynamic>{
// 'favouritePokemons': favouritePokemons.map((x) => x.toJson()).toList(),
// };
// }
// factory FavouritesState.fromMap(Map<String, dynamic> map) {
// return FavouritesState(
// favouritePokemons: List<Pokemon>.from(map['favouritePokemons']?.map((x) => Pokemon.fromJson(x))),
// );
// }
Map<String, dynamic> toMap() {
return <String, dynamic>{
'favouritePokemons': favouritePokemons.map((x) => x.toJson()).toList(),
'uId': uId,
};
}
factory FavouritesState.fromMap(Map<String, dynamic> map) {
return FavouritesState(
favouritePokemons: List<Pokemon>.from(
map['favouritePokemons']?.map((x) => Pokemon.fromJson(x))),
uId: List<String>.from(map['uId'] as List<String>));
}
}
| 0
|
mirrored_repositories/PokeDoke/lib/blocs/favourite pokemons
|
mirrored_repositories/PokeDoke/lib/blocs/favourite pokemons/bloc/favourites_event.dart
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
part of 'favourites_bloc.dart';
@immutable
abstract class FavouritesEvent {}
class AddToFavourites implements FavouritesEvent {
Pokemon pokemon;
String uId;
BuildContext context;
AddToFavourites({
required this.pokemon,
required this.uId,
required this.context
});
}
class DeleteFavourites implements FavouritesEvent{
Pokemon pokemon;
DeleteFavourites({
required this.pokemon,
});
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/models/pokemons.dart
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:convert';
import 'dart:core';
class Pokemons {
List<Pokemon>? pokemon;
Pokemons({this.pokemon});
Pokemons.fromJson(Map<String, dynamic> json) {
if (json['pokemon'] != null) {
pokemon = <Pokemon>[];
json['pokemon'].forEach((v) {
pokemon!.add(Pokemon.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
if (this.pokemon != null) {
data['pokemon'] = this.pokemon!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Pokemon {
dynamic id;
String? num;
String? name;
String? img;
List<String>? type;
String? height;
String? weight;
String? candy;
String? egg;
dynamic spawnChance;
dynamic avgSpawns;
String? spawnTime;
List<String>? weaknesses;
List<NextEvolution>? nextEvolution;
List<PrevEvolution>? prevEvolution;
Pokemon(
{this.id,
this.num,
this.name,
this.img,
this.type,
this.height,
this.weight,
this.candy,
this.egg,
this.spawnChance,
this.avgSpawns,
this.spawnTime,
this.weaknesses,
this.nextEvolution,
this.prevEvolution});
Pokemon.fromJson(Map<String, dynamic> json) {
id = json['id'];
num = json['num'];
name = json['name'];
img = json['img'];
type = json['type'].cast<String>();
height = json['height'];
weight = json['weight'];
candy = json['candy'];
egg = json['egg'];
spawnChance = json['spawn_chance'];
avgSpawns = json['avg_spawns'];
spawnTime = json['spawn_time'];
weaknesses = json['weaknesses'].cast<String>();
if (json['next_evolution'] != null) {
nextEvolution = <NextEvolution>[];
json['next_evolution'].forEach((v) {
nextEvolution!.add(NextEvolution.fromJson(v));
});
}
if (json['prev_evolution'] != null) {
prevEvolution = <PrevEvolution>[];
json['prev_evolution'].forEach((v) {
prevEvolution!.add(PrevEvolution.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['id'] = this.id;
data['num'] = this.num;
data['name'] = this.name;
data['img'] = this.img;
data['type'] = this.type;
data['height'] = this.height;
data['weight'] = this.weight;
data['candy'] = this.candy;
data['egg'] = this.egg;
data['spawn_chance'] = this.spawnChance;
data['avg_spawns'] = this.avgSpawns;
data['spawn_time'] = this.spawnTime;
data['weaknesses'] = this.weaknesses;
if (this.nextEvolution != null) {
data['next_evolution'] =
this.nextEvolution!.map((v) => v.toJson()).toList();
}
if (this.prevEvolution != null) {
data['prev_evolution'] =
this.prevEvolution!.map((v) => v.toJson()).toList();
}
return data;
}
@override
String toString() {
return 'Pokemon(id: $id, num: $num, name: $name, img: $img, type: $type, height: $height, weight: $weight, candy: $candy, egg: $egg, spawnChance: $spawnChance, avgSpawns: $avgSpawns, spawnTime: $spawnTime, weaknesses: $weaknesses, nextEvolution: $nextEvolution, prevEvolution: $prevEvolution)';
}
bool isEqual(Pokemon other) {
return this.toString() == other.toString();
}
}
class NextEvolution {
String? num;
String? name;
NextEvolution({this.num, this.name});
NextEvolution.fromJson(Map<String, dynamic> json) {
num = json['num'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['num'] = this.num;
data['name'] = this.name;
return data;
}
Map<String, dynamic> toMap() {
return <String, dynamic>{
'num': num,
'name': name,
};
}
factory NextEvolution.fromMap(Map<String, dynamic> map) {
return NextEvolution(
num: map['num'] != null ? map['num'] as String : null,
name: map['name'] != null ? map['name'] as String : null,
);
}
}
class PrevEvolution {
String? num;
String? name;
PrevEvolution({this.num, this.name});
PrevEvolution.fromJson(Map<String, dynamic> json) {
num = json['num'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['num'] = this.num;
data['name'] = this.name;
return data;
}
Map<String, dynamic> toMap() {
return <String, dynamic>{
'num': num,
'name': name,
};
}
factory PrevEvolution.fromMap(Map<String, dynamic> map) {
return PrevEvolution(
num: map['num'] != null ? map['num'] as String : null,
name: map['name'] != null ? map['name'] as String : null,
);
}
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/models/user_model.dart
|
import 'dart:convert';
// ignore_for_file: public_member_api_docs, sort_constructors_first
class UserModel {
String? userId;
String? userName;
String? userEmail;
String? userPassword;
bool isLoggedIn;
bool isSignedUp;
UserModel({
this.userId,
this.userName,
this.userEmail,
this.userPassword,
required this.isLoggedIn,
required this.isSignedUp,
});
Map<String, dynamic> toMap() {
return <String, dynamic>{
'userId': userId,
'userName': userName,
'userEmail': userEmail,
'userPassword': userPassword,
'isLoggedIn': isLoggedIn,
'isSignedUp': isSignedUp,
};
}
factory UserModel.fromMap(Map<String, dynamic> map) {
return UserModel(
userId: map['userId'] != null ? map['userId'] as String : null,
userName: map['userName'] != null ? map['userName'] as String : null,
userEmail: map['userEmail'] != null ? map['userEmail'] as String : null,
userPassword:
map['userPassword'] != null ? map['userPassword'] as String : null,
isLoggedIn: map['isLoggedIn'] as bool,
isSignedUp: map['isSignedUp'] as bool,
);
}
String toJson() => json.encode(toMap());
factory UserModel.fromJson(String source) =>
UserModel.fromMap(json.decode(source) as Map<String, dynamic>);
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/api/pokemon_api_constants.dart
|
var pokeApi = "https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json";
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/api/pokemon_api_methods.dart
|
import 'dart:convert';
import 'package:pokedoke/api/pokemon_api_constants.dart';
import 'package:pokedoke/models/pokemons.dart';
import 'package:http/http.dart' as http;
class ApiService {
Future<Pokemons> getPokemons() async {
var client = http.Client();
var uri = Uri.parse(pokeApi);
var response = await client.get(uri);
if (response.statusCode == 200) {
return Pokemons.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load post');
}
}
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/services/authentications.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:pokedoke/models/user_model.dart';
class Authentication {
final FirebaseAuth _auth = FirebaseAuth.instance;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<String> signup(UserModel user) async {
String msg = "Sign up failed.";
try {
UserCredential credentials = await _auth.createUserWithEmailAndPassword(
email: user.userEmail!,
password: user.userPassword!,
);
if (credentials.user != null) {
user.userId = credentials.user!.uid;
await _firestore.collection('users').doc(credentials.user!.uid).set({
'name': user.userName,
'email': user.userEmail,
'password': user.userPassword,
'id': user.userId,
});
return "success";
}
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
return 'The password is too weak.';
} else if (e.code == 'email-already-in-use') {
return 'The email is already in use.';
}
}
return msg;
}
Future<String> login(UserModel user) async {
String msg = 'An error occured';
try {
await _auth.signInWithEmailAndPassword(email: user.userEmail!, password: user.userPassword!);
return 'success';
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
return 'User not found';
} else if (e.code == 'wrong-password') {
return 'Wrong password';
}
}
return msg;
}
signOut() async {
await _auth.signOut();
}
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/screens/home_screen.dart
|
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pokedoke/api/pokemon_api_methods.dart';
import 'package:pokedoke/blocs/user%20bloc/bloc/user_bloc.dart';
import 'package:pokedoke/constants/colors.dart';
import 'package:pokedoke/database/cloud/firestore_methods.dart';
import 'package:pokedoke/models/pokemons.dart';
import 'package:pokedoke/screens/favourites_screen.dart';
import 'package:pokedoke/services/authentications.dart';
import 'package:pokedoke/widgets/poke_card.dart';
import 'package:pokedoke/widgets/poke_categories_card.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
late Pokemons pokemons;
bool _loading = false;
@override
void initState() {
getData();
super.initState();
}
getData() async {
setState(() {
_loading = true;
});
pokemons = await ApiService().getPokemons();
setState(() {
_loading = false;
});
}
@override
Widget build(BuildContext context) {
return BlocBuilder<UserBloc, UserState>(
builder: (context, state) {
return Scaffold(
backgroundColor: scaffoldBackgroundColor,
drawer: Drawer(
backgroundColor: secondaryColor,
child: Column(
children: [
const SizedBox(
height: 80,
),
CircleAvatar(
radius: 30,
backgroundColor: scaffoldBackgroundColor,
child: Text(
state.user.userName![0],
style: TextStyle(
color: secondaryColor,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.center,
),
),
const SizedBox(
height: 16,
),
Text(
state.user.userName!,
style:
TextStyle(fontSize: 16, color: scaffoldBackgroundColor),
),
ListTile(
tileColor: secondaryColor,
onTap: () {
Navigator.of(context).pop();
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => FavouritePokemonsScreen())
);
},
leading: Icon(
Icons.favorite,
color: scaffoldBackgroundColor,
),
title: Text("View Favourites", style: TextStyle(color: scaffoldBackgroundColor),),
),
ListTile(
tileColor: secondaryColor,
onTap: () {
context.read<UserBloc>().add(LogoutUser());
},
leading: Icon(
Icons.logout,
color: scaffoldBackgroundColor,
),
title: Text("Log out?", style: TextStyle(color: scaffoldBackgroundColor),),
),
],
),
),
appBar: AppBar(
backgroundColor: scaffoldBackgroundColor,
toolbarHeight: 100,
iconTheme: IconThemeData(
size: 25,
color: secondaryColor,
),
title: Text(
"PokeDoke",
style: TextStyle(
color: secondaryColor
),
),
centerTitle: true,
elevation: 0,
),
body: _loading
? Center(
child: CircularProgressIndicator(
color: secondaryColor,
),
)
: Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
children: [
const SizedBox(height: 30,),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Wrap(
spacing: 6,
children: [
CategoryCard(
image: "pikachu.jpg",
title: "Electric",
onPressed: (){},
),
CategoryCard(
image: "charizard.jpg",
title: "Fire",
onPressed: (){},
),
CategoryCard(
image: "mewtwo.jpg",
title: "Psychic",
onPressed: (){},
),
CategoryCard(
image: "water.jpg",
title: "Water",
onPressed: (){},
),
CategoryCard(
image: "poison.jpg",
title: "Poison",
onPressed: (){},
),
CategoryCard(
image: "rockPokemon.jpg",
title: "Rock",
onPressed: (){},
),
CategoryCard(
image: "ghost.jpg",
title: "Ghost",
onPressed: (){},
),
],
),
),
const SizedBox(height: 30,),
GridView.builder(
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, childAspectRatio: 1.4),
itemCount: pokemons.pokemon!.length,
shrinkWrap: true,
// scrollDirection: Axis.vertical,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return PokeCard(
pokemon: pokemons.pokemon![index],
);
}),
],
),
),
));
},
);
}
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/screens/signup_screen.dart
|
import 'package:awesome_snackbar_content/awesome_snackbar_content.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:pokedoke/blocs/user%20bloc/bloc/user_bloc.dart';
import 'package:pokedoke/constants/colors.dart';
import 'package:pokedoke/models/user_model.dart';
import 'package:pokedoke/screens/login_screen.dart';
import 'package:string_validator/string_validator.dart';
class SignupScreen extends StatefulWidget {
const SignupScreen({super.key});
@override
State<SignupScreen> createState() => _SignupScreenState();
}
class _SignupScreenState extends State<SignupScreen> {
final _signupFormKey = GlobalKey<FormBuilderState>();
@override
Widget build(BuildContext context) {
return BlocListener<UserBloc, UserState>(
listener: (context, state) {
if (state.user.isSignedUp) {
final snackBar = SnackBar(
/// need to set following properties for best effect of awesome_snackbar_content
elevation: 0,
behavior: SnackBarBehavior.floating,
backgroundColor: Colors.transparent,
content: AwesomeSnackbarContent(
title: 'Congratulations',
message: "You have successfully signed up!",
/// change contentType to ContentType.success, ContentType.warning or ContentType.help for variants
contentType: ContentType.success,
),
);
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(snackBar);
} else {
if (state.user.isSignedUp) {
final snackBar = SnackBar(
/// need to set following properties for best effect of awesome_snackbar_content
elevation: 0,
behavior: SnackBarBehavior.floating,
backgroundColor: Colors.transparent,
content: AwesomeSnackbarContent(
title: 'Oops!',
message: "An error occured!",
contentType: ContentType.failure,
),
);
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(snackBar);
}
}
},
child: Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: scaffoldBackgroundColor,
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
children: [
const SizedBox(
height: 70,
),
Align(
alignment: Alignment.topLeft,
child: Text(
"Sign up",
style: TextStyle(
color: secondaryColor,
fontSize: 32,
fontWeight: FontWeight.w700),
),
),
const SizedBox(
height: 60,
),
FormBuilder(
key: _signupFormKey,
child: Column(
children: [
FormBuilderTextField(
name: 'nameField',
cursorColor: secondaryColor,
textCapitalization: TextCapitalization.sentences,
decoration: InputDecoration(
labelText: 'Name',
hintText: 'Enter your name',
labelStyle: TextStyle(
color: secondaryColor,
fontSize: 16,
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondaryColor),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondaryColor),
),
),
validator: (value) {
if (value == null) {
return "Field is required.";
}
if (isAlpha(value)) {
return "Only Alphabets are allowed.";
}
return null;
},
),
const SizedBox(
height: 30,
),
FormBuilderTextField(
name: 'emailField',
cursorColor: secondaryColor,
textCapitalization: TextCapitalization.sentences,
decoration: InputDecoration(
labelText: 'Email',
hintText: 'Enter your email',
labelStyle: TextStyle(
color: secondaryColor,
fontSize: 16,
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondaryColor),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondaryColor),
),
),
validator: FormBuilderValidators.compose([
FormBuilderValidators.email(),
FormBuilderValidators.required()
]),
),
const SizedBox(
height: 30,
),
FormBuilderTextField(
name: 'passwordField',
cursorColor: secondaryColor,
obscureText: true,
decoration: InputDecoration(
labelText: 'Password',
hintText: 'Enter your password',
labelStyle: TextStyle(
color: secondaryColor,
fontSize: 16,
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondaryColor),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondaryColor),
),
),
validator: FormBuilderValidators.compose([
FormBuilderValidators.minLength(8),
FormBuilderValidators.required()
]),
),
const SizedBox(
height: 30,
),
BlocListener<UserBloc, UserState>(
listener: (context, state) {},
child: SizedBox(
width: MediaQuery.of(context).size.width,
child: ElevatedButton(
onPressed: () async {
if (_signupFormKey.currentState!
.validate()) {
context.read<UserBloc>().add(SignupUser(
user: UserModel(
userName: _signupFormKey
.currentState!
.fields['nameField']!
.value,
userEmail: _signupFormKey
.currentState!
.fields['emailField']!
.value,
userPassword: _signupFormKey
.currentState!
.fields['passwordField']!
.value,
isSignedUp: false,
isLoggedIn: false)));
}
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(
secondaryColor)),
child: const Text(
"Sign up!",
style: TextStyle(fontSize: 16),
))),
),
],
)),
SizedBox(
height: MediaQuery.of(context).size.height * 0.32,
),
GestureDetector(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => LoginScreen()));
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Text("Already have an account? "),
Text(
"Login!",
style:
TextStyle(decoration: TextDecoration.underline),
)
],
),
),
],
),
),
)),
);
}
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/screens/poke_details_screen.dart
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pokedoke/blocs/favourite%20pokemons/bloc/favourites_bloc.dart';
import 'package:pokedoke/blocs/user%20bloc/bloc/user_bloc.dart';
import 'package:pokedoke/constants/colors.dart';
import 'package:pokedoke/models/pokemons.dart';
class PokeDetailsScreen extends StatefulWidget {
final Pokemon pokemon;
final Color color;
const PokeDetailsScreen(
{required this.color, required this.pokemon, super.key});
@override
State<PokeDetailsScreen> createState() => _PokeDetailsScreenState();
}
class _PokeDetailsScreenState extends State<PokeDetailsScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: widget.color,
appBar: AppBar(
backgroundColor: widget.color,
elevation: 0,
leading: IconButton(
icon: Icon(
Icons.arrow_back_ios,
color: scaffoldBackgroundColor,
),
onPressed: () {
Navigator.of(context).pop();
},
),
),
body: Stack(
children: [
Positioned(
top: 30,
left: 30,
child: Column(
children: [
Text(
widget.pokemon.name!,
style: TextStyle(
fontSize: 26,
fontWeight: FontWeight.w600,
color: scaffoldBackgroundColor),
),
Text(widget.pokemon.type![0],
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
color: scaffoldBackgroundColor))
],
),
),
Positioned(
bottom: 0,
// This is the main info container
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height * 0.6,
decoration: BoxDecoration(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30)),
color: scaffoldBackgroundColor),
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
children: [
const SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text("Height"),
Text(widget.pokemon.height!)
],
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text("Weight"),
Text(widget.pokemon.weight!)
],
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text("Weakness"),
Text(widget.pokemon.weaknesses!.join(", "))
],
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text("Poke ID"),
Text(widget.pokemon.id.toString())
],
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text("Spawn chances"),
Text(widget.pokemon.spawnChance.toString())
],
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text("Egg"),
Text(widget.pokemon.egg.toString())
],
),
Expanded(child: Container()),
BlocBuilder<UserBloc, UserState>(builder: (context, state) {
return SizedBox(
width: MediaQuery.of(context).size.width,
child: ElevatedButton(
onPressed: () {
context.read<FavouritesBloc>().add(
AddToFavourites(
pokemon: widget.pokemon,
uId: state.user.userId!,
context: context));
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(
widget.color)),
child: const Text(
"Add to favourites!",
style: TextStyle(fontWeight: FontWeight.w600),
),
));
})
],
),
),
),
),
Positioned(
top: MediaQuery.of(context).size.height * 0.17,
left: MediaQuery.of(context).size.width * 0.35,
child: CachedNetworkImage(
imageUrl: widget.pokemon.img!,
height: 130,
fit: BoxFit.fitHeight,
)),
],
),
);
}
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/screens/login_screen.dart
|
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:pokedoke/blocs/user%20bloc/bloc/user_bloc.dart';
import 'package:pokedoke/constants/colors.dart';
import 'package:pokedoke/database/cloud/firestore_methods.dart';
import 'package:pokedoke/models/user_model.dart';
import 'package:pokedoke/screens/signup_screen.dart';
import 'package:pokedoke/services/authentications.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final _loginFormKey = GlobalKey<FormBuilderState>();
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: scaffoldBackgroundColor,
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
children: [
const SizedBox(
height: 70,
),
Align(
alignment: Alignment.topLeft,
child: Text(
"Login",
style: TextStyle(
color: secondaryColor,
fontSize: 32,
fontWeight: FontWeight.w700),
),
),
const SizedBox(
height: 60,
),
FormBuilder(
key: _loginFormKey,
child: Column(
children: [
FormBuilderTextField(
name: 'emailField',
cursorColor: secondaryColor,
textCapitalization: TextCapitalization.sentences,
decoration: InputDecoration(
labelText: 'Email',
hintText: 'Enter your email',
labelStyle: TextStyle(
color: secondaryColor,
fontSize: 16,
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondaryColor),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondaryColor),
),
),
validator: FormBuilderValidators.compose([
FormBuilderValidators.email(),
FormBuilderValidators.required()
]),
),
const SizedBox(
height: 30,
),
FormBuilderTextField(
name: 'passwordField',
cursorColor: secondaryColor,
obscureText: true,
decoration: InputDecoration(
labelText: 'Password',
hintText: 'Enter your password',
labelStyle: TextStyle(
color: secondaryColor,
fontSize: 16,
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondaryColor),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondaryColor),
),
),
validator: FormBuilderValidators.compose([
FormBuilderValidators.minLength(8),
FormBuilderValidators.required()
])),
const SizedBox(
height: 30,
),
SizedBox(
width: MediaQuery.of(context).size.width,
child: ElevatedButton(
onPressed: () async {
if (_loginFormKey.currentState!.validate()) {
print("Here");
context.read<UserBloc>().add(LoginUser(
context: context,
user: UserModel(
isLoggedIn: true,
isSignedUp: true,
userEmail: _loginFormKey.currentState!
.fields['emailField']!.value,
userPassword: _loginFormKey
.currentState!
.fields['passwordField']!
.value,
// userName: await getUserName(FirebaseAuth
// .instance.currentUser!.uid),
)));
print("Here 2");
} else {}
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(
secondaryColor)),
child: const Text(
"Login",
style: TextStyle(fontSize: 16),
))),
],
)),
SizedBox(
height: MediaQuery.of(context).size.height * 0.43,
),
GestureDetector(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const SignupScreen()));
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Text("Don't have an account? "),
Text(
"Sign up!",
style: TextStyle(decoration: TextDecoration.underline),
)
],
),
),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/PokeDoke/lib
|
mirrored_repositories/PokeDoke/lib/screens/favourites_screen.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pokedoke/blocs/favourite%20pokemons/bloc/favourites_bloc.dart';
import 'package:pokedoke/blocs/user%20bloc/bloc/user_bloc.dart';
import 'package:pokedoke/constants/colors.dart';
import 'package:pokedoke/global/global_methods.dart';
import 'package:pokedoke/widgets/favourite_pokemon_tile.dart';
class FavouritePokemonsScreen extends StatefulWidget {
const FavouritePokemonsScreen({super.key});
@override
State<FavouritePokemonsScreen> createState() =>
_FavouritePokemonsScreenState();
}
class _FavouritePokemonsScreenState extends State<FavouritePokemonsScreen> {
@override
Widget build(BuildContext context) {
return BlocBuilder<FavouritesBloc, FavouritesState>(
builder: (context, state) {
var favPokemonsAll = state.favouritePokemons;
var users = state.uId;
String currentUser = context.read<UserBloc>().state.user.userId!;
var favPokemons = getFilteredFavourites(favPokemonsAll, users, currentUser);
return Scaffold(
backgroundColor: scaffoldBackgroundColor,
appBar: AppBar(
iconTheme: IconThemeData(
size: 25,
color: secondaryColor,
),
backgroundColor: scaffoldBackgroundColor,
elevation: 0,
title: Text("Favourite Pokemons", style: TextStyle(color: secondaryColor),),
centerTitle: true,
),
body: Padding(
padding: EdgeInsets.all(18),
child: Column(
children: [
ListView.builder(
shrinkWrap: true,
itemCount: favPokemons.length,
itemBuilder: (context, index) {
return FavouritePokemonTile(
pokemon: favPokemons[index],
);
},
)
],
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/PokeDoke
|
mirrored_repositories/PokeDoke/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pokedoke/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/FirebaseProducts
|
mirrored_repositories/FirebaseProducts/lib/main.dart
|
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:productos/home/Home.dart';
import 'package:productos/login/Login.dart';
import 'package:firebase_auth/firebase_auth.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Productos',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: FirebaseAuth.instance.currentUser != null
? Home(
user: FirebaseAuth.instance.currentUser,
)
: Login(),
);
}
}
| 0
|
mirrored_repositories/FirebaseProducts/lib
|
mirrored_repositories/FirebaseProducts/lib/addProduct/addProduct.dart
|
import 'package:flutter/material.dart';
import 'FormAdd.dart';
// ignore: must_be_immutable
class AddProduct extends StatelessWidget {
Function callbackInsert;
AddProduct({
Key key,
this.callbackInsert,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
title: Text('Agregar producto'),
backgroundColor: Colors.purple,
iconTheme: IconThemeData(color: Colors.white),
),
body: SafeArea(
child:
ListView(padding: EdgeInsets.symmetric(vertical: 8.0), children: [
FormAdd(callbackInsert: callbackInsert),
]),
));
}
}
| 0
|
mirrored_repositories/FirebaseProducts/lib
|
mirrored_repositories/FirebaseProducts/lib/addProduct/FormAdd.dart
|
import 'package:flutter/material.dart';
int resultId;
// ignore: must_be_immutable
class FormAdd extends StatefulWidget {
Function callbackInsert;
FormAdd({Key key, this.callbackInsert});
@override
ContentForm createState() => ContentForm();
}
Widget _boxTextField(String placeholder, TextEditingController controllerText,
TextInputType typeData, int maxlines) =>
TextFormField(
controller: controllerText,
validator: (value) {
if (typeData == TextInputType.number) {
if (value.isEmpty) {
return "Rellene el campo";
} else {
switch (placeholder) {
case 'Cantidad':
var valueData = int.tryParse(value);
return (value.length > 18)
? "Maximo 17 caracteres"
: ((valueData == null) ? "Digite un numero entero" : null);
break;
case 'Precio':
var valueData = double.tryParse(value);
return (value.length > 18)
? "Maximo 17 caracteres"
: ((valueData == null) ? "Digite un numero decimal" : null);
break;
}
}
} else {
return (value.trim().isEmpty) ? 'Rellena el campo' : null;
}
return null;
},
style: TextStyle(
fontSize: 20,
),
minLines: 1,
maxLines: maxlines,
decoration: InputDecoration(labelText: placeholder),
textAlign: TextAlign.center,
keyboardType: typeData,
);
class ContentForm extends State<FormAdd> {
final _formKey = GlobalKey<FormState>();
String titleAvatar = "";
Map<String, TextEditingController> controllerForm = {
"name": TextEditingController(),
"price": TextEditingController(),
"detailarticle": TextEditingController(),
"amount": TextEditingController()
};
void _changedCircleAvatarName(String val) {
setState(() {
titleAvatar = (val != "") ? val[0].toUpperCase() : "";
});
}
void _returnMainPage(BuildContext context) {
Navigator.of(context).pop(this);
}
_insertDB() {
Map<String, dynamic> data = {
'name': controllerForm['name'].text,
'price': double.tryParse(controllerForm['price'].text),
'detail': controllerForm['detailarticle'].text,
'amount': int.tryParse(controllerForm['amount'].text)
};
widget.callbackInsert(data);
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Container(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
color: Colors.purple[900],
child: CircleAvatar(
backgroundColor: Colors.white,
maxRadius: 50.0,
child: Text(
titleAvatar,
style: TextStyle(fontSize: 40, color: Colors.black),
),
)),
SizedBox(
height: 10,
),
TextFormField(
controller: controllerForm['name'],
onChanged: (String val) => {
if ((val.trim()).length <= 1)
{
_changedCircleAvatarName(val.trim()),
}
},
validator: (value) {
return (value.trim().isEmpty)
? 'Rellena el campo'
: ((value.length > 29) ? "Maximo 29 caracteres" : null);
},
style: TextStyle(
fontSize: 20,
),
decoration: InputDecoration(labelText: "Nombre"),
textAlign: TextAlign.center,
keyboardType: TextInputType.text,
),
SizedBox(
height: 10,
),
_boxTextField(
"Precio", controllerForm['price'], TextInputType.number, 1),
SizedBox(
height: 10,
),
_boxTextField("Detalle del producto",
controllerForm['detailarticle'], TextInputType.text, 5),
SizedBox(
height: 10,
),
_boxTextField("Cantidad", controllerForm['amount'],
TextInputType.number, 1),
SizedBox(
height: 10,
),
RaisedButton(
color: Colors.purple[700],
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
15.0,
),
),
child: Text(
'Registrar',
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
onPressed: () => {
if (_formKey.currentState.validate())
{
_insertDB(),
}
},
),
RaisedButton(
color: Colors.pink,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
15.0,
),
),
child: Text(
'Cancelar',
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
onPressed: () => {_returnMainPage(context)},
),
],
)),
//)
),
);
}
}
| 0
|
mirrored_repositories/FirebaseProducts/lib
|
mirrored_repositories/FirebaseProducts/lib/updateProduct/updateProduct.dart
|
import 'package:flutter/material.dart';
import 'package:productos/updateProduct/FormUpdate.dart';
// ignore: must_be_immutable
class UpdateProduct extends StatefulWidget {
final Map<String, dynamic> dataMainPage;
Function callbackUpdate;
UpdateProduct({
Key key,
this.dataMainPage,
this.callbackUpdate,
}) : super(key: key);
@override
_UpdateProductState createState() => _UpdateProductState();
}
class _UpdateProductState extends State<UpdateProduct> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
title: Text('Actualizar producto'),
backgroundColor: Colors.purple,
iconTheme: IconThemeData(color: Colors.white),
),
body: SafeArea(
child:
ListView(padding: EdgeInsets.symmetric(vertical: 8.0), children: [
FormUpdate(
dataArticle: widget.dataMainPage,
callbackUpdate: widget.callbackUpdate,
),
]),
));
}
}
| 0
|
mirrored_repositories/FirebaseProducts/lib
|
mirrored_repositories/FirebaseProducts/lib/updateProduct/FormUpdate.dart
|
import 'package:flutter/material.dart';
import 'package:productos/models/Product.dart';
// ignore: must_be_immutable
class FormUpdate extends StatefulWidget {
final Map<String, dynamic> dataArticle;
Function callbackUpdate;
FormUpdate({Key key, this.dataArticle, this.callbackUpdate})
: super(key: key);
@override
ContentForm createState() => ContentForm();
}
Widget _boxTextField(String placeholder, TextEditingController controllerText,
TextInputType typeData, bool isEnabled, int maxlines) =>
TextFormField(
controller: controllerText,
validator: (value) {
if (typeData == TextInputType.number) {
if (value.isEmpty) {
return "Rellene el campo";
} else {
switch (placeholder) {
case 'Cantidad':
var valueData = int.tryParse(value);
return (value.length > 18)
? "Maximo 17 caracteres"
: ((valueData == null) ? "Digite un numero entero" : null);
break;
case 'Precio':
var valueData = double.tryParse(value);
return (value.length > 18)
? "Maximo 17 caracteres"
: ((valueData == null) ? "Digite un numero decimal" : null);
break;
}
}
} else {
return (value.trim().isEmpty) ? 'Rellena el campo' : null;
}
return null;
},
style: TextStyle(
fontSize: 20,
),
minLines: 1,
maxLines: maxlines,
decoration: InputDecoration(labelText: placeholder),
textAlign: TextAlign.center,
keyboardType: typeData,
enabled: isEnabled,
);
class ContentForm extends State<FormUpdate> {
final _formKey = GlobalKey<FormState>();
String titleAvatar = "";
Map<String, TextEditingController> controllerForm = {
"id": TextEditingController(),
"name": TextEditingController(),
"price": TextEditingController(),
"detail": TextEditingController(),
"amount": TextEditingController()
};
void initState() {
super.initState();
titleAvatar = ("${widget.dataArticle['name'][0]}".toString()).toUpperCase();
controllerForm['name'].text = "${widget.dataArticle['name']}";
controllerForm['id']..text = "${widget.dataArticle['id']}";
controllerForm['price']..text = "${widget.dataArticle['price']}";
controllerForm['detail']..text = "${widget.dataArticle['detail']}";
controllerForm['amount']..text = "${widget.dataArticle['amount']}";
controllerForm['name'].addListener(() {
final text = controllerForm['name'].text.toLowerCase();
controllerForm['name'].value = controllerForm['name'].value.copyWith(
text: text,
selection: TextSelection(
baseOffset: text.length, extentOffset: text.length),
composing: TextRange.empty,
);
});
}
void _changedCircleAvatarName(String val) {
setState(() {
titleAvatar = (val != "") ? val[0].toUpperCase() : "";
});
}
void _returnMainPage(BuildContext context) {
Navigator.of(context).pop(this);
}
void _updateProduct(BuildContext context) {
var product = Product(
id: controllerForm['id'].text,
name: controllerForm['name'].text.trim(),
price: double.tryParse(controllerForm['price'].text),
detail: controllerForm['detail'].text,
amount: int.tryParse(controllerForm['amount'].text));
widget.callbackUpdate(product);
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Container(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
color: Colors.purple[900],
child: CircleAvatar(
backgroundColor: Colors.white,
maxRadius: 50.0,
child: Text(
titleAvatar,
style: TextStyle(fontSize: 40, color: Colors.black),
),
)),
_boxTextField("Clave", controllerForm['id'], TextInputType.text,
false, 1),
SizedBox(
height: 10,
),
TextFormField(
controller: controllerForm['name'],
onChanged: (String val) => {
if ((val.trim()).length <= 1)
{
_changedCircleAvatarName(val.trim()),
}
},
validator: (value) {
return (value.trim().isEmpty)
? 'Rellena el campo'
: ((value.length > 29) ? "Maximo 29 caracteres" : null);
},
style: TextStyle(
fontSize: 20,
),
decoration: const InputDecoration(
labelText: "Nombre",
),
textAlign: TextAlign.center,
keyboardType: TextInputType.text,
),
SizedBox(
height: 10,
),
_boxTextField("Precio", controllerForm['price'],
TextInputType.number, true, 1),
SizedBox(
height: 10,
),
_boxTextField("Detalle del producto", controllerForm['detail'],
TextInputType.text, true, 5),
SizedBox(
height: 10,
),
_boxTextField("Cantidad", controllerForm['amount'],
TextInputType.number, true, 1),
SizedBox(
height: 10,
),
RaisedButton(
color: Colors.purple[700],
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
15.0,
),
),
child: Text(
'Actualizar',
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
onPressed: () => {
if (_formKey.currentState.validate())
{
print('actualizando...'),
_updateProduct(context),
}
else
{print('error en la actualización')}
},
),
RaisedButton(
color: Colors.pink,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
15.0,
),
),
child: Text(
'Cancelar',
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
onPressed: () => {_returnMainPage(context)},
),
],
)),
//)
),
);
}
}
| 0
|
mirrored_repositories/FirebaseProducts/lib
|
mirrored_repositories/FirebaseProducts/lib/models/Product.dart
|
class Product {
final String id;
final String name;
final double price;
final String detail;
final int amount;
Product({this.id, this.name, this.price, this.detail, this.amount});
Map<String, dynamic> toMap() {
return {
"name": name,
"price": price,
"detail": detail,
"amount": amount,
};
}
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
id: json['id'],
name: json['name'],
price: json['price'],
detail: json['detail'],
amount: json['amount']);
}
}
| 0
|
mirrored_repositories/FirebaseProducts/lib
|
mirrored_repositories/FirebaseProducts/lib/login/Login.dart
|
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/services.dart';
import 'package:productos/home/Home.dart';
import 'package:productos/register/Register.dart';
class Login extends StatefulWidget {
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
final Color _primaryColor = Color(0xff18203d);
final Color _secondaryColor = Color(0xff232c51);
final Color _logoGreen = Color(0xff25bcbb);
final _auth = FirebaseAuth.instance;
final _formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
final _scaffKey = GlobalKey<ScaffoldState>();
bool isProcessingQuery = false;
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffKey,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
title: Center(
child: Text(
'Login',
style: TextStyle(
fontSize: 28,
color: Colors.white,
),
),
),
),
backgroundColor: _primaryColor,
body: Form(
key: _formKey,
child: Container(
margin: EdgeInsets.symmetric(horizontal: 20),
child: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 20,
),
_buildField(_emailController, Icons.email, 'Email',
keyboardType: TextInputType.emailAddress),
SizedBox(
height: 20,
),
_buildField(_passwordController, Icons.lock, 'Contraseña',
obscureText: true),
SizedBox(
height: 40,
),
MaterialButton(
minWidth: double.maxFinite,
height: 50,
color: _logoGreen,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
child: isProcessingQuery
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(
backgroundColor: Colors.white,
),
SizedBox(
width: 20.0,
),
Text('Acceder',
style: TextStyle(
color: Colors.white, fontSize: 16)),
],
)
: Text('Acceder',
style: TextStyle(color: Colors.white, fontSize: 16)),
onPressed: () {
if (_formKey.currentState.validate() &&
!isProcessingQuery) {
print('Empezando consulta');
setState(() {
isProcessingQuery = true;
});
_signInWithEmailAndPassword();
}
},
),
SizedBox(height: 20),
MaterialButton(
minWidth: double.maxFinite,
height: 50,
color: Colors.blue,
disabledColor: Colors.blue[400],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
child: Text('Crear nueva cuenta',
style: TextStyle(color: Colors.white, fontSize: 16)),
onPressed: isProcessingQuery
? null
: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => Register()));
},
onLongPress: null,
),
],
),
),
),
),
);
}
_buildField(TextEditingController controller, IconData icon, String labelText,
{TextInputType keyboardType = TextInputType.text,
bool obscureText = false}) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: _secondaryColor, border: Border.all(color: Colors.blue)),
child: TextFormField(
keyboardType: keyboardType,
obscureText: obscureText,
controller: controller,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(horizontal: 10),
labelText: labelText,
labelStyle: TextStyle(color: Colors.white),
icon: Icon(
icon,
color: Colors.white,
),
border: InputBorder.none),
validator: (value) {
if (value.trim().isEmpty) {
return 'Escribe tu $labelText';
}
return null;
},
),
);
}
_signInWithEmailAndPassword() async {
try {
UserCredential user = await _auth.signInWithEmailAndPassword(
email: _emailController.text.trim(),
password: _passwordController.text.trim(),
);
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (_) => Home(
user: user.user,
),
));
} on FirebaseAuthException catch (e) {
print('Datos incorrectos...');
if (e.code == 'invalid-email')
_showMessage(
'La dirección email no tiene un formato valido. Debe de contener "@"');
else if (e.code == 'user-not-found')
_showMessage(
'Nose encontro ninguna cuenta registrada con este email. Verifique su email');
else if (e.code == 'wrong-password')
_showMessage('La contraseña es incorrecta');
else if (e.code == 'too-many-requests')
_showMessage('Demasiados intentos fallidos. Intentar mas tarde');
else if (e.code == 'unknown')
_showMessage(
'No se pudo establecer conexión con el servidor. Compruebe su conexión a Internet.');
else
_showMessage('Mensaje: ${e.message}. Codigo: ${e.code}');
} catch (e) {
_showMessage('Error desconocido');
print(e);
} finally {
print('Fin consulta');
setState(() {
isProcessingQuery = false;
});
}
}
void _showMessage(String msg) {
_scaffKey.currentState.hideCurrentSnackBar();
_scaffKey.currentState.showSnackBar(SnackBar(
duration: Duration(seconds: 15),
backgroundColor: Colors.amberAccent,
content: Text(
msg,
style: TextStyle(
fontSize: 20,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
));
}
}
| 0
|
mirrored_repositories/FirebaseProducts/lib
|
mirrored_repositories/FirebaseProducts/lib/home/Home.dart
|
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:productos/home/CreateComponent.dart';
import 'package:productos/addProduct/addProduct.dart';
import 'package:productos/login/Login.dart';
import 'package:productos/models/Product.dart';
import 'package:productos/services/FirestoreService.dart';
class Home extends StatefulWidget {
final User user;
Home({this.user});
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
FirestoreService firestoreService = FirestoreService();
Route _handleNavigationPressed() {
return PageRouteBuilder(
transitionDuration: const Duration(
milliseconds: 500,
),
pageBuilder: (context, animation, secondaryAnimation) => AddProduct(
callbackInsert: callbackInsert,
),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
var tween = Tween<Offset>(begin: Offset(0.0, 1.0), end: Offset.zero)
.chain(CurveTween(curve: Curves.ease));
return SlideTransition(
position: animation.drive(tween),
child: child,
);
},
);
}
void callbackDelete(String id) {
setState(() {
firestoreService.deleteProduct(id);
});
}
void callbackInsert(Map<String, dynamic> data) {
setState(() {
firestoreService.addProduct(data);
});
}
void callbackUpdate(Product data) {
setState(() {
firestoreService.updateProduct(data);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(
child: Text(widget.user.displayName),
),
actions: [
DropdownButton<String>(
style: TextStyle(
color: Colors.white,
fontSize: 18,
),
dropdownColor: Color(0xff18203d),
underline: Container(
color: Colors.transparent,
),
icon: Icon(
Icons.more_vert,
color: Colors.white,
size: 30,
),
items: <String>['Cerrar Sesión']
.map<DropdownMenuItem<String>>((e) => DropdownMenuItem<String>(
child: Text(e),
value: e,
))
.toList(),
onChanged: (value) {
if (value == 'Cerrar Sesión') {
FirebaseAuth.instance.signOut().then((value) =>
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => Login())));
}
},
)
],
),
body: SafeArea(
child: StreamBuilder(
stream:
FirebaseFirestore.instance.collection('productos').snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
if (snapshot.data.size != 0) {
List<DocumentSnapshot> docs = snapshot.data.docs;
return ListView.builder(
padding:
EdgeInsets.symmetric(horizontal: 10.0, vertical: 15.0),
itemCount: docs.length,
itemBuilder: (context, index) {
return CreateComponent(
dataComponent: <String, dynamic>{
'id': docs[index].id,
...docs[index].data()
},
callbackDelete: callbackDelete,
callbackUpdate: callbackUpdate,
);
});
}
return Center(child: Text('No se han agregado datos.'));
}
return Center(
child: CircularProgressIndicator(),
);
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).push(_handleNavigationPressed());
},
backgroundColor: Colors.pink[600],
tooltip: 'Agregar producto',
child: Icon(Icons.add),
),
);
}
}
| 0
|
mirrored_repositories/FirebaseProducts/lib
|
mirrored_repositories/FirebaseProducts/lib/home/CreateComponent.dart
|
import 'package:flutter/material.dart';
import 'package:productos/updateProduct/updateProduct.dart';
// ignore: must_be_immutable
class CreateComponent extends StatefulWidget {
final Map<String, dynamic> dataComponent;
Function callbackDelete;
Function callbackUpdate;
CreateComponent(
{Key key, this.dataComponent, this.callbackDelete, this.callbackUpdate})
: super(key: key);
@override
State<StatefulWidget> createState() => _CreateComponentState();
}
class _CreateComponentState extends State<CreateComponent> {
Widget _customText(String texto, FontWeight fontWeight, double fontsize) =>
Text(
texto,
textAlign: TextAlign.justify,
style: TextStyle(
fontSize: fontsize,
fontWeight: fontWeight,
),
maxLines: 3,
overflow: TextOverflow.ellipsis,
softWrap: false,
);
Widget dividerColumnText() => Divider(
color: Colors.blue[300],
height: 10,
thickness: 2,
);
Route _handleNavigationPressedUpdate() {
return PageRouteBuilder(
transitionDuration: const Duration(
milliseconds: 500,
),
pageBuilder: (context, animation, secondaryAnimation) => UpdateProduct(
dataMainPage: widget.dataComponent,
callbackUpdate: widget.callbackUpdate),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
var tween = Tween<Offset>(begin: Offset(0.0, 1.0), end: Offset.zero)
.chain(CurveTween(curve: Curves.ease));
return SlideTransition(
position: animation.drive(tween),
child: child,
);
},
);
}
_updateComponent(BuildContext context) {
widget.callbackDelete(widget.dataComponent['id']);
Navigator.pop(context);
}
_deleteProduct(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return SimpleDialog(
children: [
Padding(
padding: EdgeInsets.only(left: 15.0, right: 15.0, top: 15.0),
child: Column(
children: [
Center(
child: Text(
"¿Esta seguro que desea eliminar este producto?",
textAlign: TextAlign.center,
)),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
RaisedButton(
color: Colors.blue[400],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
15.0,
),
),
child: Text(
'Si',
style: TextStyle(
fontSize: 10,
color: Colors.white,
),
),
onPressed: () => {_updateComponent(context)},
),
RaisedButton(
color: Colors.blue[400],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
15.0,
),
),
child: Text(
'No',
style: TextStyle(
fontSize: 10,
color: Colors.white,
),
),
onPressed: () => {
Navigator.pop(context),
},
),
],
),
],
),
)
],
);
});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
GestureDetector(
child: Container(
color: Colors.purple[900],
child: Column(children: [
SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Flexible(
flex: 10,
child: CircleAvatar(
backgroundColor: Colors.white,
maxRadius: 60.0,
child: Text(
"${widget.dataComponent['name'][0]}".toUpperCase(),
style: TextStyle(fontSize: 70.0, color: Colors.black),
),
),
),
Spacer(
flex: 1,
),
Flexible(
flex: 15,
child: Container(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: _customText(
" id: ${widget.dataComponent['id']}",
FontWeight.bold,
14),
),
Flexible(
child: IconButton(
color: Colors.red,
iconSize: 35,
icon: Icon(Icons.cancel),
onPressed: () {
_deleteProduct(context);
}),
),
],
),
dividerColumnText(),
_customText(" ${widget.dataComponent['name']}",
FontWeight.bold, 18),
dividerColumnText(),
_customText(" \$${widget.dataComponent['price']}",
FontWeight.normal, 17),
dividerColumnText(),
_customText(
" Detalle: ${widget.dataComponent['detail']}",
FontWeight.normal,
17),
dividerColumnText(),
_customText(
" Cantidad: ${widget.dataComponent['amount']}",
FontWeight.normal,
17),
SizedBox(
height: 15,
),
],
),
),
//),
),
),
],
),
SizedBox(
height: 15,
),
]),
),
onTap: () {
Navigator.of(context).push(_handleNavigationPressedUpdate());
},
),
SizedBox(
height: 8,
),
],
);
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.