repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/Flutter-Weather-App-Bloc/lib
mirrored_repositories/Flutter-Weather-App-Bloc/lib/bloc/weather_bloc.dart
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:geolocator/geolocator.dart'; import 'package:meta/meta.dart'; import 'package:weather/weather.dart'; import 'package:weather_app_bloc_1/data/my_data.dart'; part 'weather_event.dart'; part 'weather_state.dart'; class WeatherBloc extends Bloc<WeatherBlocEvent, WeatherBlocState> { WeatherBloc() : super(WeatherInitial()) { on<FetchWeather>((event, emit) async { emit(WeatherBlocLoading()); try { WeatherFactory wf = WeatherFactory(API_KEY, language: Language.VIETNAMESE); Weather weather = await wf.currentWeatherByLocation( event.position.latitude, event.position.longitude); print(weather); emit(WeatherBlocSuccess(weather)); } catch (e) { emit(WeatherBlockFailure()); } }); } }
0
mirrored_repositories/Flutter-Weather-App-Bloc/lib
mirrored_repositories/Flutter-Weather-App-Bloc/lib/screens/home_screen.dart
import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:intl/intl.dart'; import 'package:weather_app_bloc_1/bloc/weather_bloc.dart'; class HomeScreen extends StatefulWidget { const HomeScreen({super.key}); @override State<HomeScreen> createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { Widget getWeatherIcon(int code) { switch (code) { case > 200 && <= 300: return Image.asset( 'assets/1.png', ); case >= 300 && < 400: return Image.asset( 'assets/2.png', ); case >= 500 && < 600: return Image.asset( 'assets/3.png', ); case >= 600 && < 700: return Image.asset( 'assets/4.png', ); case >= 700 && < 800: return Image.asset( 'assets/5.png', ); case == 800: return Image.asset( 'assets/6.png', ); case > 800 && <= 804: return Image.asset( 'assets/7.png', ); default: return Image.asset( 'assets/1.png', ); } } String getHiFromHour(String formattedDate) { // Specify the correct date format DateFormat inputFormat = DateFormat("MMMM d, yyyy h:mm:ss a"); // Parse the input string DateTime parsedDate = inputFormat.parse(formattedDate); // get hour from Datetime Object int hour = parsedDate.hour; if (hour >= 0 && hour < 12) { return "Chào buổi sáng"; } else if (hour >= 12 && hour < 18) { return "Chào buổi trưa"; } else { return "Chào buổi tối"; } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.black, extendBodyBehindAppBar: true, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, systemOverlayStyle: SystemUiOverlayStyle(statusBarBrightness: Brightness.dark), ), body: Padding( padding: EdgeInsets.fromLTRB(40, 1.2 * kToolbarHeight, 40, 20), child: SizedBox( height: MediaQuery.of(context).size.height, child: Stack( children: [ Align( alignment: AlignmentDirectional(3, -0.3), child: Container( height: 300, width: 300, decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.deepPurple, ), ), ), Align( alignment: AlignmentDirectional(-3, -0.3), child: Container( height: 300, width: 300, decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.deepPurple, ), ), ), Align( alignment: AlignmentDirectional(0, -1.2), child: Container( height: 300, width: 300, decoration: BoxDecoration( shape: BoxShape.circle, color: Color(0xFFFFAB40), ), ), ), BackdropFilter( filter: ImageFilter.blur(sigmaX: 100.0, sigmaY: 100.0), child: Container( decoration: BoxDecoration(color: Colors.transparent), ), ), BlocBuilder<WeatherBloc, WeatherBlocState>( builder: (context, state) { if (state is WeatherBlocSuccess) { return SizedBox( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '️🎯 ${state.weather.areaName}', style: TextStyle( color: Colors.white, fontWeight: FontWeight.w300, ), ), SizedBox( height: 8, ), Text( getHiFromHour( DateFormat("MMMM d, yyyy h:mm:ss a") .format(state.weather.date!), ), style: TextStyle( color: Colors.white, fontSize: 25, fontWeight: FontWeight.bold, ), ), getWeatherIcon(state.weather.weatherConditionCode!), Center( child: Text( '${state.weather.temperature!.celsius!.round()} °C', style: TextStyle( color: Colors.white, fontSize: 55, fontWeight: FontWeight.w600, ), ), ), Center( child: Text( '${state.weather.weatherMain!.toUpperCase()}', style: TextStyle( color: Colors.white, fontSize: 25, fontWeight: FontWeight.w500, ), ), ), SizedBox( height: 8, ), Center( child: Text( DateFormat().format(state.weather.date!), style: TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.w300, ), ), ), SizedBox( height: 30, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Image.asset( 'assets/11.png', scale: 8, ), SizedBox( width: 5, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Sunrise', style: TextStyle( color: Colors.white, fontWeight: FontWeight.w300, ), ), SizedBox( height: 3, ), Text( DateFormat() .add_jm() .format(state.weather.sunrise!), style: TextStyle( color: Colors.white, fontWeight: FontWeight.w700, ), ), ], ) ], ), Row( children: [ Image.asset( 'assets/12.png', scale: 8, ), SizedBox( width: 5, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Sunset', style: TextStyle( color: Colors.white, fontWeight: FontWeight.w300, ), ), SizedBox( height: 3, ), Text( DateFormat() .add_jm() .format(state.weather.sunset!), style: TextStyle( color: Colors.white, fontWeight: FontWeight.w700, ), ), ], ) ], ), ], ), Padding( padding: EdgeInsets.symmetric(vertical: 5.0), child: Divider( color: Colors.grey, ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Image.asset( 'assets/13.png', scale: 8, ), SizedBox( width: 5, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Temp Max', style: TextStyle( color: Colors.white, fontWeight: FontWeight.w300, ), ), SizedBox( height: 3, ), Text( '${state.weather.tempMax!.celsius!.round().toString()} °C', style: TextStyle( color: Colors.white, fontWeight: FontWeight.w700, ), ), ], ) ], ), Row( children: [ Image.asset( 'assets/14.png', scale: 8, ), SizedBox( width: 5, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Temp Min', style: TextStyle( color: Colors.white, fontWeight: FontWeight.w300, ), ), SizedBox( height: 3, ), Text( '${state.weather.tempMin!.celsius!.round().toString()} °C', style: TextStyle( color: Colors.white, fontWeight: FontWeight.w700, ), ), ], ) ], ), ], ), ], ), ); } else { return Container(); } }, ) ], ), ), ), ); } }
0
mirrored_repositories/Flutter-Weather-App-Bloc
mirrored_repositories/Flutter-Weather-App-Bloc/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:weather_app_bloc_1/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Flutter-Travel-App/travel_app
mirrored_repositories/Flutter-Travel-App/travel_app/lib/main.dart
import 'package:flutter/material.dart'; import '../pages/welcome_page.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Flutter Travel App', debugShowCheckedModeBanner: false, home: WelcomePage() ); } }
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/nav_pages.dart/profile.dart
import 'package:flutter/material.dart'; import '../widget/reuseable_text.dart'; class Profile extends StatelessWidget { const Profile({super.key}); @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: const [ Icon( Icons.person, size: 200.0, color: Colors.deepPurpleAccent, ), AppText( text: "Profile", size: 20, color: Colors.black, fontWeight: FontWeight.w400, ) ], ), ); } }
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/nav_pages.dart/favorite.dart
import 'package:flutter/material.dart'; import '../widget/reuseable_text.dart'; class Bar extends StatelessWidget { const Bar({super.key}); @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: const [ Icon( Icons.favorite, size: 200.0, color: Colors.deepPurpleAccent, ), AppText( text: "Favorite", size: 20, color: Colors.black, fontWeight: FontWeight.w400, ) ], ), ); } }
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/nav_pages.dart/mail.dart
import 'package:flutter/material.dart'; import '../widget/reuseable_text.dart'; class Mail extends StatelessWidget { const Mail({super.key}); @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: const [ Icon( Icons.mail, size: 200.0, color: Colors.deepPurpleAccent, ), AppText( text: "Mail", size: 20, color: Colors.black, fontWeight: FontWeight.w400, ) ], ), ); } }
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/nav_pages.dart/main_wrapper.dart
import 'package:flutter/material.dart'; import 'package:water_drop_nav_bar/water_drop_nav_bar.dart'; import 'favorite.dart'; import '../nav_pages.dart/profile.dart'; import 'mail.dart'; import '../pages/home_page.dart'; class MainWrapper extends StatefulWidget { const MainWrapper({super.key}); @override State<MainWrapper> createState() => _MainWrapperState(); } class _MainWrapperState extends State<MainWrapper> { late final PageController pageController; int currentIndex = 0; List<Widget> pages = const [ HomePage(), Bar(), Mail(), Profile(), ]; @override void initState() { pageController = PageController(); super.initState(); } @override void dispose() { pageController.dispose(); super.dispose(); } void onTap(int index) { setState(() { currentIndex = index; }); pageController.animateToPage(index, duration: const Duration(milliseconds: 400), curve: Curves.linear); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: PageView( physics: const NeverScrollableScrollPhysics(), controller: pageController, children: pages, ), bottomNavigationBar: WaterDropNavBar( bottomPadding: 10.0, waterDropColor: Colors.deepPurpleAccent, backgroundColor: Colors.white, onItemSelected: onTap, selectedIndex: currentIndex, barItems: [ BarItem( filledIcon: Icons.home_filled, outlinedIcon: Icons.home_outlined, ), BarItem( filledIcon: Icons.favorite_rounded, outlinedIcon: Icons.favorite_border_rounded), BarItem( filledIcon: Icons.mail, outlinedIcon: Icons.mail_outline_outlined), BarItem(filledIcon: Icons.people, outlinedIcon: Icons.people_outline), ], ), )); } } // BottomNavigationBar( // unselectedFontSize: 0, // selectedFontSize: 0, // type: BottomNavigationBarType.fixed, // currentIndex: currentIndex, // showSelectedLabels: false, // showUnselectedLabels: false, // backgroundColor: Colors.white, // onTap: onTap, // elevation: 0, // unselectedItemColor: Colors.grey, // selectedItemColor: Colors.deepPurpleAccent, // items: const [ // BottomNavigationBarItem( // label: "Home", // icon: Icon( // Icons.apps_rounded, // ), // ), // BottomNavigationBarItem( // label: "Bar", // icon: Icon( // Icons.bar_chart_sharp, // ), // ), // BottomNavigationBarItem( // label: "Search", // icon: Icon( // Icons.search, // ), // ), // BottomNavigationBarItem( // label: "My Profile", // icon: Icon( // Icons.person, // ), // ), // ], // ),
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/pages/home_page.dart
import 'package:animate_do/animate_do.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import '../models/category_model.dart'; import '../models/people_also_like_model.dart'; import '../nav_pages.dart/main_wrapper.dart'; import '../pages/details_page.dart'; import '../widget/reuseable_text.dart'; import '../models/tab_bar_model.dart'; import '../widget/painter.dart'; import '../widget/reuseabale_middle_app_text.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> with TickerProviderStateMixin { late final TabController tabController; final EdgeInsetsGeometry padding = const EdgeInsets.symmetric(horizontal: 10.0); @override void initState() { tabController = TabController(length: 3, vsync: this); super.initState(); } @override void dispose() { tabController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; return GestureDetector( onTap: () => FocusManager.instance.primaryFocus?.unfocus(), child: Scaffold( appBar: _buildAppBar(size), body: SizedBox( width: size.width, height: size.height, child: Padding( padding: padding, child: SingleChildScrollView( physics: const BouncingScrollPhysics(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ FadeInUp( delay: const Duration(milliseconds: 300), child: const AppText( text: "Top Tours", size: 35, color: Colors.black, fontWeight: FontWeight.w500, ), ), FadeInUp( delay: const Duration(milliseconds: 400), child: const AppText( text: "For Your Request", size: 24, color: Colors.black, fontWeight: FontWeight.w400, ), ), FadeInUp( delay: const Duration(milliseconds: 500), child: Padding( padding: EdgeInsets.only( bottom: size.height * 0.01, top: size.height * 0.02), child: TextField( style: GoogleFonts.ubuntu( fontSize: 14, fontWeight: FontWeight.w400, color: Colors.grey, ), decoration: InputDecoration( contentPadding: const EdgeInsets.symmetric( vertical: 0, horizontal: 20), filled: true, fillColor: const Color.fromARGB(255, 240, 240, 240), prefixIcon: IconButton( onPressed: () {}, icon: const Icon( Icons.search, color: Colors.black, ), ), suffixIcon: IconButton( onPressed: () {}, icon: const Icon( Icons.filter_alt_outlined, color: Colors.grey, ), ), hintStyle: GoogleFonts.ubuntu( fontSize: 14, fontWeight: FontWeight.w400, color: Colors.grey, ), hintText: "Discover City", border: OutlineInputBorder( borderSide: BorderSide.none, borderRadius: BorderRadius.circular(14), ), ), ), ), ), FadeInUp( delay: const Duration(milliseconds: 600), child: Container( margin: const EdgeInsets.only(top: 10.0), width: size.width, child: Align( alignment: Alignment.centerLeft, child: TabBar( overlayColor: MaterialStateProperty.all(Colors.transparent), labelPadding: EdgeInsets.only( left: size.width * 0.05, right: size.width * 0.05), controller: tabController, labelColor: Colors.black, unselectedLabelColor: Colors.grey, isScrollable: true, indicatorSize: TabBarIndicatorSize.label, indicator: const CircleTabBarIndicator( color: Colors.deepPurpleAccent, radius: 4, ), tabs: const [ Tab( text: "Places", ), Tab(text: "Inspiration"), Tab(text: "Popular"), ], ), ), ), ), FadeInUp( delay: const Duration(milliseconds: 700), child: Container( margin: EdgeInsets.only(top: size.height * 0.01), width: size.width, height: size.height * 0.4, child: TabBarView( physics: const NeverScrollableScrollPhysics(), controller: tabController, children: [ TabViewChild( list: places, ), TabViewChild(list: inspiration), TabViewChild(list: popular), ]), ), ), FadeInUp( delay: const Duration(milliseconds: 800), child: const MiddleAppText(text: "Find More")), FadeInUp( delay: const Duration(milliseconds: 900), child: Container( margin: EdgeInsets.only(top: size.height * 0.01), width: size.width, height: size.height * 0.12, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: categoryComponents.length, physics: const BouncingScrollPhysics(), itemBuilder: (context, index) { Category current = categoryComponents[index]; return Column( children: [ Container( margin: const EdgeInsets.all(10.0), width: size.width * 0.16, height: size.height * 0.07, decoration: BoxDecoration( color: Colors.deepPurpleAccent .withOpacity(0.2), borderRadius: BorderRadius.circular(15), ), child: Padding( padding: const EdgeInsets.all(20.0), child: Image( image: AssetImage( current.image, ), ), ), ), AppText( text: current.name, size: 14, color: Colors.black, fontWeight: FontWeight.w400, ) ], ); }), ), ), FadeInUp( delay: const Duration(milliseconds: 1000), child: const MiddleAppText(text: "People Also Like")), FadeInUp( delay: const Duration(milliseconds: 1100), child: Container( margin: EdgeInsets.only(top: size.height * 0.01), width: size.width, height: size.height * 0.68, child: ListView.builder( itemCount: peopleAlsoLikeModel.length, physics: const NeverScrollableScrollPhysics(), itemBuilder: (context, index) { PeopleAlsoLikeModel current = peopleAlsoLikeModel[index]; return GestureDetector( onTap: () => Navigator.push( context, MaterialPageRoute( builder: (context) => DetailsPage( personData: current, tabData: null, isCameFromPersonSection: true, ), ), ), child: Container( margin: const EdgeInsets.all(8.0), width: size.width, height: size.height * 0.15, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(15), ), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Hero( tag: current.day, child: Container( margin: const EdgeInsets.all(8.0), width: size.width * 0.28, decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), image: DecorationImage( image: AssetImage( current.image, ), fit: BoxFit.cover, ), ), ), ), Padding( padding: EdgeInsets.only( left: size.width * 0.02), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: size.height * 0.035, ), AppText( text: current.title, size: 17, color: Colors.black, fontWeight: FontWeight.w400, ), SizedBox( height: size.height * 0.005, ), AppText( text: current.location, size: 14, color: Colors.black.withOpacity(0.5), fontWeight: FontWeight.w300, ), Padding( padding: EdgeInsets.only( top: size.height * 0.015), child: AppText( text: "${current.day} Day", size: 14, color: Colors.black.withOpacity(0.5), fontWeight: FontWeight.w300, ), ), ], ), ), ], ), ), ); }), ), ) ], ), ), ), ), ), ); } PreferredSize _buildAppBar(Size size) { return PreferredSize( preferredSize: Size.fromHeight(size.height * 0.09), child: Padding( padding: const EdgeInsets.only(top: 12), child: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: const Icon( Icons.menu, color: Colors.black, ), actions: [ Padding( padding: const EdgeInsets.only( right: 5, ), child: GestureDetector( onTap: (() => Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => const MainWrapper()))), child: const CircleAvatar( radius: 30, backgroundImage: AssetImage("assets/images/main.png"), ), ), ) ], ), ), ); } } class TabViewChild extends StatelessWidget { const TabViewChild({ required this.list, Key? key, }) : super(key: key); final List<TabBarModel> list; @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; return ListView.builder( itemCount: list.length, physics: const BouncingScrollPhysics(), scrollDirection: Axis.horizontal, itemBuilder: (context, index) { TabBarModel current = list[index]; return GestureDetector( onTap: () => Navigator.push( context, MaterialPageRoute( builder: (context) => DetailsPage( personData: null, tabData: current, isCameFromPersonSection: false, ), ), ), child: Stack( alignment: Alignment.bottomLeft, children: [ Hero( tag: current.image, child: Container( margin: const EdgeInsets.all(10.0), width: size.width * 0.6, decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), image: DecorationImage( image: AssetImage(current.image), fit: BoxFit.cover, ), ), ), ), Positioned( bottom: 0, left: 0, right: 0, top: size.height * 0.2, child: Container( margin: const EdgeInsets.all(10.0), width: size.width * 0.53, height: size.height * 0.2, decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), gradient: const LinearGradient( colors: [ Color.fromARGB(153, 0, 0, 0), Color.fromARGB(118, 29, 29, 29), Color.fromARGB(54, 0, 0, 0), Color.fromARGB(0, 0, 0, 0), ], begin: Alignment.bottomCenter, end: Alignment.topCenter, ), ), ), ), Positioned( left: size.width * 0.07, bottom: size.height * 0.045, child: AppText( text: current.title, size: 15, color: Colors.white, fontWeight: FontWeight.w400, ), ), Positioned( left: size.width * 0.07, bottom: size.height * 0.025, child: Row( children: [ const Icon( Icons.location_on, color: Colors.white, size: 15, ), SizedBox( width: size.width * 0.01, ), AppText( text: current.location, size: 12, color: Colors.white, fontWeight: FontWeight.w400, ), ], ), ), ], ), ); }, ); } }
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/pages/welcome_page.dart
import 'package:animate_do/animate_do.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:shape_of_view_null_safe/shape_of_view_null_safe.dart'; import '../nav_pages.dart/main_wrapper.dart'; import '../widget/reuseable_text.dart'; import '../models/welcome_model.dart'; class WelcomePage extends StatefulWidget { const WelcomePage({super.key}); @override State<WelcomePage> createState() => _WelcomePageState(); } class _WelcomePageState extends State<WelcomePage> { late final PageController pageController; @override void initState() { pageController = PageController(); super.initState(); } @override void dispose() { pageController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; return SafeArea( child: Scaffold( backgroundColor: const Color.fromARGB(255, 243, 243, 243), body: SizedBox( width: size.width, height: size.height, child: PageView.builder( controller: pageController, scrollDirection: Axis.vertical, itemCount: welcomeComponents.length, physics: const BouncingScrollPhysics(), itemBuilder: (context, index) { WelcomeModel current = welcomeComponents[index]; return SizedBox( width: size.width, height: size.height, child: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ SizedBox( width: size.width, height: size.height * 0.4, child: Padding( padding: EdgeInsets.only( left: size.width * 0.1, top: size.height * 0.04, right: size.width * 0.01), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ FadeInRight( child: AppText( text: current.title, size: 40, color: Colors.black, fontWeight: FontWeight.w500), ), FadeInLeft( child: AppText( text: current.subTitle, size: 30, color: Colors.black, fontWeight: FontWeight.w300, ), ), FadeInUp( delay: const Duration(milliseconds: 400), child: Padding( padding: EdgeInsets.only( top: size.height * 0.02), child: SizedBox( width: size.width * 0.8, child: AppText( text: current.description, size: 15, color: Colors.grey, fontWeight: FontWeight.w200, ), ), ), ), FadeInUpBig( duration: const Duration(milliseconds: 1100), child: Padding( padding: EdgeInsets.only( top: size.height * 0.08), child: MaterialButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15), ), minWidth: size.width * 0.3, height: size.height * 0.055, color: Colors.deepPurpleAccent, onPressed: () { Navigator.push( context, CupertinoPageRoute( builder: (context) => const MainWrapper())); }, child: const AppText( text: "Let's Go", size: 16, color: Colors.white, fontWeight: FontWeight.w300, ), ), ), ), ], ), Column( children: List.generate( 3, (indexDots) => GestureDetector( onTap: () { pageController.animateToPage( indexDots, duration: const Duration(milliseconds: 500), curve: Curves.linear, ); }, child: AnimatedContainer( margin: EdgeInsets.only( right: size.width * 0.01, bottom: size.height * 0.008), width: 10, height: index == indexDots ? 55 : 10, duration: const Duration(milliseconds: 200), decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), color: index == indexDots ? Colors.deepPurpleAccent : const Color.fromARGB( 255, 193, 170, 255), ), ), ), ), ) ], ), ), ), /// Bottom Images FadeInUpBig( duration: const Duration(milliseconds: 1200), child: ShapeOfView( width: size.width, elevation: 4, height: size.height * 0.55, shape: DiagonalShape( position: DiagonalPosition.Top, direction: DiagonalDirection.Right, angle: DiagonalAngle.deg(angle: 8), ), child: Image( image: AssetImage( current.imageUrl, ), fit: BoxFit.cover, ), ), ), ], ), ); }, ), ), ), ); } }
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/pages/details_page.dart
import 'package:animate_do/animate_do.dart'; import 'package:flutter/material.dart'; import '../models/people_also_like_model.dart'; import '../models/tab_bar_model.dart'; import '../widget/reuseable_text.dart'; class DetailsPage extends StatefulWidget { const DetailsPage({ super.key, required this.tabData, required this.personData, required this.isCameFromPersonSection, }); final TabBarModel? tabData; final PeopleAlsoLikeModel? personData; final bool isCameFromPersonSection; @override State<DetailsPage> createState() => _DetailsPageState(); } class _DetailsPageState extends State<DetailsPage> { int selected = 0; final EdgeInsetsGeometry padding = const EdgeInsets.symmetric(horizontal: 20.0); dynamic current; onFirstLoaded() { if (widget.tabData == null) { return current = widget.personData; } else { return current = widget.tabData; } } @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; onFirstLoaded(); return Scaffold( extendBodyBehindAppBar: true, appBar: _buildAppBar(), body: SizedBox( width: size.width, height: size.height, child: Stack( children: [ Positioned( left: 0, top: 0, right: 0, child: Hero( tag: widget.isCameFromPersonSection ? current.day : current.image, child: Container( width: size.width, height: size.height * 0.45, decoration: BoxDecoration( image: DecorationImage( image: AssetImage(current?.image), fit: BoxFit.cover, )), ), ), ), Positioned( left: 0, bottom: 0, right: 0, child: Container( padding: padding, width: size.width, height: size.height * 0.65, decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topLeft: Radius.circular(30), topRight: Radius.circular(30), )), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ FadeInUp( delay: const Duration(milliseconds: 200), child: Padding( padding: EdgeInsets.only(top: size.height * 0.02), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ AppText( text: current.title, size: 28, color: Colors.black, fontWeight: FontWeight.w500, ), Row( children: [ const Icon( Icons.location_on, color: Colors.black54, size: 15, ), SizedBox( width: size.width * 0.01, ), AppText( text: current.location, size: 12, color: Colors.black54, fontWeight: FontWeight.w400, ), ], ), ], ), AppText( text: "\$${current.price}", size: 25, color: Colors.black54, fontWeight: FontWeight.w500, ), ], ), ), ), SizedBox( height: size.height * 0.02, ), FadeInUp( delay: const Duration(milliseconds: 300), child: Row( children: [ Wrap( children: List.generate(5, (index) { return Icon( index < 4 ? Icons.star : Icons.star_border, color: index < 4 ? Colors.amber : Colors.grey, ); }), ), SizedBox( width: size.width * 0.01, ), const AppText( text: "(4.0)", size: 15, color: Colors.black54, fontWeight: FontWeight.w400, ), ], ), ), SizedBox(height: size.height * 0.03), FadeInUp( delay: const Duration(milliseconds: 400), child: const AppText( text: "People", size: 24, color: Colors.black, fontWeight: FontWeight.w500, ), ), SizedBox(height: size.height * 0.002), FadeInUp( delay: const Duration(milliseconds: 500), child: const AppText( text: "Number of people in your group", size: 14, color: Colors.black54, fontWeight: FontWeight.w400, ), ), FadeInUp( delay: const Duration(milliseconds: 600), child: Container( margin: EdgeInsets.only(top: size.height * 0.01), width: size.width * 0.9, height: size.height * 0.08, child: ListView.builder( physics: const BouncingScrollPhysics(), scrollDirection: Axis.horizontal, itemCount: 7, itemBuilder: (ctx, index) { return GestureDetector( onTap: () { setState(() { selected = index; }); }, child: Padding( padding: const EdgeInsets.all(10.0), child: AnimatedContainer( width: size.width * 0.12, decoration: BoxDecoration( color: selected == index ? Colors.black : const Color.fromARGB( 255, 245, 245, 245), borderRadius: BorderRadius.circular(15), ), duration: const Duration(milliseconds: 200), child: Center( child: Text( "${index + 1}", style: TextStyle( fontSize: 17, fontWeight: FontWeight.w500, color: selected == index ? Colors.white : Colors.black), ), ), ), ), ); }), ), ), SizedBox(height: size.height * 0.02), FadeInUp( delay: const Duration(milliseconds: 800), child: const AppText( text: "Description", size: 21, color: Colors.black, fontWeight: FontWeight.w500, ), ), SizedBox(height: size.height * 0.01), FadeInUp( delay: const Duration(milliseconds: 900), child: const AppText( text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.", size: 13, color: Colors.black54, fontWeight: FontWeight.w300, ), ), FadeInUp( delay: const Duration(milliseconds: 1000), child: Padding( padding: EdgeInsets.only(top: size.height * 0.05), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Container( width: size.width * 0.14, height: size.height * 0.06, decoration: BoxDecoration( border: Border.all( color: Colors.deepPurpleAccent, width: 2), borderRadius: BorderRadius.circular(10)), child: IconButton( onPressed: () {}, icon: const Icon( Icons.favorite_border, color: Colors.deepPurpleAccent, ), )), MaterialButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15), ), minWidth: size.width * 0.6, height: size.height * 0.06, color: Colors.deepPurpleAccent, onPressed: () {}, child: const AppText( text: "Book Trip Now", size: 16, color: Colors.white, fontWeight: FontWeight.w300, ), ), ], ), ), ), ], ), ), ), ], ), )); } AppBar _buildAppBar() { return AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: IconButton( onPressed: () { Navigator.pop(context); }, icon: const Icon(Icons.arrow_back_ios), ), actions: [ IconButton( onPressed: () {}, icon: const Icon(Icons.more_vert_outlined), ), ], ); } }
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/models/welcome_model.dart
class WelcomeModel { final String title; final String subTitle; final String description; final String imageUrl; WelcomeModel({ required this.title, required this.subTitle, required this.description, required this.imageUrl, }); } List<WelcomeModel> welcomeComponents = [ WelcomeModel( title: "Travel", subTitle: "Roads", description: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.", imageUrl: "assets/images/1.jpg"), WelcomeModel( title: "Enjoy", subTitle: "Seas", description: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.", imageUrl: "assets/images/2.jpg"), WelcomeModel( title: "Discover", subTitle: "Mountains", description: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.", imageUrl: "assets/images/3.jpg"), ];
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/models/people_also_like_model.dart
class PeopleAlsoLikeModel { final String title; final String location; final int day; final String image; final int price; PeopleAlsoLikeModel({ required this.title, required this.location, required this.day, required this.image, required this.price }); } List<PeopleAlsoLikeModel> peopleAlsoLikeModel = [ PeopleAlsoLikeModel( title: "Eiffel Tower", location: "Paris", image: "assets/images/paris.jpg", day: 5, price: 430), PeopleAlsoLikeModel( title: "Baja Peninsula", location: "Mexico", image: "assets/images/images.jpeg", day: 7, price: 233), PeopleAlsoLikeModel( title: "Sossusvlei", location: "Salt pan in Namibia", image: "assets/images/Sossusvlei.jpg", day: 9, price: 550), PeopleAlsoLikeModel( title: "Cancún", location: "Mexico", image: "assets/images/22bab5ad4b9aa1027ad00a84ea7493d2c0c5e666d43d3b9413e332bdbd3f1780.jpg", day: 3, price: 546), ];
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/models/tab_bar_model.dart
class TabBarModel { final String title; final String location; final String image; final int price; TabBarModel( {required this.title, required this.location, required this.image, required this.price}); } List<TabBarModel> places = [ TabBarModel( title: "South Island", location: "New Zealand", image: "assets/images/New_Zealand.jpg", price: 320), TabBarModel( title: "Eiffel Tower", location: "Paris", image: "assets/images/paris.jpg", price: 262), TabBarModel( title: "Tahiti", location: "Island in French Polynesia", image: "assets/images/Tahiti.jpg", price: 221) ]; List<TabBarModel> inspiration = [ TabBarModel( title: "Unguja", location: "Island in Tanzania", image: "assets/images/download.jpeg", price: 543), TabBarModel( title: "Baja Peninsula", location: "Mexico", image: "assets/images/images.jpeg", price: 238), TabBarModel( title: "Sossusvlei", location: "Salt pan in Namibia", image: "assets/images/Sossusvlei.jpg", price: 124) ]; List<TabBarModel> popular = [ TabBarModel( title: "Dubai", location: "United Arab Emirates", image: "assets/images/607d0368488549e7b9179724b0db4940.jpg", price: 756), TabBarModel( title: "Cancún", location: "Mexico", image: "assets/images/22bab5ad4b9aa1027ad00a84ea7493d2c0c5e666d43d3b9413e332bdbd3f1780.jpg", price: 321), TabBarModel( title: "Crete", location: "Greece", image: "assets/images/shutterstock_436817194.jpg", price: 340), ];
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/models/category_model.dart
class Category { final String name; final String image; Category({required this.name, required this.image,}); } List<Category> categoryComponents = [ Category(name: "Beach", image: "assets/images/beach.png"), Category(name: "Boat", image: "assets/images/boat.png"), Category(name: "Museum", image: "assets/images/museum.png"), Category(name: "Lake", image: "assets/images/lake.png"), Category(name: "Tricycle", image: "assets/images/tricycle.png"), ];
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/widget/reuseabale_middle_app_text.dart
import 'package:flutter/material.dart'; import 'reuseable_text.dart'; class MiddleAppText extends StatelessWidget { const MiddleAppText({ Key? key, required this.text, }) : super(key: key); final String text; @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; return Padding( padding: EdgeInsets.only(top: size.height * 0.015), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ AppText( text: text, size: 19, color: Colors.black, fontWeight: FontWeight.w500, ), const AppText( text: "See All", size: 14, color: Colors.deepPurpleAccent, fontWeight: FontWeight.w500, ), ], ), ); } }
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/widget/reuseable_text.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class AppText extends StatelessWidget { const AppText( {super.key, required this.text, required this.size, required this.color, required this.fontWeight}); final String text; final double size; final Color color; final FontWeight fontWeight; @override Widget build(BuildContext context) { return Text( text, style: GoogleFonts.ubuntu( fontSize: size, color: color, fontWeight: fontWeight, ), ); } }
0
mirrored_repositories/Flutter-Travel-App/travel_app/lib
mirrored_repositories/Flutter-Travel-App/travel_app/lib/widget/painter.dart
import 'package:flutter/material.dart'; class CircleTabBarIndicator extends Decoration { final Color color; final double radius; const CircleTabBarIndicator({required this.color, required this.radius}); @override BoxPainter createBoxPainter([VoidCallback? onChanged]) { return _CirclePainter(color: color, radius: radius); } } class _CirclePainter extends BoxPainter { final Color color; double radius; _CirclePainter({required this.color, required this.radius}); @override void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { Paint _paint = Paint(); _paint.color = color; _paint.isAntiAlias = true; final Offset circleOffset = Offset( configuration.size!.width / 2 - radius / 2, configuration.size!.height - radius / 2); canvas.drawCircle(offset + circleOffset, radius, _paint); } }
0
mirrored_repositories/lint_staged
mirrored_repositories/lint_staged/lib/lint_staged.dart
import 'dart:io'; import 'src/context.dart'; import 'src/logging.dart'; import 'src/message.dart'; import 'src/run.dart'; import 'src/symbols.dart'; /// /// Root lint_staged function that is called from `bin/lint_staged.dart`. /// /// [allowEmpty] - Allow empty commits when tasks revert all staged changes /// [diff] - Override the default "--staged" flag of "git diff" to get list of files /// [diffFilter] - Override the default "--diff-filter=ACMR" flag of "git diff" to get list of files /// [stash] - Enable the backup stash, and revert in case of errors /// Future<bool> lintStaged({ bool allowEmpty = false, List<String> diff = const [], String? diffFilter, bool stash = true, String? workingDirectory, int maxArgLength = 0, }) async { try { final ctx = await runAll( allowEmpty: allowEmpty, diff: diff, diffFilter: diffFilter, stash: stash, maxArgLength: maxArgLength, workingDirectory: workingDirectory); _printTaskOutput(ctx); return true; } catch (e) { if (e is Context) { if (e.errors.contains(kConfigNotFoundError)) { stdout.error(kNoConfigurationMsg); } else if (e.errors.contains(kApplyEmptyCommitError)) { stdout.warn(kPreventedEmptyCommitMsg); } else if (e.errors.contains(kGitError) && !e.errors.contains(kGetBackupStashError)) { stdout.failed(kGitErrorMsg); if (e.shouldBackup) { // No sense to show this if the backup stash itself is missing. stdout.error(kRestoreStashExampleMsg); } } _printTaskOutput(e); return false; } rethrow; } } void _printTaskOutput(Context ctx) { if (ctx.output.isEmpty) return; final log = ctx.errors.isNotEmpty ? stdout.failed : stdout.success; for (var line in ctx.output) { log(line); } }
0
mirrored_repositories/lint_staged/lib
mirrored_repositories/lint_staged/lib/src/group.dart
import 'package:glob/glob.dart'; import 'package:verbose/verbose.dart'; final _verbose = Verbose('lint_staged:group'); class Group { final List<String> scripts; final List<String> files; Group({required this.scripts, required this.files}); } Map<String, Group> groupFilesByConfig( {required Map<String, List<String>> config, required List<String> files}) { final fileSet = files.toSet(); final groups = <String, Group>{}; // Separate config into inclusion and exclusion patterns final includeConfig = config.entries.where((e) => !e.key.startsWith('!')); final excludeConfig = config.entries.where((e) => e.key.startsWith('!')); // First, include files based on inclusion patterns for (var entry in includeConfig) { final glob = Glob(entry.key); final matchedFiles = fileSet.where((file) => glob.matches(file)).toList(); if (matchedFiles.isNotEmpty) { _verbose('$glob matched files: $matchedFiles'); groups[entry.key] = Group(scripts: entry.value, files: matchedFiles); } } // Next, exclude files based on exclusion patterns for (var entry in excludeConfig) { final glob = Glob(entry.key.substring(1)); // Remove the '!' prefix final excludedFiles = fileSet.where((file) => glob.matches(file)).toSet(); // Remove excluded files from each group for (var group in groups.values) { _verbose('$glob excluded files: $excludedFiles'); group.files.removeWhere((file) => excludedFiles.contains(file)); } } return groups; }
0
mirrored_repositories/lint_staged/lib
mirrored_repositories/lint_staged/lib/src/logging.dart
import 'dart:async'; import 'dart:io' as io; import 'package:ansi/ansi.dart'; import 'package:ansi_escapes/ansi_escapes.dart'; import 'package:path/path.dart'; import 'package:verbose/verbose.dart'; class _Figures { static const success = '✔'; static const error = '✗'; static const skipped = '↓'; static const warn = '⚠'; } extension IOSink on io.IOSink { void failed(String message) { writeln('${red(_Figures.error)} $message'); } void skipped(String message) { writeln('${grey(_Figures.skipped)} $message'); } void warn(String message) { writeln(yellow('${_Figures.warn} $message')); } void error(String message) { writeln(red(message)); } void success(String message) { writeln('${green(_Figures.success)} $message'); } } final _isTest = basename(io.Platform.script.path).startsWith('test.dart'); class Spinner { final Stopwatch _stopwatch; Timer? _timer; _SpinnerFrame? _frame; late int _lineCount; Spinner() : _stopwatch = Stopwatch(); Duration get elapsed => _stopwatch.elapsed; void progress(String message) { _lineCount = message.split('\n').length; _frame = _SpinnerFrame(message); _start(); } void failed(String message) { _stop(); io.stdout.writeln('${red(_Figures.error)} $message'); } void success(String message) { _stop(); io.stdout.writeln( '${green(_Figures.success)} ${message.padRight(40)}${elapsed.inMilliseconds}ms'); } void skipped(String message) { _stop(); io.stdout.writeln('${grey(_Figures.skipped)} $message'); } void _start() { io.stdout.write(_frame); _stopwatch.reset(); _stopwatch.start(); if (Verbose.enabled || _isTest) { io.stdout.write('\n'); return; } _timer = Timer.periodic(const Duration(milliseconds: 80), (t) { io.stdout.write('${ansiEscapes.eraseLines(_lineCount)}$_frame'); }); } void _stop() { if (Verbose.enabled || _isTest) { return; } if (_timer != null) { io.stdout.write(ansiEscapes.eraseLines(_lineCount)); _stopwatch.stop(); _timer?.cancel(); _timer = null; } } } const _kFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; class _SpinnerFrame { int _index = 0; final String message; _SpinnerFrame(this.message); @override String toString() => '${_kFrames[_index++ % _kFrames.length]} $message'; }
0
mirrored_repositories/lint_staged/lib
mirrored_repositories/lint_staged/lib/src/fs.dart
import 'dart:io'; import 'package:path/path.dart'; class FileSystem { final String root; FileSystem([String? path]) : root = path ?? Directory.current.path; Future<void> append(String filename, String content) async { final file = File(join(root, filename)); if (!await file.exists()) { await file.create(recursive: true); } file.writeAsString(content, mode: FileMode.append); } Future<void> write(String filename, String content) async { final file = File(join(root, filename)); if (!await file.exists()) { await file.create(recursive: true); } file.writeAsString(content); } Future<void> remove(String filename) async { final file = File(join(root, filename)); if (await file.exists()) { await file.delete(recursive: true); } } Future<bool> exists(String path) async { final file = File(join(root, path)); if (await file.exists()) { return true; } return Directory(join(root, path)).exists(); } Future<String?> read(String filename) async { final file = File(join(root, filename)); if (await file.exists()) { return await file.readAsString(); } return null; } }
0
mirrored_repositories/lint_staged/lib
mirrored_repositories/lint_staged/lib/src/symbols.dart
const kApplyEmptyCommitError = Symbol('ApplyEmptyCommitError'); const kConfigNotFoundError = Symbol('Configuration could not be found'); const kConfigFormatError = Symbol('Configuration should be an object or a function'); const kConfigEmptyError = Symbol('Configuration should not be empty'); const kGetBackupStashError = Symbol('GetBackupStashError'); const kGetStagedFilesError = Symbol('GetStagedFilesError'); const kGitError = Symbol('GitError'); const kGitRepoError = Symbol('GitRepoError'); const kHideUnstagedChangesError = Symbol('HideUnstagedChangesError'); const kInvalidOptionsError = Symbol('Invalid Options'); const kRestoreMergeStatusError = Symbol('RestoreMergeStatusError'); const kRestoreOriginalStateError = Symbol('RestoreOriginalStateError'); const kRestoreUnstagedChangesError = Symbol('RestoreUnstagedChangesError'); const kTaskError = Symbol('TaskError');
0
mirrored_repositories/lint_staged/lib
mirrored_repositories/lint_staged/lib/src/chunk.dart
import 'dart:math'; /// /// Chunk files into sub-lists based on the length of the resulting argument string /// List<List<String>> chunkFiles( List<String> files, { int maxArgLength = 0, }) { if (maxArgLength <= 0) { return [files]; } final fileListLength = files.join(' ').length; final chunkCount = min((fileListLength / maxArgLength).ceil(), files.length); return chunkList(files, chunkCount); } /// Chunk list into sub-lists List<List<T>> chunkList<T>(List<T> list, int chunkCount) { if (chunkCount == 1) return [list]; final chunked = <List<T>>[]; int position = 0; for (var i = 0; i < chunkCount; i++) { final chunkLength = ((list.length - position) / (chunkCount - i)).ceil(); chunked.add([]); chunked[i] = list.sublist(position, chunkLength + position); position += chunkLength; } return chunked; }
0
mirrored_repositories/lint_staged/lib
mirrored_repositories/lint_staged/lib/src/run.dart
import 'dart:io'; import 'package:ansi/ansi.dart'; import 'package:lint_staged/src/fs.dart'; import 'package:verbose/verbose.dart'; import 'chunk.dart'; import 'config.dart'; import 'git.dart'; import 'group.dart'; import 'workflow.dart'; import 'logging.dart'; import 'message.dart'; import 'context.dart'; import 'symbols.dart'; final _verbose = Verbose('lint_staged:run'); Future<Context> runAll({ bool allowEmpty = false, List<String> diff = const [], String? diffFilter, bool stash = true, String? workingDirectory, int maxArgLength = 0, }) async { final ctx = getInitialContext(); final fs = FileSystem(workingDirectory); if (!await fs.exists('.git')) { ctx.output.add(kNotGitRepoMsg); ctx.errors.add(kGitRepoError); throw ctx; } final git = Git( diff: diff, diffFilter: diffFilter, workingDirectory: workingDirectory); /// Test whether we have any commits or not. /// Stashing must be disabled with no initial commit. final hasInitialCommit = (await git.lastCommit).isNotEmpty; /// lint_staged will create a backup stash only when there's an initial commit, /// and when using the default list of staged files by default ctx.shouldBackup = hasInitialCommit && stash; if (!ctx.shouldBackup) { final reason = diff.isNotEmpty ? '`--diff` was used' : hasInitialCommit ? '`--no-stash` was used' : 'there\'s no initial commit yet'; stdout.warn('Skipping backup because $reason.'); } final stagedFiles = await git.stagedFiles; if (stagedFiles.isEmpty) { ctx.output.add(kNoStagedFilesMsg); return ctx; } final config = await loadConfig(workingDirectory: workingDirectory); if (config == null || config.isEmpty) { ctx.errors.add(kConfigNotFoundError); throw ctx; } final groups = groupFilesByConfig(config: config, files: stagedFiles); if (groups.isEmpty) { ctx.output.add(kNoStagedFilesMatchedMsg); return ctx; } final matchedFiles = groups.values.expand((element) => element.files).toList(); final matchedFileChunks = chunkFiles(matchedFiles, maxArgLength: maxArgLength); final workflow = Workflow( fs: fs, ctx: ctx, git: git, allowEmpty: allowEmpty, matchedFileChunks: matchedFileChunks, ); final spinner = Spinner(); spinner.progress('Preparing lint_staged...'); await workflow.prepare(); spinner.success('Prepared lint_staged'); if (ctx.hasPartiallyStagedFiles) { spinner.progress('Hide unstaged changes...'); await workflow.hideUnstagedChanges(); spinner.success('Hide unstaged changes'); } else { spinner.skipped('Hide unstaged changes'); } spinner.progress('Run tasks for staged files...'); await Future.wait(groups.values.map((group) async { await Future.wait(group.scripts.map((script) async { final args = script.split(' '); final exe = args.removeAt(0); await Future.wait(group.files.map((file) async { final result = await Process.run(exe, [...args, file], workingDirectory: workingDirectory); final messsages = ['$script $file']; if (result.stderr.toString().trim().isNotEmpty) { messsages.add(red(result.stderr.toString().trim())); } if (result.stdout.toString().trim().isNotEmpty) { messsages.add(result.stdout.toString().trim()); } _verbose(messsages.join('\n')); if (result.exitCode != 0) { ctx.output.add(messsages.join('\n')); ctx.errors.add(kTaskError); } })); })); })); spinner.success('Run tasks for staged files'); if (!applyModifationsSkipped(ctx)) { spinner.progress('Apply modifications...'); await workflow.applyModifications(); spinner.success('Apply modifications'); } else { spinner.skipped('Apply modifications'); } if (ctx.hasPartiallyStagedFiles && !restoreUnstagedChangesSkipped(ctx)) { spinner.progress('Restore unstaged changes...'); await workflow.resotreUnstagedChanges(); spinner.success('Restore unstaged changes'); } else { spinner.skipped('Restore unstaged changes'); } if (restoreOriginalStateEnabled(ctx) && !restoreOriginalStateSkipped(ctx)) { spinner.progress('Revert because of errors...'); await workflow.restoreOriginState(); spinner.success('Revert because of errors'); } else { spinner.skipped('Revert because of errors'); } if (cleanupEnabled(ctx) && !cleanupSkipped(ctx)) { spinner.progress('Cleanup temporary files...'); await workflow.cleanup(); spinner.success('Cleanup temporary files'); } else { spinner.skipped('Cleanup temporary files'); } if (ctx.errors.isNotEmpty) { throw ctx; } return ctx; }
0
mirrored_repositories/lint_staged/lib
mirrored_repositories/lint_staged/lib/src/config.dart
import 'dart:io'; import 'package:path/path.dart'; import 'package:verbose/verbose.dart'; import 'package:yaml/yaml.dart'; final _verbose = Verbose('lint_staged:config'); Future<Map<String, List<String>>?> loadConfig({ String? workingDirectory, }) async { final pubspecPath = join(workingDirectory ?? Directory.current.path, 'pubspec.yaml'); final yaml = await loadYaml(File(pubspecPath).readAsStringSync()); final map = yaml['lint_staged']; if (map is! Map) { return null; } _verbose('Found config: $map'); final config = <String, List<String>>{}; for (var entry in map.entries) { final value = entry.value; if (value is String) { config[entry.key] = value.split('&&').map((e) => e.trim()).toList(); } else if (value is List) { config[entry.key] = value.cast(); } } return config; }
0
mirrored_repositories/lint_staged/lib
mirrored_repositories/lint_staged/lib/src/workflow.dart
import 'package:path/path.dart' show join; import 'package:verbose/verbose.dart'; import 'context.dart'; import 'fs.dart'; import 'git.dart'; import 'symbols.dart'; /// In git status machine output, renames are presented as `to`NUL`from` /// When diffing, both need to be taken into account, but in some cases on the `to`. final _renameRegex = RegExp(r'\x00'); final _verbose = Verbose('lint_staged:workflow'); /// /// From list of files, split renames and flatten into two files `to`NUL`from`. /// List<String> processRenames(List<String> files, [bool includeRenameFrom = true]) { return files.fold([], (flattened, file) { if (_renameRegex.hasMatch(file)) { /// first is to, last is from final rename = file.split(_renameRegex); if (includeRenameFrom) { flattened.add(rename.last); } flattened.add(rename.first); } else { flattened.add(file); } return flattened; }); } const _kStashMessage = 'lint_staged automatic backup'; const _kGitDiffArgs = [ '--binary', // support binary files '--unified=0', // do not add lines around diff for consistent behaviour '--no-color', // disable colors for consistent behaviour '--no-ext-diff', // disable external diff tools for consistent behaviour '--src-prefix=a/', // force prefix for consistent behaviour '--dst-prefix=b/', // force prefix for consistent behaviour '--patch', // output a patch that can be applied '--submodule=short', // always use the default short format for submodules ]; const _kGitApplyArgs = [ '-v', '--whitespace=nowarn', '--recount', '--unidiff-zero' ]; class Workflow { final Git git; final FileSystem fs; final Context ctx; final bool allowEmpty; final List<List<String>> matchedFileChunks; late List<String> _partiallyStagedFiles; late List<String> _deletedFiles; /// /// These three files hold state about an ongoing git merge /// Resolve paths during constructor /// late final String _mergeHeadFilename = join(git.gitdir, 'MERGE_HEAD'); late final String _mergeModeFilename = join(git.gitdir, 'MERGE_MODE'); late final String _mergeMsgFilename = join(git.gitdir, 'MERGE_MSG'); late final String _unstagedFilename = join(git.gitdir, 'lint_staged_unstaged.patch'); String? mergeHeadContent; String? mergeModeContent; String? mergeMsgContent; Workflow({ required this.fs, required this.git, required this.ctx, this.allowEmpty = false, this.matchedFileChunks = const [], }); /// /// Get name of backup stash /// Future<String> getBackupStash() async { final stashes = await git.stashes; final index = stashes.indexWhere((line) => line.contains(_kStashMessage)); if (index == -1) { ctx.errors.add(kGetBackupStashError); throw Exception('lint_staged automatic backup is missing!'); } return index.toString(); } /// /// Save meta information about ongoing git merge /// Future<void> backupMergeStatus() async { await Future.wait([ fs.read(_mergeHeadFilename).then((value) => mergeHeadContent = value), fs.read(_mergeModeFilename).then((value) => mergeModeContent = value), fs.read(_mergeMsgFilename).then((value) => mergeModeContent = value) ]); } /// /// Restore meta information about ongoing git merge /// Future<void> restoreMergeStatus() async { try { await Future.wait([ if (mergeHeadContent != null) fs.write(_mergeHeadFilename, mergeHeadContent!), if (mergeModeContent != null) fs.write(_mergeModeFilename, mergeModeContent!), if (mergeMsgContent != null) fs.write(_mergeMsgFilename, mergeMsgContent!), ]); } catch (error, stack) { _verbose(error.toString()); _verbose(stack.toString()); handleError( Exception('Merge state could not be restored due to an error!'), kRestoreMergeStatusError); } } /// /// Create a diff of partially staged files and backup stash if enabled. /// Future<void> prepare() async { try { _partiallyStagedFiles = await git.partiallyStagedFiles; if (_partiallyStagedFiles.isNotEmpty) { ctx.hasPartiallyStagedFiles = true; final files = processRenames(_partiallyStagedFiles); await git.run([ 'diff', ..._kGitDiffArgs, '--output', _unstagedFilename, '--', ...files ]); } else { ctx.hasPartiallyStagedFiles = false; } /// If backup stash should be skipped, no need to continue if (!ctx.shouldBackup) { return; } /// When backup is enabled, the revert will clear ongoing merge status. await backupMergeStatus(); /// Get a list of unstaged deleted files, because certain bugs might cause them to reappear: /// - in git versions =< 2.13.0 the `git stash --keep-index` option resurrects deleted files /// - git stash can't infer RD or MD states correctly, and will lose the deletion _deletedFiles = await git.deletedFiles; /// Save stash of all staged files. /// and `stash store` saves it as an actual stash. final stash = await git.createStash(); /// Whether there's nothing to stash. if (stash.isNotEmpty) { await git.storeStash(stash, message: _kStashMessage); } } catch (error, stack) { _verbose(error.toString()); _verbose(stack.toString()); handleError(error); } } /// /// Remove unstaged changes to all partially staged files, to avoid tasks from seeing them /// Future<void> hideUnstagedChanges() async { try { final files = processRenames(_partiallyStagedFiles, false); await git.run(['checkout', '--force', '--', ...files]); } catch (error, stack) { _verbose(error.toString()); _verbose(stack.toString()); /// ///`git checkout --force` doesn't throw errors, so it shouldn't be possible to get here. // If this does fail, the handleError method will set ctx.gitError and lint_staged will fail. /// handleError(error, kHideUnstagedChangesError); } } /// /// Applies back task modifications, and unstaged changes hidden in the stash. /// In case of a merge-conflict retry with 3-way merge. /// Future<void> applyModifications() async { /// `matchedFileChunks` includes staged files that lint_staged originally detected and matched against a task. /// Add only these files so any 3rd-party edits to other files won't be included in the commit. /// These additions per chunk are run "serially" to prevent race conditions. /// Git add creates a lockfile in the repo causing concurrent operations to fail. for (var files in matchedFileChunks) { await git.run(['add', '--', ...files]); } final stagedFilesAfterAdd = await git.stagedFiles; if (stagedFilesAfterAdd.isEmpty && !allowEmpty) { handleError( Exception('Prevented an empty git commit!'), kApplyEmptyCommitError); } } /// /// Restore unstaged changes to partially changed files. If it at first fails, /// this is probably because of conflicts between new task modifications. /// 3-way merge usually fixes this, and in case it doesn't we should just give up and throw. /// Future<void> resotreUnstagedChanges() async { try { await git.run(['apply', ..._kGitApplyArgs, _unstagedFilename]); } catch (_) { _verbose('Error while restoring changes:'); _verbose('Retrying with 3-way merge'); try { // Retry with a 3-way merge if normal apply fails await git .run(['apply', ..._kGitApplyArgs, '--3way', _unstagedFilename]); } catch (error, stack) { _verbose('Error while restoring unstaged changes using 3-way merge:'); _verbose(error.toString()); _verbose(stack.toString()); handleError(error, kRestoreUnstagedChangesError); } } } /// /// Restore original HEAD state in case of errors /// Future<void> restoreOriginState() async { try { await git.run(['reset', '--hard', 'HEAD']); final backupStash = await getBackupStash(); await git.run(['stash', 'apply', '--quiet', '--index', backupStash]); /// Restore meta information about ongoing git merge await restoreMergeStatus(); /// If stashing resurrected deleted files, clean them out await Future.wait(_deletedFiles.map((file) => fs.remove(file))); // Clean out patch await fs.remove(_unstagedFilename); } catch (error, stack) { _verbose(error.toString()); _verbose(stack.toString()); handleError(error, kRestoreOriginalStateError); } } /// /// Drop the created stashes after everything has run /// Future<void> cleanup() async { try { await git.run(['stash', 'drop', '--quiet', await getBackupStash()]); } catch (error, stack) { _verbose(error.toString()); _verbose(stack.toString()); handleError(error); } } void handleError(dynamic error, [Symbol? symbol]) { ctx.errors.add(kGitError); if (symbol != null) { ctx.errors.add(symbol); } // throw error; } }
0
mirrored_repositories/lint_staged/lib
mirrored_repositories/lint_staged/lib/src/message.dart
const kNotGitRepoMsg = 'Current directory is not a git directory!'; const kGetStagedFilesErrorMsg = 'Failed to get staged files!'; const kNoStagedFilesMsg = 'No staged files'; const kNoStagedFilesMatchedMsg = 'No staged files matched'; const kGitErrorMsg = 'lint_staged failed due to a git error.'; const kNoConfigurationMsg = 'No `lint_staged` configuration found in pubspec.yaml.'; const kPreventedEmptyCommitMsg = '''lint_staged prevented an empty git commit. Use the `--allow-empty` option to continue, or check your task configuration'''; const kRestoreStashExampleMsg = ''' Any lost modifications can be restored from a git stash: > git stash list stash@{0}: automatic lint_staged backup > git stash apply --index stash@{0} ''';
0
mirrored_repositories/lint_staged/lib
mirrored_repositories/lint_staged/lib/src/context.dart
import 'symbols.dart'; class Context { bool hasPartiallyStagedFiles = false; bool shouldBackup = false; Set<Object> errors = {}; List<String> output = []; } Context getInitialContext() => Context(); bool applyModifationsSkipped(Context ctx) { /// Always apply back unstaged modifications when skipping backup if (!ctx.shouldBackup) return false; /// Should be skipped in case of git errors if (ctx.errors.contains(kGitError)) { return true; } /// Should be skipped when tasks fail if (ctx.errors.contains(kTaskError)) { return true; } return false; } bool restoreUnstagedChangesSkipped(Context ctx) { /// Should be skipped in case of git errors if (ctx.errors.contains(kGitError)) { return true; } /// Should be skipped when tasks fail if (ctx.errors.contains(kTaskError)) { return true; } return false; } bool restoreOriginalStateEnabled(Context ctx) => ctx.shouldBackup && (ctx.errors.contains(kTaskError) || ctx.errors.contains(kApplyEmptyCommitError) || ctx.errors.contains(kRestoreUnstagedChangesError)); bool restoreOriginalStateSkipped(Context ctx) { // Should be skipped in case of unknown git errors if (ctx.errors.contains(kGitError) && !ctx.errors.contains(kApplyEmptyCommitError) && !ctx.errors.contains(kRestoreUnstagedChangesError)) { return true; } return false; } bool cleanupEnabled(Context ctx) => ctx.shouldBackup; bool cleanupSkipped(Context ctx) { // Should be skipped in case of unknown git errors if (ctx.errors.contains(kGitError) && !ctx.errors.contains(kApplyEmptyCommitError) && !ctx.errors.contains(kRestoreUnstagedChangesError)) { return true; } // Should be skipped when reverting to original state fails if (ctx.errors.contains(kRestoreOriginalStateError)) { return true; } return false; }
0
mirrored_repositories/lint_staged/lib
mirrored_repositories/lint_staged/lib/src/git.dart
import 'dart:io' show Process, ProcessException, ProcessResult; import 'dart:math'; import 'package:ansi/ansi.dart'; import 'package:verbose/verbose.dart'; final _verbose = Verbose('lit_staged:git'); class Git { final String? workingDirectory; final List<String> _diff; final String? diffFilter; Git({this.workingDirectory, List<String> diff = const [], this.diffFilter}) : _diff = diff; String? _gitdir; String get gitdir => _gitdir ??= Process.runSync('git', ['rev-parse', '--git-dir'], workingDirectory: workingDirectory) .stdout .toString() .trim(); String? _currentBranch; String get currentBranch => _currentBranch ??= Process.runSync( 'git', ['rev-parse', '--abbrev-ref', 'HEAD'], workingDirectory: workingDirectory) .stdout .toString() .trim(); Future<String> status([List<String> args = const []]) async => _stdout(['status', ...args]); Future<String> show([List<String> args = const []]) async => _stdout(['show', ...args]); Future<String> diff([List<String> args = const []]) async => _stdout(['diff', ...args]); Future<ProcessResult> run(List<String> args) async { final result = await Process.run('git', [..._kNoSubmoduleRecurse, ...args], workingDirectory: workingDirectory); final messsages = ['git ${args.join(' ')}']; if (result.stderr.toString().trim().isNotEmpty) { messsages.add(grey(result.stderr.toString().trim())); } if (result.stdout.toString().trim().isNotEmpty) { messsages.add(grey(result.stdout.toString().trim())); } _verbose(messsages.join('\n')); if (result.exitCode != 0) { throw ProcessException( 'git', args, messsages.join('\n'), result.exitCode); } return result; } Future<String> _stdout(List<String> args) async { final result = await run(args); String output = result.stdout as String; if (output.endsWith('\n')) { output = output.replaceFirst(RegExp(r'(\n)+$'), ''); } return output; } Future<List<String>> get stagedFiles async { final args = getDiffArgs(diff: _diff, diffFilter: diffFilter); final output = await _stdout(args); final files = parseGitZOutput(output).toList(); _verbose('Staged files: $files'); return files; } /// /// Get a list of all files with both staged and unstaged modifications. /// Renames have special treatment, since the single status line includes /// both the "from" and "to" filenames, where "from" is no longer on disk. /// Future<List<String>> get partiallyStagedFiles async { final status = await _stdout(['status', '-z']); if (status.isEmpty) { return []; } /// /// See https://git-scm.com/docs/git-status#_short_format /// Entries returned in machine format are separated by a NUL character. /// The first letter of each entry represents current index status, /// and second the working tree. Index and working tree status codes are /// separated from the file name by a space. If an entry includes a /// renamed file, the file names are separated by a NUL character /// (e.g. `to`\0`from`) /// final files = status .split(RegExp(r'\x00(?=[ AMDRCU?!]{2} |$)')) .where((line) { if (line.length > 2) { final index = line[0]; final workingTree = line[1]; return index != ' ' && workingTree != ' ' && index != '?' && workingTree != '?'; } return false; }) .map((line) => line.substring(min(3, line.length))) /// Remove first three letters (index, workingTree, and a whitespace) .where((e) => e.isNotEmpty) /// Filter empty string .toList(); _verbose('Found partially staged files: $files'); return files; } Future<String> get lastCommit async { final output = await _stdout(['log', '-1', '--pretty=%B']); return output.trim(); } Future<int> get commitCount async { final output = await _stdout(['rev-list', '--count', 'HEAD']); return int.parse(output.trim()); } Future<List<String>> get hashes async { final output = await _stdout(['log', '--format=format:%H']); return output.trim().split('\n'); } Future<List<String>> get stashes async { final output = await _stdout(['stash', 'list']); return output.trim().split('\n'); } Future<List<String>> get deletedFiles async { final output = await _stdout(['ls-files', '--deleted']); final files = output.split('\n').where((line) => line.trim().isNotEmpty).toList(); _verbose('Deleted files: $files'); return files; } /// The `stash create` command creates a dangling commit without removing any files, Future<String> createStash() async { final output = await _stdout(['stash', 'create']); return output.trim(); } Future<String> storeStash(String stash, {required String message}) async { final output = await _stdout(['stash', 'store', '--quiet', '-m', message, stash]); return output.trim(); } } /// /// Get git diff arguments /// List<String> getDiffArgs({ List<String> diff = const [], String? diffFilter, }) { /// /// Docs for --diff-filter option: /// @see https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---diff-filterACDMRTUXB82308203 /// final diffFilterArgs = diffFilter != null ? diffFilter.trim() : 'ACMR'; /// Use `--diff branch1...branch2` or `--diff="branch1,branch2", or fall back to default staged files final diffArgs = diff.isNotEmpty ? diff : ['--staged']; /// Docs for -z option: /// @see https://git-scm.com/docs/git-diff#Documentation/git-diff.txt--z return [ 'diff', '--name-only', '-z', '--diff-filter=$diffFilterArgs', ...diffArgs ]; } /// Explicitly never recurse commands into submodules, overriding local/global configuration. /// @see https://git-scm.com/docs/git-config#Documentation/git-config.txt-submodulerecurse /// const _kNoSubmoduleRecurse = ['-c', 'submodule.recurse=false']; /// /// Return array of strings split from the output of `git <something> -z`. /// With `-z`, git prints `fileA\u0000fileB\u0000fileC\u0000` so we need to /// remove the last occurrence of `\u0000` before splitting /// List<String> parseGitZOutput(String input) { return input.isEmpty ? [] : input.replaceFirst(RegExp(r'\u0000$'), '').split('\u0000'); }
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/unit/git_test.dart
import 'package:lint_staged/src/git.dart'; import 'package:test/expect.dart'; import 'package:test/scaffolding.dart'; void main() { group('getDiffArg', () { final customDiff = ['origin/main..custom-branch']; final customDiffArr = ['origin/main', 'custom-branch']; final customDiffFilter = 'a'; test('should default to sane value', () { final diff = getDiffArgs(); expect( diff, equals( ['diff', '--name-only', '-z', '--diff-filter=ACMR', '--staged'])); }); test('should work only with diff set as string', () { final diff = getDiffArgs(diff: customDiff); expect( diff, equals([ 'diff', '--name-only', '-z', '--diff-filter=ACMR', 'origin/main..custom-branch', ])); }); test('should work only with diff set as comma separated list', () { final diff = getDiffArgs(diff: customDiffArr); expect( diff, equals([ 'diff', '--name-only', '-z', '--diff-filter=ACMR', 'origin/main', 'custom-branch', ])); }); test('should work only with diffFilter set', () { final diff = getDiffArgs(diffFilter: customDiffFilter); expect(diff, equals(['diff', '--name-only', '-z', '--diff-filter=a', '--staged'])); }); test('should work with both diff and diffFilter set', () { final diff = getDiffArgs(diff: customDiff, diffFilter: customDiffFilter); expect( diff, equals([ 'diff', '--name-only', '-z', '--diff-filter=a', 'origin/main..custom-branch', ])); }); }); group('parseGitZOutput', () { test('should split string from `git -z` control character', () { final input = 'a\u0000b\u0000c'; expect(parseGitZOutput(input), equals(['a', 'b', 'c'])); }); test('should remove trailing `git -z` control character', () { final input = 'a\u0000'; expect(parseGitZOutput(input), equals(['a'])); }); test('should handle empty input', () { final input = ''; expect(parseGitZOutput(input), equals([])); }); }); }
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/unit/chunk_test.dart
import 'package:lint_staged/src/chunk.dart'; import 'package:test/test.dart'; void main() { group('chunkFiles', () { const files = ['example.js', 'foo.js', 'bar.js', 'foo/bar.js']; test('should default to same value', () { final chunkedFiles = chunkFiles(['foo.js']); expect( chunkedFiles, equals([ ['foo.js'] ])); }); test('should not chunk short argument string', () { final chunkedFiles = chunkFiles(files, maxArgLength: 1000); expect(chunkedFiles, equals([files])); }); test('should chunk too long argument string', () { final chunkedFiles = chunkFiles(files, maxArgLength: 20); expect( chunkedFiles, equals([ [files[0], files[1]], [files[2], files[3]], ])); }); }); }
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/unit/context_test.dart
import 'package:lint_staged/src/context.dart'; import 'package:lint_staged/src/symbols.dart'; import 'package:test/test.dart'; void main() { group('LintStagedContext', () { group('applyModificationsSkipped', () { test('should return false when backup is disabled', () { final ctx = getInitialContext()..shouldBackup = false; expect(applyModifationsSkipped(ctx), false); }); test('should return error message when there is an unkown git error', () { final ctx = getInitialContext() ..shouldBackup = true ..errors = {kGitError}; expect(applyModifationsSkipped(ctx), true); }); }); group('restoreUnstagedChangesSkipped', () { test('should return error message when there is an unkown git error', () { final ctx = getInitialContext()..errors = {kGitError}; expect(restoreUnstagedChangesSkipped(ctx), true); }); }); group('restoreOriginalStateSkipped', () { test('should return error message when there is an unkown git error', () { final ctx = getInitialContext()..errors = {kGitError}; expect(restoreOriginalStateSkipped(ctx), true); }); }); group('shouldSkipCleanup', () { test('should return error message when reverting to original state fails', () { final ctx = getInitialContext()..errors = {kRestoreOriginalStateError}; expect(cleanupSkipped(ctx), true); }); }); }); }
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/integration/git_submodules_test.dart
import 'package:path/path.dart' show join; import 'package:test/test.dart'; import '__fixtures__/config.dart'; import '__fixtures__/file.dart'; import 'utils.dart'; void main() { group('lint_staged', () { test('handles git submodules', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatFix); await project.fs.write('lib/main.dart', kFormattedDart); await project.git.run(['add', '.']); await expectLater( project.gitCommit(gitCommitArgs: ['-m', 'committed pretty file']), completes); // create a new repo for the git submodule to a temp path final anotherProject = IntegrationProject(); await anotherProject.setup(); /// Add the newly-created repo as a submodule in a new path. /// This simulates adding it from a remote. By default file protocol is not allowed, /// see https://git-scm.com/docs/git-config#Documentation/git-config.txt-protocolallow await project.git.run([ '-c', 'protocol.file.allow=always', 'submodule', 'add', '--force', anotherProject.path, './submodule', ]); /// Commit this submodule await project.git.run(['add', '.']); await expectLater( project.gitCommit( allowEmpty: true, gitCommitArgs: ['-m', 'Add submodule']), completes); final submoduleProject = IntegrationProject(join(project.path, 'submodule')); await submoduleProject.fs.write('pubspec.yaml', kConfigFormatExit); /// Stage pretty file await submoduleProject.fs.append('lib/main.dart', kFormattedDart); await submoduleProject.git.run(['add', '.']); /// Run lint_staged with `dart format --set-exit-if-changed` and commit formatted file await submoduleProject.config(); await expectLater(submoduleProject.gitCommit(), completes); /// Nothing is wrong, so a new commit is created expect(await submoduleProject.git.commitCount, equals(2)); expect(await submoduleProject.git.lastCommit, contains('test')); expect(await submoduleProject.fs.read('lib/main.dart'), equals(kFormattedDart)); /// Commit this submodule await project.git.run(['add', '.']); await expectLater( project.gitCommit( allowEmpty: true, gitCommitArgs: ['-m', 'Update submodule']), completes); }); }); }
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/integration/allow_empty_test.dart
import 'package:test/test.dart'; import '__fixtures__/config.dart'; import '__fixtures__/file.dart'; import 'utils.dart'; void main() { group('lint_staged', () { test( 'fails when task reverts staged changes without `--allow-empty`, to prevent an empty git commit', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatFix); // Create and commit a formatted file without running lint_staged // This way the file will be available for the next step await project.fs.write('lib/main.dart', kFormattedDart); await project.git.run(['add', '.']); await project.git.run(['commit', '-m committed formatted file']); // Edit file to be ugly await project.fs.remove('lib/main.dart'); await project.fs.write('lib/main.dart', kUnFormattedDart); await project.git.run(['add', 'lib/main.dart']); // Run lint_staged to automatically format the file // Since formatter reverts all changes, the commit should fail await expectLater(project.gitCommit(), throwsIntegrationTestError); // Something was wrong so the repo is returned to original state expect(await project.git.commitCount, equals(2)); expect( await project.git.lastCommit, contains('committed formatted file')); expect(await project.fs.read('lib/main.dart'), equals(kUnFormattedDart)); }); test( 'creates commit when task reverts staged changed and --allow-empty is used', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatFix); // Create and commit a formatted file without running lint_staged // This way the file will be available for the next step await project.fs.write('lib/main.dart', kFormattedDart); await project.git.run(['add', '.']); await project.git.run(['commit', '-m committed formatted file']); // Edit file to be unformatted await project.fs.remove('lib/main.dart'); await project.fs.write('lib/main.dart', kUnFormattedDart); await project.git.run(['add', 'lib/main.dart']); // Run lint_staged to automatically format the file // Here we also pass '--allow-empty' to gitCommit because this part is not the full lint_staged await expectLater( project.gitCommit( allowEmpty: true, gitCommitArgs: ['-m test', '--allow-empty']), completes); // Nothing was wrong so the empty commit is created expect(await project.git.commitCount, equals(3)); expect(await project.git.lastCommit, contains('test')); expect(await project.git.diff(['-1']), equals('')); expect(await project.fs.read('lib/main.dart'), equals(kFormattedDart)); }); }); }
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/integration/file_resurrection_test.dart
import 'package:test/test.dart'; import '__fixtures__/config.dart'; import '__fixtures__/file.dart'; import 'utils.dart'; void main() { group('lint_staged', () { test('does not resurrect removed files due to git bug when tasks pass', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatExit); await project.fs.remove('README.md'); // Remove file from previous commit await project.fs.write('lib/main.dart', kFormattedDart); await project.git.run(['add', 'lib/main.dart']); await project.gitCommit(); expect(await project.fs.exists('README.md'), isFalse); }); test('does not resurrect removed files in complex case', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatExit); // Add file to index, and remove it from disk await project.fs.write('lib/main.dart', kFormattedDart); await project.git.run(['add', 'lib/main.dart']); await project.fs.remove('lib/main.dart'); // Rename file in index, and remove it from disk final readme = await project.fs.read('README.md'); await project.fs.remove('README.md'); await project.git.run(['add', 'README.md']); await project.fs.write('README_NEW.md', readme!); await project.git.run(['add', 'README_NEW.md']); await project.fs.remove('README_NEW.md'); expect( await project.git.status(['--porcelain']), contains('RD README.md -> README_NEW.md\n' 'AD lib/main.dart\n' '?? pubspec.yaml')); await project.gitCommit(); expect( await project.git.status(['--porcelain']), contains(' D README_NEW.md\n' ' D lib/main.dart\n' '?? pubspec.yaml')); expect(await project.fs.exists('lib/main.dart'), isFalse); expect(await project.fs.exists('README_NEW.md'), isFalse); }); test('does not resurrect removed files due to git bug when tasks fail', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatExit); await project.fs.remove('README.md'); // Remove file from previous commit await project.fs.write('lib/main.dart', kUnFormattedDart); await project.git.run(['add', 'lib/main.dart']); expect( await project.git.status(['--porcelain']), contains(' D README.md\n' 'A lib/main.dart\n' '?? pubspec.yaml')); await expectLater( project.gitCommit(allowEmpty: true), throwsIntegrationTestError); expect( await project.git.status(['--porcelain']), contains(' D README.md\n' 'A lib/main.dart\n' '?? pubspec.yaml')); expect(await project.fs.exists('README.md'), isFalse); }); }); }
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/integration/untracked_files_test.dart
import 'package:test/test.dart'; import '__fixtures__/config.dart'; import '__fixtures__/file.dart'; import 'utils.dart'; void main() { group('lint_staged', () { test('ignores untracked files', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.append('pubspec.yaml', kConfigFormatExit); // Stage pretty file await project.fs.append('lib/main.dart', kFormattedDart); await project.git.run(['add', 'lib/main.dart']); // Add untracked files await project.fs.append('lib/untracked.dart', kFormattedDart); await project.fs.append('.gitattributes', 'binary\n'); await project.fs.write('binary', 'Hello, World!'); // Run lint_staged with `dart format --set-exit-if-changed` and commit formatted file await project.gitCommit(); // Nothing is wrong, so a new commit is created expect(await project.git.commitCount, equals(2)); expect(await project.git.lastCommit, contains('test')); expect(await project.fs.read('lib/main.dart'), equals(kFormattedDart)); expect( await project.fs.read('lib/untracked.dart'), equals(kFormattedDart)); expect(await project.fs.read('binary'), equals('Hello, World!')); }); test('ingores untracked files when task fails', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.append('pubspec.yaml', kConfigFormatExit); // Stage unfixable file await project.fs.append('lib/main.dart', kInvalidDart); await project.git.run(['add', 'lib/main.dart']); // Add untracked files await project.fs.append('lib/untracked.dart', kFormattedDart); await project.fs.append('.gitattributes', 'binary\n'); await project.fs.write('binary', 'Hello, World!'); // Run lint_staged with `dart format --set-exit-if-changed` and commit formatted file expectLater(project.gitCommit(), throwsIntegrationTestError); // Something was wrong so the repo is returned to original state expect(await project.git.commitCount, equals(1)); expect(await project.git.lastCommit, contains('initial commit')); expect(await project.fs.read('lib/main.dart'), equals(kInvalidDart)); expect( await project.fs.read('lib/untracked.dart'), equals(kFormattedDart)); expect(await project.fs.read('binary'), equals('Hello, World!')); }); }); }
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/integration/utils.dart
import 'dart:io'; import 'package:lint_staged/lint_staged.dart'; import 'package:lint_staged/src/fs.dart'; import 'package:lint_staged/src/git.dart'; import 'package:path/path.dart'; import 'package:test/test.dart'; String _temp() => join(Directory.systemTemp.path, 'tmp', 'husky_test_${DateTime.now().microsecondsSinceEpoch}'); class IntegrationProject { final String path; late final Git git = Git(workingDirectory: path); late final fs = FileSystem(path); IntegrationProject([String? directory]) : path = directory ?? _temp(); Future<void> setup({bool initialCommit = true}) async { /// Git init await Process.run('git', ['init', path]); await fs.write('.gitattributes', '*.dart text eol=lf'); /// Git config await config(); if (initialCommit) { await _initialCommit(); } } Future<void> config() async { await git.run(['config', 'user.name', 'test']); await git.run(['config', 'user.email', 'test@example.com']); await git.run(['config', 'commit.gpgsign', 'false']); await git.run(['config', 'merge.conflictstyle', 'merge']); } Future<void> _initialCommit() async { await fs.append('README.md', '# Test\n'); await git.run(['add', 'README.md', '.gitattributes']); await git.run(['commit', '-m initial commit']); } Future<void> gitCommit({ bool allowEmpty = false, int maxArgLength = 0, List<String>? gitCommitArgs, }) async { final passed = await lintStaged( maxArgLength: maxArgLength, allowEmpty: allowEmpty, workingDirectory: path); if (!passed) { throw IntegrationTestError(); } final commitArgs = gitCommitArgs ?? ['-m test']; await git.run(['commit', ...commitArgs]); } } class IntegrationTestError {} final Matcher throwsIntegrationTestError = throwsA(isA<IntegrationTestError>()); final Matcher throwsProcessException = throwsA(isA<ProcessException>());
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/integration/basic_functionality_test.dart
import 'package:test/test.dart'; import '__fixtures__/config.dart'; import '__fixtures__/file.dart'; import 'utils.dart'; void main() { group('lint_staged', () { test('commits entire staged file when no errors from linter', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatExit); // Stage formatted file await project.fs.write('lib/main.dart', kFormattedDart); await project.git.run(['add', 'lib/main.dart']); // Run lint_staged to automatically format the file and commit formatted file await project.gitCommit(); // Nothing is wrong, so a new commit created expect(await project.git.commitCount, equals(2)); expect(await project.git.lastCommit, contains('test')); expect(await project.fs.read('lib/main.dart'), equals(kFormattedDart)); }); test('commits entire staged file when no errors and linter modifies file', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatFix); // Stage multi unformatted files await project.fs.write('lib/main.dart', kUnFormattedDart); await project.git.run(['add', 'lib/main.dart']); await project.fs.write('lib/foo.dart', kUnFormattedDart); await project.git.run(['add', 'lib/foo.dart']); // Run lint_staged to automatically format the file and commit formatted files await project.gitCommit(); // Nothing was wrong so the empty commit is created expect(await project.git.commitCount, equals(2)); expect(await project.git.lastCommit, contains('test')); expect(await project.fs.read('lib/main.dart'), equals(kFormattedDart)); expect(await project.fs.read('lib/foo.dart'), equals(kFormattedDart)); }); test('fails to commit entire staged file when errors from linter', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatExit); // Stage unformatted file await project.fs.write('lib/main.dart', kUnFormattedDart); await project.git.run(['add', 'lib/main.dart']); final status = await project.git.status(); // Run lint_staged to automatically format the file and commit formatted files await expectLater(project.gitCommit(), throwsIntegrationTestError); // Nothing was wrong so the empty commit is created expect(await project.git.commitCount, equals(1)); expect(await project.git.lastCommit, contains('initial commit')); expect(await project.git.status(), equals(status)); expect(await project.fs.read('lib/main.dart'), equals(kUnFormattedDart)); }); test( 'fails to commit entire staged file when errors from linter and linter modifies files', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatFix); // Stage invalid file await project.fs.write('lib/main.dart', kInvalidDart); await project.git.run(['add', 'lib/main.dart']); final status = await project.git.status(); // Run lint_staged to automatically format the file and commit formatted files await expectLater(project.gitCommit(), throwsIntegrationTestError); // Nothing was wrong so the empty commit is created expect(await project.git.commitCount, equals(1)); expect(await project.git.lastCommit, contains('initial commit')); expect(await project.git.status(), equals(status)); expect(await project.fs.read('lib/main.dart'), equals(kInvalidDart)); }); test('clears unstaged changes when linter applies same changes', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.append('pubspec.yaml', kConfigFormatFix); // Stage unformatted file await project.fs.append( 'lib/main.dart', kUnFormattedDart, ); await project.git.run(['add', 'lib/main.dart']); // Replace unformatted file with formatted but do not stage changes await project.fs.remove('lib/main.dart'); await project.fs.append('lib/main.dart', kFormattedDart); // Run lint_staged to automatically format the file and commit formatted files await project.gitCommit(); // Nothing was wrong so the empty commit is created expect(await project.git.commitCount, equals(2)); expect(await project.git.lastCommit, contains('test')); // Latest commit contains pretty file // `git show` strips empty line from here here expect(await project.git.show(['HEAD:lib/main.dart']), equals(kFormattedDart.trim())); // Nothing is staged expect(await project.git.status(), contains('nothing added to commit')); // File is pretty, and has been edited expect(await project.fs.read('lib/main.dart'), equals(kFormattedDart)); }); test('runs chunked tasks when necessary', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatExit); // Stage two files await project.fs.write('lib/main.dart', kFormattedDart); await project.git.run(['add', 'lib/main.dart']); await project.fs.write('lib/foo.dart', kFormattedDart); await project.git.run(['add', 'lib/foo.dart']); // Run lint_staged to automatically format the file and commit formatted files // Set maxArgLength low enough so that chunking is used await project.gitCommit(maxArgLength: 10); // Nothing was wrong so the empty commit is created expect(await project.git.commitCount, equals(2)); expect(await project.git.lastCommit, contains('test')); expect(await project.fs.read('lib/main.dart'), equals(kFormattedDart)); expect(await project.fs.read('lib/foo.dart'), equals(kFormattedDart)); }); test('fails when backup stash is missing', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); final config = '''lint_staged: 'lib/**.dart': git stash drop '''; await project.fs.write('pubspec.yaml', config); // Stage two files await project.fs.write('lib/main.dart', kFormattedDart); await project.git.run(['add', 'lib/main.dart']); // Run lint_staged to automatically format the file and commit formatted files // Set maxArgLength low enough so that chunking is used expect(project.gitCommit(maxArgLength: 10), throwsIntegrationTestError); }); test('works when a branch named stash exists', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatExit); // create a new branch called stash await project.git.run(['branch', 'stash']); // Stage two files await project.fs.write('lib/main.dart', kFormattedDart); await project.git.run(['add', 'lib/main.dart']); // Run lint_staged to automatically format the file and commit formatted file await project.gitCommit(); // Nothing is wrong, so a new commit is created and file is pretty expect(await project.git.commitCount, equals(2)); expect(await project.git.lastCommit, contains('test')); expect(await project.fs.read('lib/main.dart'), equals(kFormattedDart)); }); test('ignores files given in pubspec.yaml', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatFixWithIgnore); // Stage multi unformatted files await project.fs.write('lib/main.dart', kUnFormattedDart); await project.git.run(['add', 'lib/main.dart']); await project.fs.write('lib/foo.g.dart', kUnFormattedDart); await project.git.run(['add', 'lib/foo.g.dart']); // Run lint_staged to automatically format the file and commit formatted files await project.gitCommit(); // main.dart should be formatted, while foo.g.dart should not expect(await project.git.commitCount, equals(2)); expect(await project.git.lastCommit, contains('test')); expect(await project.fs.read('lib/main.dart'), equals(kFormattedDart)); expect(await project.fs.read('lib/foo.g.dart'), equals(kUnFormattedDart)); }); }); }
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/integration/merge_conflict_test.dart
import 'package:test/test.dart'; import '__fixtures__/config.dart'; import 'utils.dart'; void main() { group('lint_staged', () { test('handles merge conflicts', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); final branch = project.git.currentBranch; final fileInBranchA = 'String foo = "foo";\n'; final fileInBranchB = 'String foo="bar";\n'; final fileInBranchBFixed = 'String foo = "bar";\n'; // Create one branch await project.git.run(['checkout', '-b', 'branch-a']); await project.fs.append('lib/main.dart', fileInBranchA); await project.fs.append('pubspec.yaml', kConfigFormatFix); await project.git.run(['add', '.']); await project.gitCommit(gitCommitArgs: ['-m commit a']); expect(await project.fs.read('lib/main.dart'), equals(fileInBranchA)); await project.git.run(['checkout', branch]); // Create another branch await project.git.run(['checkout', '-b', 'branch-b']); await project.fs.append('lib/main.dart', fileInBranchB); await project.fs.append('pubspec.yaml', kConfigFormatFix); await project.git.run(['add', '.']); await project.gitCommit(gitCommitArgs: ['-m commit b']); expect( await project.fs.read('lib/main.dart'), equals(fileInBranchBFixed)); // Merge first branch await project.git.run(['checkout', branch]); await project.git.run(['merge', 'branch-a']); expect(await project.fs.read('lib/main.dart'), equals(fileInBranchA)); expect(await project.git.lastCommit, contains('commit a')); // Merge second branch, causing merge conflict final merge = project.git.run(['merge', 'branch-b']); await expectLater(merge, throwsException); expect( await project.fs.read('lib/main.dart'), contains('<<<<<<< HEAD\n' 'String foo = "foo";\n' '=======\n' 'String foo = "bar";\n' '>>>>>>> branch-b\n' '')); // Fix conflict and commit using lint_staged await project.fs.write('lib/main.dart', fileInBranchB); expect(await project.fs.read('lib/main.dart'), equals(fileInBranchB)); await project.git.run(['add', '.']); await project.gitCommit(gitCommitArgs: ['--no-edit']); // Nothing is wrong, so a new commit is created and file is pretty expect(await project.git.commitCount, equals(4)); final log = await project.git.lastCommit; expect(log, contains('Merge branch \'branch-b\'')); expect(log, contains('Conflicts:')); expect(log, contains('lib/main.dart')); expect( await project.fs.read('lib/main.dart'), equals(fileInBranchBFixed)); }); test('handles merge conflict when task errors', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); final branch = project.git.currentBranch; final fileInBranchA = 'String foo = "foo";\n'; final fileInBranchB = 'String foo="bar";\n'; final fileInBranchBFixed = 'String foo = "bar";\n'; // Create one branch await project.git.run(['checkout', '-b', 'branch-a']); await project.fs.append('lib/main.dart', fileInBranchA); await project.fs.append('pubspec.yaml', kConfigFormatFix); await project.git.run(['add', '.']); await project.gitCommit(gitCommitArgs: ['-m commit a']); expect(await project.fs.read('lib/main.dart'), equals(fileInBranchA)); await project.git.run(['checkout', branch]); // Create another branch await project.git.run(['checkout', '-b', 'branch-b']); await project.fs.append('lib/main.dart', fileInBranchB); await project.fs.append('pubspec.yaml', kConfigFormatFix); await project.git.run(['add', '.']); await project.gitCommit(gitCommitArgs: ['-m commit b']); expect( await project.fs.read('lib/main.dart'), equals(fileInBranchBFixed)); // Merge first branch await project.git.run(['checkout', branch]); await project.git.run(['merge', 'branch-a']); expect(await project.fs.read('lib/main.dart'), equals(fileInBranchA)); expect(await project.git.lastCommit, contains('commit a')); // Merge second branch, causing merge conflict await expectLater( project.git.run(['merge', 'branch-b']), throwsProcessException); expect( await project.fs.read('lib/main.dart'), contains('<<<<<<< HEAD\n' 'String foo = "foo";\n' '=======\n' 'String foo = "bar";\n' '>>>>>>> branch-b\n' '')); // Fix conflict and commit using lint_staged await project.fs.write('lib/main.dart', fileInBranchB); expect(await project.fs.read('lib/main.dart'), equals(fileInBranchB)); await project.git.run(['add', '.']); await project.fs.write('pubspec.yaml', kConfigFormatExit); await expectLater(project.gitCommit(), throwsIntegrationTestError); // Something went wrong, so lintStaged failed and merge is still going expect(await project.git.commitCount, equals(2)); expect(await project.git.status(), contains('All conflicts fixed but you are still merging')); expect(await project.fs.read('lib/main.dart'), equals(fileInBranchB)); }); }); }
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/integration/partially_staged_changes_test.dart
import 'package:test/test.dart'; import '__fixtures__/config.dart'; import '__fixtures__/file.dart'; import 'utils.dart'; void main() { group('lint_staged', () { test( 'commits partial change from partially staged file when no errors from linter', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.append('pubspec.yaml', kConfigFormatExit); // Stage pretty file await project.fs.append('lib/main.dart', kFormattedDart); await project.git.run(['add', 'lib/main.dart']); // Edit pretty file but do not stage changes final appended = '\nprint("test");\n'; await project.fs.append('lib/main.dart', appended); await project.gitCommit(); // Nothing is wrong, so a new commit is created and file is pretty expect(await project.git.commitCount, equals(2)); expect(await project.git.lastCommit, contains('test')); // Latest commit contains pretty file // `git show` strips empty line from here here expect(await project.git.show(['HEAD:lib/main.dart']), equals(kFormattedDart.trim())); // Since edit was not staged, the file is still modified final status = await project.git.status(); expect(status, contains('modified: lib/main.dart')); expect(status, contains('no changes added to commit')); expect(await project.fs.read('lib/main.dart'), equals(kFormattedDart + appended)); }); test( 'commits partial change from partially staged file when no errors from linter and linter modifies file', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.append('pubspec.yaml', kConfigFormatFix); // Stage ugly file await project.fs.append('lib/main.dart', kUnFormattedDart); await project.git.run(['add', 'lib/main.dart']); // Edit ugly file but do not stage changes final appended = '\n\nprint("test");\n'; await project.fs.append('lib/main.dart', appended); await project.gitCommit(); // Nothing is wrong, so a new commit is created and file is pretty expect(await project.git.commitCount, equals(2)); expect(await project.git.lastCommit, contains('test')); // Latest commit contains pretty file // `git show` strips empty line from here here expect(await project.git.show(['HEAD:lib/main.dart']), equals(kFormattedDart.trim())); // Nothing is staged final status = await project.git.status(); expect(status, contains('modified: lib/main.dart')); expect(status, contains('no changes added to commit')); // File is pretty, and has been edited expect(await project.fs.read('lib/main.dart'), equals(kFormattedDart + appended)); }); test( 'fails to commit partial change from partially staged file when errors from linter', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.append('pubspec.yaml', kConfigFormatExit); // Stage ugly file await project.fs.append('lib/main.dart', kUnFormattedDart); await project.git.run(['add', 'lib/main.dart']); // Edit ugly file but do not stage changes final appended = '\nprint("test");\n'; await project.fs.append('lib/main.dart', appended); final status = await project.git.status(); // Run lint_staged with `dart format --set-exit-if-changed` to break the linter await expectLater(project.gitCommit(), throwsIntegrationTestError); // Something was wrong so the repo is returned to original state expect(await project.git.commitCount, equals(1)); expect(await project.git.lastCommit, contains('initial commit')); expect(await project.git.status(), equals(status)); expect(await project.fs.read('lib/main.dart'), equals(kUnFormattedDart + appended)); }); test( 'fails to commit partial change from partially staged file when errors from linter and linter modifies files', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.append('pubspec.yaml', kConfigFormatFix); // Add unfixable file to commit so `prettier --write` breaks await project.fs.append('lib/main.dart', kInvalidDart); await project.git.run(['add', 'lib/main.dart']); // Edit unfixable file but do not stage changes final appended = '\nprint("test");\n'; await project.fs.append('lib/main.dart', appended); final status = await project.git.status(); await expectLater(project.gitCommit(), throwsIntegrationTestError); // Something was wrong so the repo is returned to original state expect(await project.git.commitCount, equals(1)); expect(await project.git.lastCommit, contains('initial commit')); expect(await project.git.status(), equals(status)); expect(await project.fs.read('lib/main.dart'), equals(kInvalidDart + appended)); }); }); }
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/integration/git_worktrees_test.dart
import 'package:path/path.dart' show join; import 'package:test/test.dart'; import '__fixtures__/config.dart'; import '__fixtures__/file.dart'; import 'utils.dart'; void main() { group('lint_staged', () { test('handles git worktrees', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); // create a new branch and add it as worktree final worktreeProject = IntegrationProject(join(project.path, 'worktree')); await project.git.run(['branch', 'test']); await project.git.run(['worktree', 'add', worktreeProject.path, 'test']); // Stage pretty file await worktreeProject.fs.write('pubspec.yaml', kConfigFormatExit); await worktreeProject.fs.append('lib/main.dart', kFormattedDart); await worktreeProject.git.run(['add', 'lib/main.dart']); // Run lint_staged with `dart format --set-exit-if-changed` and commit formatted file await worktreeProject.gitCommit(); // Nothing is wrong, so a new commit is created expect(await worktreeProject.git.commitCount, equals(2)); expect(await worktreeProject.git.lastCommit, contains('test')); expect(await worktreeProject.fs.read('lib/main.dart'), equals(kFormattedDart)); }); }); }
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/integration/diff_test.dart
import 'package:lint_staged/lint_staged.dart'; import 'package:test/test.dart'; import '__fixtures__/config.dart'; import '__fixtures__/file.dart'; import 'utils.dart'; void main() { group('lint_staged', () { test('supports overriding file list using --diff', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatExit); // Commit unformatted file await project.fs.write('lib/main.dart', kUnFormattedDart); await project.git.run(['add', '.']); await project.git.run(['commit', '-m unformatted']); final hashes = await project.git.hashes; expect(hashes.length, 2); // Run lint_staged with `--diff` between the two commits. // Nothing is staged at this point, so don't run `gitCommit` final passed = await lintStaged( diff: ['${hashes[1]}..${hashes[0]}'], stash: false, workingDirectory: project.path, ); // lint_staged failed because commit diff contains unformatted file expect(passed, isFalse); }); test('supports overriding default --diff-filter', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatExit); // Stage unformatted file await project.fs.write('lib/main.dart', kUnFormattedDart); await project.git.run(['add', '.']); // Run lint_staged with `--diff-filter=D` to include only deleted files. final passed = await lintStaged( diffFilter: 'D', stash: false, workingDirectory: project.path, ); // lint_staged passed because no matching (deleted) files expect(passed, isTrue); }); }); }
0
mirrored_repositories/lint_staged/test
mirrored_repositories/lint_staged/test/integration/git_amend_test.dart
import 'package:test/test.dart'; import '__fixtures__/config.dart'; import '__fixtures__/file.dart'; import 'utils.dart'; void main() { group('lint_staged', () { test('works when amending previous commit with unstaged changes', () async { final project = IntegrationProject(); print('dir: ${project.path}'); await project.setup(); await project.fs.write('pubspec.yaml', kConfigFormatExit); // Edit file from previous commit await project.fs.append('README.md', '\n## Amended\n'); await project.git.run(['add', 'README.md']); // Edit again, but keep it unstaged await project.fs.append('README.md', '\n## Edited\n'); await project.fs.append('lib/main.dart', kFormattedDart); // Run lint_staged with `dart format --set-exit-if-changed` and commit formatted file await project.gitCommit(gitCommitArgs: ['--amend', '--no-edit']); // Nothing is wrong, so the commit was amended expect(await project.git.commitCount, equals(1)); expect(await project.git.lastCommit, contains('initial commit')); expect( await project.fs.read('README.md'), contains('# Test\n' '\n## Amended\n' '\n## Edited\n')); expect(await project.fs.read('lib/main.dart'), equals(kFormattedDart)); final status = await project.git.status(); expect(status, contains('modified: README.md')); expect(status, contains('lib/')); expect(status, contains('no changes added to commit')); }); }); }
0
mirrored_repositories/lint_staged/test/integration
mirrored_repositories/lint_staged/test/integration/__fixtures__/file.dart
const kFormattedDart = '''const kTestMap = { 'foo': 'bar', }; '''; const kUnFormattedDart = '''const kTestMap = { 'foo': 'bar', }; '''; const kInvalidDart = '''const kTestMap = { 'foo': 'bar', ''';
0
mirrored_repositories/lint_staged/test/integration
mirrored_repositories/lint_staged/test/integration/__fixtures__/config.dart
const kConfigFormatFix = '''lint_staged: 'lib/**.dart': dart format --fix '''; const kConfigFormatFixWithIgnore = '''lint_staged: 'lib/**.dart': dart format --fix '!lib/**.g.dart': dart format --fix '''; const kConfigFormatExit = '''lint_staged: 'lib/**.dart': dart format --set-exit-if-changed ''';
0
mirrored_repositories/lint_staged
mirrored_repositories/lint_staged/bin/lint_staged.dart
import 'dart:io'; import 'package:args/args.dart'; import 'package:lint_staged/lint_staged.dart'; void main(List<String> arguments) async { final argParser = ArgParser() ..addMultiOption('diff', help: 'Override the default "--staged" flag of "git diff" to get list of files. Implies "--no-stash".') ..addOption('diff-filter', help: 'Override the default "--diff-filter=ACMR" flag of "git diff" to get list of files') ..addFlag('allow-empty', help: 'Allow empty commits when tasks revert all staged changes') ..addFlag('stash', defaultsTo: true, negatable: true, help: 'Enable the backup stash, and revert in case of errors'); final argResults = argParser.parse(arguments); final allowEmpty = argResults['allow-empty'] == true; final diff = argResults['diff']; final diffFilter = argResults['diff-filter']; final stash = argResults['stash'] == true; final passed = await lintStaged( allowEmpty: allowEmpty, diff: diff, diffFilter: diffFilter, stash: stash, maxArgLength: _maxArgLength ~/ 2, ); exit(passed ? 0 : 1); } /// /// Get the maximum length of a command-line argument string based on current platform /// /// https://serverfault.com/questions/69430/what-is-the-maximum-length-of-a-command-line-in-mac-os-x /// https://support.microsoft.com/en-us/help/830473/command-prompt-cmd-exe-command-line-string-limitation /// https://unix.stackexchange.com/a/120652 /// int get _maxArgLength { if (Platform.isMacOS) { return 262144; } return 131072; }
0
mirrored_repositories/flutter-auto-world
mirrored_repositories/flutter-auto-world/lib/main.dart
import 'package:auto_world/config/theme.dart'; import 'package:auto_world/screens/home.dart'; import 'package:auto_world/screens/login.dart'; import 'package:auto_world/screens/register.dart'; import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return MaterialApp( debugShowCheckedModeBanner: false, initialRoute: "/home", routes: { "/login": (_) => Login(), "/register": (_) => Register(), "/home": (_) => Home() }, theme: ThemeData( fontFamily: "Sansation", appBarTheme: AppBarTheme( elevation: 0.0, color: secondary, ), primarySwatch: primarySwatch, primaryColor: primary, accentColor: primary, buttonColor: primary, scaffoldBackgroundColor: secondary, buttonTheme: ButtonThemeData( buttonColor: secondary ), primaryIconTheme: IconThemeData(color: Colors.white), primaryTextTheme: TextTheme( title: TextStyle(color: Colors.white), ), ), ); } }
0
mirrored_repositories/flutter-auto-world/lib
mirrored_repositories/flutter-auto-world/lib/widgets/customDivider.dart
import 'package:auto_world/config/theme.dart'; import 'package:flutter/material.dart'; class CustomDivider extends StatelessWidget{ @override Widget build(BuildContext context) { // TODO: implement build return Divider( height: 1, color: primary.withOpacity(.4), indent: 10, endIndent: 10, ); } }
0
mirrored_repositories/flutter-auto-world/lib
mirrored_repositories/flutter-auto-world/lib/widgets/customCard.dart
import 'package:auto_world/config/theme.dart'; import 'package:flutter/material.dart'; class CustomCard extends StatelessWidget { Widget child; CustomCard({@required this.child}) : assert(child != null); @override Widget build(BuildContext context) { // TODO: implement build return Container( margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: secondary, boxShadow: [ BoxShadow( color: Color(0xff000000).withOpacity(.2), spreadRadius: 0, blurRadius: 10, ), ], ), child: ClipRRect( borderRadius: BorderRadius.circular(10), child: child, ), ); } }
0
mirrored_repositories/flutter-auto-world/lib
mirrored_repositories/flutter-auto-world/lib/widgets/customButton.dart
import 'package:auto_world/config/theme.dart'; import 'package:flutter/material.dart'; class CustomButton extends StatelessWidget{ String text; GestureTapCallback onTap; CustomButton({@required this.text, this.onTap}): assert(text != null); @override Widget build(BuildContext context) { // TODO: implement build return Container( child: FlatButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5) ), disabledColor: primary.withOpacity(.8), color: primary, child: Container( alignment: Alignment.center, width: double.infinity, height: 45, child: Text(text, style: TextStyle(fontSize: 18, color: secondary),), ), onPressed: onTap ?? null, ), ); } } class SmallCustomButton extends StatelessWidget{ String text; GestureTapCallback onTap; SmallCustomButton({@required this.text, this.onTap}): assert(text != null); @override Widget build(BuildContext context) { // TODO: implement build return FlatButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5) ), disabledColor: primary.withOpacity(.8), color: primary, child: Container( alignment: Alignment.center, width: double.infinity, height: 20, child: Text(text, style: TextStyle(fontSize: 14, color: secondary),), ), onPressed: onTap ?? null, ); } }
0
mirrored_repositories/flutter-auto-world/lib
mirrored_repositories/flutter-auto-world/lib/widgets/customInputField.dart
import 'package:auto_world/config/theme.dart'; import 'package:flutter/material.dart'; typedef ValueCallback(String value); class CustomInputField extends StatelessWidget { String labelText; ValueCallback validator; ValueCallback onFieldSubmit; bool isPassword; FocusNode focusNode; TextEditingController controller; TextInputType textInputType; TextInputAction textInputAction; int maxLines = 1; CustomInputField({ this.labelText, this.validator, this.isPassword = false, this.controller, this.focusNode, this.textInputType, this.textInputAction, this.onFieldSubmit, this.maxLines = 1 }); @override Widget build(BuildContext context) { // TODO: implement build return TextFormField( textInputAction: textInputAction ?? null, focusNode: focusNode ?? null, controller: controller ?? null, validator: validator, cursorColor: primary, obscureText: isPassword, onChanged: (value){ }, onFieldSubmitted: onFieldSubmit ?? null, keyboardType: textInputType ?? null, maxLines: maxLines ?? null, style: TextStyle(color: primary, fontSize: 15), decoration: InputDecoration( contentPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 5), labelText: textInputType == TextInputType.multiline ? null : labelText, hintText: textInputType == TextInputType.multiline ? labelText : null, hasFloatingPlaceholder: textInputType == TextInputType.multiline ? false : true, border: OutlineInputBorder(), errorBorder: OutlineInputBorder( borderSide: BorderSide( color: Colors.red, ), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide( color: primary, ), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide( color: primary, ), ), labelStyle: TextStyle(color: primary, fontSize: 15), hintStyle: TextStyle(color: primary, fontSize: 15), ), ); } }
0
mirrored_repositories/flutter-auto-world/lib
mirrored_repositories/flutter-auto-world/lib/models/videoModel.dart
class VideoModel { int id; String name; String url; String image; VideoModel({this.image, this.name, this.url, this.id}); factory VideoModel.fromJson(Map json) { return VideoModel( id: json['id'], name: json['name'], url: json['url'], image: json['image']); } } List<VideoModel> videos = [ VideoModel( name: "Triumph Daytona 675R Sports bike PowerDrift review ", image: "https://mcn-images.bauersecure.com/PageFiles/488517/123.jpg", url: "vZhNv3ThdlI", id: 1, ), VideoModel( name: "Ducati 959 Panigale", image: "https://i.pinimg.com/originals/42/df/f2/42dff23c7362999cc389e9dff46268bf.jpg", url: "edzcKRgN_sg", id: 2, ), VideoModel( name: "1299 Superleggera ", image: "https://i.pinimg.com/originals/aa/7f/04/aa7f04719a25863f24489207b18b29e3.jpg", url: "U1_S-o_-cI8", id: 3, ) ];
0
mirrored_repositories/flutter-auto-world/lib
mirrored_repositories/flutter-auto-world/lib/config/theme.dart
import 'package:flutter/material.dart'; Color primary = Color(0xffffffff); Color secondary = Color(0xff333333); String logoUrl = 'assets/images/logo.png'; // logo_dark const int _orangePrimaryValue = 0xff333333; const MaterialColor primarySwatch = MaterialColor( _orangePrimaryValue, <int, Color>{ 50: Color(0xffffffff), 100: Color(0xffffffff), 200: Color(0xffffffff), 300: Color(0xffffffff), 400: Color(0xFFFF9480), 500: Color(0xffffffff), 600: Color(0xffffffff), 700: Color(0xffffffff), 800: Color(0xffffffff), 900: Color(0xffffffff), }, );
0
mirrored_repositories/flutter-auto-world/lib
mirrored_repositories/flutter-auto-world/lib/screens/register.dart
import 'package:auto_world/config/theme.dart'; import 'package:auto_world/widgets/customButton.dart'; import 'package:auto_world/widgets/customInputField.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class Register extends StatefulWidget { @override State<StatefulWidget> createState() { // TODO: implement createState return RegisterState(); } } class RegisterState extends State<Register> { final _formKey = GlobalKey<FormState>(); bool autoValid = false; TextEditingController emailCtrl; TextEditingController passCtrl; FocusNode email; FocusNode password; @override void initState() { // TODO: implement initState super.initState(); emailCtrl = TextEditingController(); passCtrl = TextEditingController(); email = FocusNode(); password = FocusNode(); } unFocus(){ password?.unfocus(); email?.unfocus(); } @override void dispose() { // TODO: implement dispose super.dispose(); emailCtrl?.dispose(); passCtrl?.dispose(); email?.dispose(); password?.dispose(); } onSubmit(){ unFocus(); setState(() { autoValid = true; }); if(_formKey.currentState.validate()){ print("VALIDATE>>>>>>>>>>"); Navigator.pushNamedAndRemoveUntil(context, "/home", (Route<dynamic> route) => true); } } @override Widget build(BuildContext context) { Size size = MediaQuery.of(context).size; double height = size.height; // TODO: implement build return Scaffold( body: Container( padding: EdgeInsets.all(20), child: GestureDetector( onTap: (){ FocusScope.of(context).unfocus(); }, child: SafeArea( child: SingleChildScrollView( child: Form( key: _formKey, autovalidate: autoValid, child: Column( children: <Widget>[ SizedBox(height: 50,), Container( height: 70, child: Image.asset(logoUrl) ), SizedBox(height: 20,), Container( child: Text("Create new Account", style: TextStyle(color: primary, fontSize: 30),) ), SizedBox(height: 30,), Container( alignment: Alignment.center, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ CustomInputField( textInputType: TextInputType.emailAddress, textInputAction: TextInputAction.next, controller: emailCtrl, focusNode: email, labelText: "Email", validator: (value){ print("value $value"); if(value == null || value == ''){ return "Email is required"; } return null; }, onFieldSubmit: (value){ password.requestFocus(); }, ), SizedBox( height: 10, ), CustomInputField( textInputAction: TextInputAction.done, textInputType: TextInputType.text, focusNode: password, controller: passCtrl, labelText: "Password", isPassword: true, validator: (value){ if(value == null || value == ''){ return "Password is required"; } return null; }, onFieldSubmit: (value){ onSubmit(); }, ), SizedBox( height: 20, ), CustomButton( text: "Register", onTap: (){ onSubmit(); }, ) ], ), ), Container( alignment: Alignment.centerRight, padding: EdgeInsets.symmetric(vertical: 10), child: Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ GestureDetector( onTap: (){ Navigator.pushNamedAndRemoveUntil(context, "/login", (Route<dynamic> route) => true); }, child: Text("Already have account ?", style: TextStyle(color: primary),), ), ], ) ) ], ), ), ), ), ), ), ); } }
0
mirrored_repositories/flutter-auto-world/lib
mirrored_repositories/flutter-auto-world/lib/screens/images.dart
import 'package:auto_world/config/theme.dart'; import 'package:auto_world/widgets/customCard.dart'; import 'package:flutter/material.dart'; class ImagesPage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return ListView.builder( itemBuilder: (context, index) { return Container( height: 200, child: ImageItemWidget( index: index, ), ); }, itemCount: 100, ); } } class ImageItemWidget extends StatelessWidget { int index; ImageItemWidget({this.index}); @override Widget build(BuildContext context) { // TODO: implement build return Container( child: Stack( children: <Widget>[ CustomCard( child: Hero( tag: "hero_tag_$index", child: GestureDetector( onTap: () { Navigator.of(context).push(MaterialPageRoute( builder: (_) => ImageItemView( index: index, ))); }, child: Container( width: double.infinity, child: Image.network( "https://image.freepik.com/free-photo/fast-car-street-blurry-background-automotive_33790-62.jpg", fit: BoxFit.cover, ), ), ), ), ), Positioned( right: 0, bottom: 0, child: Hero( tag: "fav_btn_$index", child: Material( clipBehavior: Clip.hardEdge, color: Colors.transparent, child: Container( padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10), child: IconButton( onPressed: () {}, icon: Icon( Icons.favorite, color: primary, ), ), ), ), ), ) ], ), ); } } /* * * */ class ImageItemView extends StatelessWidget { int index; ImageItemView({this.index}); @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar(), body: Container( alignment: Alignment.center, child: Column( children: <Widget>[ Expanded( child: Hero( tag: "hero_tag_$index", child: Image.network( "https://image.freepik.com/free-photo/fast-car-street-blurry-background-automotive_33790-62.jpg", fit: BoxFit.contain, ), ), ), Container( margin: EdgeInsets.all(10), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RaisedButton( elevation: 0, color: Colors.transparent, onPressed: () {}, shape: CircleBorder(), child: Icon( Icons.file_download, color: primary, ), ), Hero( tag: "fav_btn_$index", child: RaisedButton( elevation: 0, color: Colors.transparent, onPressed: () {}, shape: CircleBorder(), child: Icon( Icons.favorite, color: primary, ), ), ) ], ), ) ], )), ); } }
0
mirrored_repositories/flutter-auto-world/lib
mirrored_repositories/flutter-auto-world/lib/screens/login.dart
import 'package:auto_world/config/theme.dart'; import 'package:auto_world/widgets/customButton.dart'; import 'package:auto_world/widgets/customInputField.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class Login extends StatefulWidget { @override State<StatefulWidget> createState() { // TODO: implement createState return LoginState(); } } class LoginState extends State<Login> { final _formKey = GlobalKey<FormState>(); bool autoValid = false; TextEditingController emailCtrl; TextEditingController passCtrl; FocusNode email; FocusNode password; @override void initState() { // TODO: implement initState super.initState(); emailCtrl = TextEditingController(); passCtrl = TextEditingController(); email = FocusNode(); password = FocusNode(); } unFocus(){ password?.unfocus(); email?.unfocus(); } @override void dispose() { // TODO: implement dispose super.dispose(); emailCtrl?.dispose(); passCtrl?.dispose(); email?.dispose(); password?.dispose(); } onSubmit(){ unFocus(); setState(() { autoValid = true; }); if(_formKey.currentState.validate()){ print("VALIDATE>>>>>>>>>>"); Navigator.pushNamedAndRemoveUntil(context, "/home", (Route<dynamic> route) => false); // Navigator.pushAndRemoveUntil(context, // MaterialPageRoute(builder: (BuildContext context) => Login()), // ModalRoute.withName('/')); } } @override Widget build(BuildContext context) { Size size = MediaQuery.of(context).size; double height = size.height; // TODO: implement build return Scaffold( body: Container( padding: EdgeInsets.all(20), child: GestureDetector( onTap: (){ FocusScope.of(context).unfocus(); }, child: SafeArea( child: SingleChildScrollView( child: Form( key: _formKey, autovalidate: autoValid, child: Column( children: <Widget>[ SizedBox(height: 50,), Container( height: 70, child: Image.asset(logoUrl) ), SizedBox(height: 20,), Container( child: Text("Login", style: TextStyle(color: primary, fontSize: 30),) ), SizedBox(height: 30,), Container( alignment: Alignment.center, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ CustomInputField( textInputType: TextInputType.emailAddress, textInputAction: TextInputAction.next, controller: emailCtrl, focusNode: email, labelText: "Email", validator: (value){ print("value $value"); if(value == null || value == ''){ return "Email is required"; } return null; }, onFieldSubmit: (value){ password.requestFocus(); }, ), SizedBox( height: 10, ), CustomInputField( textInputAction: TextInputAction.done, textInputType: TextInputType.text, focusNode: password, controller: passCtrl, labelText: "Password", isPassword: true, validator: (value){ if(value == null || value == ''){ return "Password is required"; } return null; }, onFieldSubmit: (value){ onSubmit(); }, ), SizedBox( height: 20, ), CustomButton( text: "Login", onTap: (){ onSubmit(); }, ) ], ), ), Container( alignment: Alignment.centerRight, padding: EdgeInsets.symmetric(vertical: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text("Forgot password ?", style: TextStyle(color: primary),), GestureDetector( onTap: (){ Navigator.pushNamedAndRemoveUntil(context, "/register", (Route<dynamic> route) => true); }, child: Text("Create new Account", style: TextStyle(color: primary),), ), ], ) ) ], ), ), ), ), ), ), ); } }
0
mirrored_repositories/flutter-auto-world/lib
mirrored_repositories/flutter-auto-world/lib/screens/home.dart
import 'package:auto_world/config/theme.dart'; import 'package:auto_world/screens/images.dart'; import 'package:auto_world/screens/profile/profile.dart'; import 'package:auto_world/screens/video/video.dart'; import 'package:circle_bottom_navigation/circle_bottom_navigation.dart'; import 'package:circle_bottom_navigation/widgets/tab_data.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class Home extends StatefulWidget{ @override State<StatefulWidget> createState() { // TODO: implement createState return HomeState(); } } class HomeState extends State<Home>{ int activeIndex = 0; PageController pageController; @override void initState() { // TODO: implement initState super.initState(); pageController = PageController(initialPage: activeIndex, keepPage: true); } @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Container( height: 35, child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Image.asset(logoUrl), ], ) ), actions: <Widget>[ Padding( padding: EdgeInsets.only(right: 15), child: InkResponse( onTap: (){}, child: Icon(Icons.notifications, color: primary,), ) ) ], ), body: Container( child: PageView( physics: NeverScrollableScrollPhysics(), controller: pageController, children: <Widget>[ Container( key: PageStorageKey("video"), child: Video(), ), Container( key: PageStorageKey("images"), child: ImagesPage(), ), // Center(child: Text("EVENT"),), Profile() ], ), ), bottomNavigationBar: CircleBottomNavigation( circleSize: 45, barHeight: 55, circleOutline: 0, initialSelection: activeIndex, barBackgroundColor: secondary, activeIconColor: secondary, textColor: primary, tabs: [ TabData(icon: Icons.video_library,title: "Videos",iconSize: 20), TabData(icon: Icons.image,title: "Images", iconSize: 20), // TabData(icon: Icons.event,title: "Events", iconSize: 20), TabData(icon: Icons.account_circle,title: "Profile", iconSize: 20), ], onTabChangedListener: (index) { setState(() => activeIndex = index); pageController.animateToPage(index, duration: Duration(milliseconds: 300), curve: Curves.easeIn); }, ) ); } }
0
mirrored_repositories/flutter-auto-world/lib/screens
mirrored_repositories/flutter-auto-world/lib/screens/video/comments.dart
import 'package:auto_world/config/theme.dart'; import 'package:auto_world/widgets/customButton.dart'; import 'package:auto_world/widgets/customCard.dart'; import 'package:auto_world/widgets/customDivider.dart'; import 'package:auto_world/widgets/customInputField.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class VideoComments extends StatelessWidget { AnimationController controller; VideoComments({@required this.controller}) : assert(controller != null); @override Widget build(BuildContext context) { // TODO: implement build return Container( height: double.infinity, width: double.infinity, color: secondary, child: Column( children: <Widget>[ Container( padding: EdgeInsets.symmetric(horizontal: 10), color: secondary, child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Expanded( child: Text( "Comments", style: TextStyle(color: primary, fontSize: 17), ), ), Material( color: Colors.transparent, child: InkResponse( onTap: () { FocusScope.of(context).unfocus(); controller.reverse(); }, child: Container( height: 30, width: 30, margin: EdgeInsets.symmetric(vertical: 10), child: Icon( Icons.close, color: primary, )), )) ], ), ), Container( margin: EdgeInsets.symmetric(horizontal: 10), child: CustomInputField( labelText: "Add Comment", textInputType: TextInputType.multiline, maxLines: 4, ), ), SizedBox(height: 5,), Container( alignment: Alignment.centerRight, margin: EdgeInsets.symmetric(horizontal: 10), child: Container( width: 70, child: SmallCustomButton( text: "Add", onTap: () { FocusScope.of(context).unfocus(); }, ), ), ), SizedBox(height: 5,), CustomDivider(), Expanded( child: GestureDetector( onTap: () { FocusScope.of(context).unfocus(); }, child: ListView( children: <Widget>[ CommentItem(), CommentItem(), CommentItem(), CommentItem(), CommentItem(), CommentItem(), CommentItem(), CommentItem(), CommentItem(), ], ), ), ), ], ), ); } } class CommentItem extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return CustomCard( child: Container( padding: EdgeInsets.symmetric(vertical: 10, horizontal: 5), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( padding: EdgeInsets.only(left: 5), child: CircleAvatar( child: FlutterLogo(), ), ), Expanded( child: Container( margin: EdgeInsets.only(left: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( child: Text( "Nikks 2 hour ago", style: TextStyle( color: primary, fontWeight: FontWeight.w600), ), ), SizedBox( height: 5, ), Container( child: Text( "Detaching from a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@ea16ddc. Reloaded 7 of 523 libraries in 653ms. Reloaded 7 of 523 libraries in 653ms. Reloaded 7 of 523 libraries in 653ms.", style: TextStyle(color: primary, fontSize: 13), ), ) ], ), )) ], ), ), ); } }
0
mirrored_repositories/flutter-auto-world/lib/screens
mirrored_repositories/flutter-auto-world/lib/screens/video/videoDetails.dart
import 'package:auto_world/config/theme.dart'; import 'package:auto_world/models/videoModel.dart'; import 'package:auto_world/screens/video/comments.dart'; import 'package:auto_world/screens/video/relatedVideos.dart'; import 'package:auto_world/widgets/customButton.dart'; import 'package:auto_world/widgets/customDivider.dart'; import 'package:auto_world/widgets/customInputField.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class VideoDetailsPage extends StatefulWidget { VideoModel videoModel; VideoDetailsPage({this.videoModel}); @override State<StatefulWidget> createState() { // TODO: implement createState return VideoDetailsPageState(); } } class VideoDetailsPageState extends State<VideoDetailsPage> { @override void initState() { // TODO: implement initState super.initState(); } @override void dispose() { // TODO: implement dispose super.dispose(); } @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( iconTheme: IconThemeData( color: primary, //change your color here ), ), body: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( child: Hero( tag: "${widget.videoModel.id}_Tag", child: Container( decoration: BoxDecoration( image: DecorationImage( image: NetworkImage(widget.videoModel.image), fit: BoxFit.cover)), height: MediaQuery.of(context).size.height / 4.5, width: double.infinity, ), ), ), Expanded( child: DetailsView( videoModel: widget.videoModel, ), ) ], ), ), ); } } class DetailsView extends StatefulWidget { VideoModel videoModel; DetailsView({this.videoModel}) : assert(videoModel != null); @override State<StatefulWidget> createState() { // TODO: implement createState return DetailsViewState(); } } class DetailsViewState extends State<DetailsView> with SingleTickerProviderStateMixin { Animation<Offset> offset; AnimationController controller; @override void initState() { // TODO: implement initState super.initState(); controller = AnimationController(vsync: this, duration: Duration(milliseconds: 300)); offset = Tween<Offset>(begin: Offset(0.0, 1.0), end: Offset.zero) .animate(controller); } @override Widget build(BuildContext context) { // TODO: implement build return Stack( children: <Widget>[ Container( child: Column( children: <Widget>[ Container( margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10), child: Column( children: <Widget>[ Row( children: <Widget>[ Expanded( child: Hero( tag: "hero_text_${widget.videoModel.id}", child: Material( color: Colors.transparent, child: Container( child: Text( widget.videoModel.name, style: TextStyle(color: primary, fontSize: 18), ), ), ), ), ), Container( child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ IconButton( onPressed: () {}, icon: Icon( Icons.thumb_up, color: primary, ), ), IconButton( onPressed: () {}, icon: Icon( Icons.thumb_down, color: primary, ), ), IconButton( onPressed: () {}, icon: Icon( Icons.redo, color: primary, ), ) ], ), ) ], ), Container( child: Text( "${widget.videoModel.name} ${widget.videoModel.name} ${widget.videoModel.name} ${widget.videoModel.name}", overflow: TextOverflow.ellipsis, style: TextStyle( color: primary.withOpacity(.7), fontSize: 14), maxLines: 3, ), ) ], ), ), CustomDivider(), Container( margin: EdgeInsets.symmetric(horizontal: 10, vertical: 5), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Expanded( child: Container( child: Row( children: <Widget>[ CircleAvatar( child: FlutterLogo(), ), SizedBox( width: 10, ), Text( "PowerDrift", style: TextStyle(color: primary), ) ], ), ), ), Container( width: 100, child: SmallCustomButton( text: "Follow", onTap: () {}, ), ) ], ), ), CustomDivider(), Container( margin: EdgeInsets.symmetric(horizontal: 10, vertical: 5), child: GestureDetector( onTap: () { controller.forward(); }, child: Material( color: Colors.transparent, child: Hero( tag: "hero_comment_id", child: Container( alignment: Alignment.bottomLeft, padding: EdgeInsets.symmetric(vertical: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( "COMMENTS ( 190 )", style: TextStyle(color: primary), ), InkResponse( onTap: () { controller.forward(); }, child: Padding( padding: EdgeInsets.only(right: 5), child: Icon( Icons.add, color: primary, size: 20, ), ), ) ], )), ), ), ), ), CustomDivider(), Expanded( child: RelatedVideos(), ) ], ), ), SlideTransition( position: offset, child: VideoComments( controller: controller, ), ) ], ); } }
0
mirrored_repositories/flutter-auto-world/lib/screens
mirrored_repositories/flutter-auto-world/lib/screens/video/video.dart
import 'package:auto_world/models/videoModel.dart'; import 'package:auto_world/screens/video/videoItem.dart'; import 'package:flutter/material.dart'; class Video extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return ListView.builder( itemBuilder: (context, index) { return VideoItem( videoModel: videos[index], isLastItem: index == (videos.length - 1), ); }, itemCount: videos.length, ); } }
0
mirrored_repositories/flutter-auto-world/lib/screens
mirrored_repositories/flutter-auto-world/lib/screens/video/videoItem.dart
import 'package:auto_world/config/theme.dart'; import 'package:auto_world/models/videoModel.dart'; import 'package:auto_world/screens/video/videoDetails.dart'; import 'package:auto_world/widgets/customCard.dart'; import 'package:flutter/material.dart'; class VideoItem extends StatelessWidget { VideoModel videoModel; bool isLastItem; bool isRelated = false; bool isClickable = true; VideoItem({ this.videoModel, this.isLastItem = false, this.isRelated = false, this.isClickable = true, }); @override Widget build(BuildContext context) { // TODO: implement build return Container( margin: isLastItem ? EdgeInsets.only(bottom: 30) : EdgeInsets.all(0), child: CustomCard( child: Material( color: Colors.transparent, child: InkWell( onTap: isClickable ? () { Navigator.push( context, MaterialPageRoute( builder: (_) => VideoDetailsPage( videoModel: videoModel, ), ), ); } : null, child: Column( children: <Widget>[ Hero( tag: "${videoModel.id}_Tag", child: Container( height: isRelated ? 100 : 170, width: double.infinity, child: Image.network( videoModel.image, fit: BoxFit.cover, ), ), ), Container( padding: EdgeInsets.symmetric(vertical: 15, horizontal: 10), child: Row( children: <Widget>[ Expanded( child: Hero( tag: "hero_text_${videoModel.id}", child: Material( color: Colors.transparent, child: Text( videoModel.name, maxLines: 2, overflow: TextOverflow.clip, style: TextStyle(color: primary, fontSize: 16), ), ), ), ), ], ), ) ], ), ), ), ), ); } }
0
mirrored_repositories/flutter-auto-world/lib/screens
mirrored_repositories/flutter-auto-world/lib/screens/video/relatedVideos.dart
import 'package:auto_world/config/theme.dart'; import 'package:auto_world/models/videoModel.dart'; import 'package:auto_world/screens/video/videoItem.dart'; import 'package:auto_world/widgets/customCard.dart'; import 'package:auto_world/widgets/customDivider.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class RelatedVideos extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Container( child: Stack( children: <Widget>[ Container( width: double.infinity, child: Container( height: double.infinity, child: ListView( children: <Widget>[ RelatedItems(videoModel: videos[1]), RelatedItems(videoModel: videos[2]), RelatedItems(videoModel: videos[0]), RelatedItems(videoModel: videos[1]), RelatedItems(videoModel: videos[2]), RelatedItems(videoModel: videos[0]), RelatedItems(videoModel: videos[1]), RelatedItems(videoModel: videos[2]), ], ), ), ), ], ), ); } } class RelatedItems extends StatelessWidget { VideoModel videoModel; RelatedItems({this.videoModel}); @override Widget build(BuildContext context) { // TODO: implement build return CustomCard( child: Container( height: 80, child: Row( children: <Widget>[ Container( width: MediaQuery.of(context).size.width / 4, child: Image.network( videoModel.image, fit: BoxFit.cover, matchTextDirection: true, ), color: Colors.white, height: double.infinity, ), Expanded( child: Container( margin: EdgeInsets.all(10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( child: Text( videoModel.name, overflow: TextOverflow.ellipsis, style: TextStyle(color: primary, fontSize: 16), maxLines: 1, ), ), SizedBox( height: 10, ), Container( child: Text( "${videoModel.name} ${videoModel.name} ${videoModel.name} ${videoModel.name}", overflow: TextOverflow.ellipsis, style: TextStyle( color: primary.withOpacity(.7), fontSize: 13), maxLines: 2, ), ) ], ), )) ], ), ), ); } }
0
mirrored_repositories/flutter-auto-world/lib/screens
mirrored_repositories/flutter-auto-world/lib/screens/profile/profile.dart
import 'package:auto_world/config/theme.dart'; import 'package:auto_world/screens/profile/editProfile.dart'; import 'package:auto_world/widgets/customDivider.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; class Profile extends StatefulWidget { @override State<StatefulWidget> createState() { // TODO: implement createState return ProfileState(); } } class ProfileState extends State<Profile> with SingleTickerProviderStateMixin { TabController _tabController; @override void initState() { // TODO: implement initState super.initState(); _tabController = TabController(length: 2, vsync: this, initialIndex: 1); } @override Widget build(BuildContext context) { return CustomScrollView( shrinkWrap: false, slivers: <Widget>[ SliverToBoxAdapter( child: ProfileTop(), ), SliverAppBar( pinned: true, title: TabBar( controller: _tabController, tabs: [ Tab( icon: Icon(Icons.video_library, color: primary,), ), Tab( icon: Icon(Icons.image, color: primary,), ), ], ), ), SliverGrid.count( crossAxisCount: 3, children: List.generate( 30, (index) => Card( child: Text("$index"), )), ) ], ); } } class ProfileTop extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Column( children: <Widget>[ Container( height: 120, width: 120, decoration: BoxDecoration( borderRadius: BorderRadius.circular(60), image: DecorationImage( fit: BoxFit.cover, image: NetworkImage( "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTo0T_MO3fGY501pC6gjpz6DFA9NzzltTxpClqpjqM1gCC-I12c&usqp=CAU")), boxShadow: [ BoxShadow( color: Color(0xff000000).withOpacity(.2), spreadRadius: 0, blurRadius: 10, ), ], ), ), SizedBox( height: 20, ), Container( child: Column( children: <Widget>[ Text( "Nikks Auto", style: TextStyle(color: primary, fontSize: 25), ), ], )), SizedBox( height: 20, ), Container( width: MediaQuery.of(context).size.width / 1.5, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ KeyValue(key: "Posts", value: "100"), KeyValue(key: "Followers", value: "10"), KeyValue(key: "Following", value: "11") ], ), ) ], ); } Widget KeyValue({String key, String value}) { return InkWell( onTap: () {}, child: Container( padding: EdgeInsets.all(5), child: Column( children: <Widget>[ Text( value, style: TextStyle( color: primary, fontSize: 18, fontWeight: FontWeight.w600), ), Text( key, style: TextStyle( color: primary, fontSize: 17, ), ) ], ), )); } } class CustomSliverPersistentHeader extends SliverPersistentHeaderDelegate { final Widget child; CustomSliverPersistentHeader({this.child}); @override Widget build( BuildContext context, double shrinkOffset, bool overlapsContent) { return this.child; } @override // TODO: implement maxExtent double get maxExtent => 200; @override // TODO: implement minExtent double get minExtent => 200; @override bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) { // TODO: implement shouldRebuild return true; } } /* * * return Container( child: SingleChildScrollView( child: Column( children: <Widget>[ Container( height: 120, width: 120, decoration: BoxDecoration( borderRadius: BorderRadius.circular(60), image: DecorationImage( fit: BoxFit.cover, image: NetworkImage("https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTo0T_MO3fGY501pC6gjpz6DFA9NzzltTxpClqpjqM1gCC-I12c&usqp=CAU") ), boxShadow: [ BoxShadow( color: Color(0xff000000).withOpacity(.2), spreadRadius: 0, blurRadius: 10, ), ], ), ), SizedBox(height: 20,), Container( child: Column( children: <Widget>[ Text("Nikks Auto", style: TextStyle(color: primary, fontSize: 25),), ], ) ), SizedBox(height: 20,), Container( width: MediaQuery.of(context).size.width/1.5, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ KeyValue(key: "Posts",value: "100"), KeyValue(key: "Followers", value: "10"), KeyValue(key: "Following", value: "11") ], ), ) ], ), ), ); } Widget KeyValue({String key, String value}){ return Column( children: <Widget>[ Text(value, style: TextStyle(color: primary, fontSize: 18, fontWeight: FontWeight.w600),), Text(key,style: TextStyle(color: primary, fontSize: 17,),) ], ); } * */
0
mirrored_repositories/flutter-auto-world/lib/screens
mirrored_repositories/flutter-auto-world/lib/screens/profile/editProfile.dart
import 'package:auto_world/widgets/customButton.dart'; import 'package:auto_world/widgets/customInputField.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class EditProfile extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar(), body: Container( padding: EdgeInsets.symmetric(horizontal: 10), child: SingleChildScrollView( child: Column( children: <Widget>[ Container( height: 120, width: 120, decoration: BoxDecoration( borderRadius: BorderRadius.circular(60), image: DecorationImage( fit: BoxFit.cover, image: NetworkImage( "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTo0T_MO3fGY501pC6gjpz6DFA9NzzltTxpClqpjqM1gCC-I12c&usqp=CAU")), boxShadow: [ BoxShadow( color: Color(0xff000000).withOpacity(.2), spreadRadius: 0, blurRadius: 10, ), ], ), ), SizedBox( height: 20, ), CustomInputField( labelText: "Name", ), SizedBox( height: 10, ), CustomInputField( labelText: "Username", ), SizedBox( height: 20, ), CustomButton( onTap: () {}, text: "Save", ) ], ), ), ), ); } }
0
mirrored_repositories/flutter-auto-world
mirrored_repositories/flutter-auto-world/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:auto_world/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/ECommerce-Products-Flutter
mirrored_repositories/ECommerce-Products-Flutter/lib/main.dart
import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:e_commers/presentation/routes/routes.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { SystemChrome.setSystemUIOverlayStyle( SystemUiOverlayStyle(statusBarColor: Colors.transparent, statusBarIconBrightness: Brightness.dark ) ); return MultiBlocProvider( providers: [ BlocProvider(create: (context) => AuthBloc()..add( CheckLoginEvent() )), BlocProvider(create: (context) => UserBloc()), BlocProvider(create: (context) => GeneralBloc()), BlocProvider(create: (context) => ProductBloc()), BlocProvider(create: (context) => CategoryBloc()), BlocProvider(create: (context) => CartBloc()), ], child: MaterialApp( debugShowCheckedModeBanner: false, title: 'E-Commers Products - Fraved', initialRoute: 'loadingPage', routes: routes, ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib
mirrored_repositories/ECommerce-Products-Flutter/lib/data/list_card.dart
import 'package:e_commers/domain/models/card/credit_card_frave.dart'; final List<CreditCardFrave> cards = [ CreditCardFrave( cardNumberHidden: '4242', cardNumber: '4242424242424242', brand: 'visa', cvv: '123', expiracyDate: '01/25', cardHolderName: 'Frave Developer' ), CreditCardFrave( cardNumberHidden: '5555', cardNumber: '5555555555554444', brand: 'mastercard', cvv: '213', expiracyDate: '01/25', cardHolderName: 'Frave Programmer' ), CreditCardFrave( cardNumberHidden: '3782', cardNumber: '378282246310005', brand: 'american express', cvv: '2134', expiracyDate: '01/25', cardHolderName: 'Franklin Perez' ), ];
0
mirrored_repositories/ECommerce-Products-Flutter/lib/data
mirrored_repositories/ECommerce-Products-Flutter/lib/data/local_storage/secure_storage.dart
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; class SecureStorageFrave { final secureStorage = FlutterSecureStorage(); Future<void> persistenToken( String token ) async { await secureStorage.write(key: 'token', value: token); } Future<String?> readToken() async { return await secureStorage.read(key: 'token'); } Future<void> deleteSecureStorage() async { await secureStorage.delete(key: 'token'); await secureStorage.deleteAll(); } } final secureStorage = SecureStorageFrave();
0
mirrored_repositories/ECommerce-Products-Flutter/lib/data
mirrored_repositories/ECommerce-Products-Flutter/lib/data/env/env.dart
class Environment { static const String baseUrl = 'http://192.168.0.104:7070/'; static const String urlApi = 'http://192.168.0.104:7070/api'; }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/routes/routes.dart
import 'package:e_commers/presentation/screen/login/loading_page.dart'; import 'package:e_commers/presentation/screen/login/login_page.dart'; import 'package:e_commers/presentation/screen/login/register_page.dart'; import 'package:e_commers/presentation/screen/start/start_home_page.dart'; import 'package:flutter/material.dart'; Map<String, Widget Function(BuildContext context)> routes = { 'loadingPage' : ( context ) => LoadingPage(), 'getStarted' : ( context ) => StartHomePage(), 'signInPage' : ( context ) => SignInPage(), 'signUpPage' : ( context ) => SignUpPage(), // 'homePage' : ( context ) => HomePage(), // 'cartPage' : ( context ) => CartPage(), // 'favoritePage' : ( context ) => FavoritePage(), // 'profilePage' : ( context ) => ProfilePage(), };
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/components/btn_frave.dart
part of 'widgets.dart'; class BtnFrave extends StatelessWidget { final String text; final double width; final double height; final double border; final Color colorText; final Color backgroundColor; final double fontSize; final VoidCallback? onPressed; final FontWeight fontWeight; final bool isTitle; const BtnFrave({ Key? key, required this.text, required this.width, this.onPressed, this.height = 50, this.border = 8.0, this.colorText = Colors.white, this.fontSize = 19, this.backgroundColor = ColorsFrave.primaryColorFrave, this.fontWeight = FontWeight.normal, this.isTitle = false }) : super(key: key); @override Widget build(BuildContext context) { return SizedBox( height: height, width: width, child: TextButton( style: TextButton.styleFrom( foregroundColor: Colors.white, backgroundColor: backgroundColor, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(border)) ), child: TextFrave( text: text, color: colorText, fontSize: fontSize, fontWeight: fontWeight, isTitle: isTitle, ), onPressed: onPressed, ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/components/circle_frave.dart
import 'package:flutter/material.dart'; class CircleFrave extends StatelessWidget { final double radius; final Color color; final Widget child; CircleFrave({ this.radius = 60.0, this.color = const Color(0xff006cf2), required this.child }); @override Widget build(BuildContext context){ return Container( height: radius, width: radius, decoration: BoxDecoration( color: color, shape: BoxShape.circle ), child: child ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/components/staggered_dual_view.dart
import 'package:flutter/material.dart'; class StaggeredDualView extends StatelessWidget { final IndexedWidgetBuilder itemBuilder; final int itemCount; final double spacing; final double aspectRatio; final double alturaElement; const StaggeredDualView({ Key? key, required this.itemBuilder, required this.itemCount, this.spacing = 0.0, this.aspectRatio = 0.5, this.alturaElement = 0.5 }) : super(key: key); @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, constraints){ final width = constraints.maxWidth; final itemHeight = (width * 0.3) / aspectRatio; final height = constraints.maxHeight + itemHeight; return OverflowBox( maxWidth: width, minWidth: width, maxHeight: height, minHeight: height, child: GridView.builder( padding: EdgeInsets.only( top: itemHeight / 2, bottom: itemHeight), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: aspectRatio, crossAxisSpacing: spacing, mainAxisSpacing: spacing ), itemCount: itemCount, itemBuilder: (context, index){ return Transform.translate( offset: Offset(0.0, index.isOdd ? itemHeight * alturaElement : 0.0), child: itemBuilder(context, index), ); } ), ); }); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/components/text_frave.dart
part of 'widgets.dart'; class TextFrave extends StatelessWidget { final String text; final double fontSize; final FontWeight fontWeight; final Color color; final int maxLines; final TextOverflow overflow; final TextAlign textAlign; final double? letterSpacing; final bool isTitle; const TextFrave({ Key? key, required this.text, this.fontSize = 18, this.fontWeight = FontWeight.normal, this.color = Colors.black, this.maxLines = 1, this.overflow = TextOverflow.visible, this.textAlign = TextAlign.left, this.letterSpacing, this.isTitle = false, }) : super(key: key); @override Widget build(BuildContext context) { return Text( text, style: GoogleFonts.getFont( isTitle ? 'Poppins' : 'Roboto', fontSize: fontSize, fontWeight: fontWeight, color: color, letterSpacing: letterSpacing), maxLines: maxLines, overflow: overflow, textAlign: textAlign, ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/components/shimmer_frave.dart
import 'package:flutter/material.dart'; import 'package:shimmer/shimmer.dart'; class ShimmerFrave extends StatelessWidget{ const ShimmerFrave({Key? key}): super(key: key); @override Widget build(BuildContext context){ return Shimmer.fromColors( baseColor: Colors.white, highlightColor: const Color(0xFFF7F7F7), child: Container( height: 50, width: MediaQuery.of(context).size.width, decoration: BoxDecoration( color: Colors.grey[200] ), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/components/widgets.dart
import 'package:e_commers/data/env/env.dart'; import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/screen/home/home_page.dart'; import 'package:e_commers/presentation/screen/profile/profile_page.dart'; import 'package:e_commers/presentation/screen/favorite/favorite_page.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:google_fonts/google_fonts.dart'; part 'bottom_nav.dart'; part 'text_frave.dart'; part 'btn_frave.dart'; part 'text_field_frave.dart';
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/components/text_field_frave.dart
part of 'widgets.dart'; class TextFormFrave extends StatelessWidget { final TextEditingController controller; final String? hintText; final bool isPassword; final TextInputType keyboardType; final FormFieldValidator<String>? validator; final Widget prefixIcon; const TextFormFrave({ Key? key, required this.controller, required this.prefixIcon, this.hintText, this.isPassword = false, this.keyboardType = TextInputType.text, this.validator, }) : super(key: key); @override Widget build(BuildContext context) { return TextFormField( controller: controller, style: GoogleFonts.getFont('Roboto', fontSize: 17), cursorColor: ColorsFrave.secundaryColorFrave, obscureText: isPassword, keyboardType: keyboardType, decoration: InputDecoration( contentPadding: EdgeInsets.symmetric(horizontal: 15, vertical: 15.0), filled: true, fillColor: Color(0xfff5f5f5), border: OutlineInputBorder(borderRadius: BorderRadius.circular(8.0), borderSide: BorderSide(color: Color(0xffF5F5F5))), enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(8.0), borderSide: BorderSide(color: Color(0xffF5F5F5))), hintText: hintText, prefixIcon: prefixIcon ), validator: validator, ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/components/bottom_nav.dart
part of 'widgets.dart'; class BottomNavigationFrave extends StatelessWidget{ final int index; BottomNavigationFrave({ required this.index }); @override Widget build(BuildContext context) { return BlocBuilder<GeneralBloc, GeneralState>( buildWhen: (previous, current) => previous != current, builder: (context, state) => AnimatedOpacity( duration: Duration(milliseconds: 250), opacity: ( state.showMenuHome ) ? 1 : 0, child: Container( height: 60, width: 320, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(15.0), boxShadow: [ BoxShadow(color: Colors.black38, blurRadius: 10, spreadRadius: -5) ] ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ _ItemButtom( i: 1, index: index, iconString: 'assets/svg/home.svg', onPressed: () => Navigator.pushAndRemoveUntil(context, routeSlide(page: HomePage()), (_) => false), ), _ItemButtom( i: 2, index: index, iconString: 'assets/svg/favorite.svg', onPressed: () => Navigator.pushAndRemoveUntil(context, routeSlide(page: FavoritePage()), (_) => false), ), CenterIcon( index: 3, iconString: 'assets/svg/bolso.svg', // onPressed: () => Navigator.pushAndRemoveUntil(context, routeSlide(page: CartPage()), (_) => false), onPressed: () { }, ), _ItemButtom( i: 4, index: index, iconString: 'assets/svg/search.svg', onPressed: () {}, ), _ItemProfile() ], ), ), ), ); } } class _ItemProfile extends StatelessWidget { @override Widget build(BuildContext context) { return GestureDetector( onTap: () => Navigator.pushAndRemoveUntil(context, routeSlide(page: ProfilePage()), (_) => false), child: BlocBuilder<UserBloc, UserState>( builder: (_, state) => state.user != null ? state.user?.image != '' ? CircleAvatar( radius: 18, backgroundImage: NetworkImage(Environment.baseUrl+ state.user!.image ) ) : CircleAvatar( radius: 18, backgroundColor: ColorsFrave.primaryColorFrave, child: TextFrave( text: state.user!.users.substring(0,1).toUpperCase(), color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20, ), ) : const CircleAvatar( radius: 18, backgroundColor: ColorsFrave.primaryColorFrave, child: CircularProgressIndicator(strokeWidth: 2) ) ), ); } } class CenterIcon extends StatelessWidget { final int index; final String iconString; final Function() onPressed; const CenterIcon({ Key? key, required this.index, required this.iconString, required this.onPressed }) : super(key: key); @override Widget build(BuildContext context) { return GestureDetector( onTap: onPressed, child: CircleAvatar( backgroundColor: ColorsFrave.primaryColorFrave, radius: 26, child: SvgPicture.asset( iconString , height: 26), ), ); } } class _ItemButtom extends StatelessWidget { final int i; final int index; final String iconString; final Function() onPressed; const _ItemButtom({ Key? key, required this.i, required this.index, required this.onPressed, required this.iconString }) : super(key: key); @override Widget build(BuildContext context) { return GestureDetector( onTap: onPressed, child: Container( child: SvgPicture.asset( iconString, height: 25, ) ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/themes/colors_frave.dart
import 'package:flutter/material.dart' show Color; class ColorsFrave { static const Color primaryColorFrave = Color(0xFF0657C8); static const Color secundaryColorFrave = Color(0xff002C8B); static const Color backgroundColorFrave = Color(0xff21242C); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/cart/payment_card_page.dart
import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/domain/models/card/credit_card_frave.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; import 'package:e_commers/data/list_card.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; class PaymentCardPage extends StatelessWidget { const PaymentCardPage({Key? key}):super(key: key); @override Widget build(BuildContext context){ final cartBloc = BlocProvider.of<CartBloc>(context); return Scaffold( backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.white, title: const TextFrave(text: 'Payment', color: Colors.black, fontSize: 21, fontWeight: FontWeight.bold), elevation: 0, centerTitle: true, leading: IconButton( splashRadius: 20, icon: const Icon(Icons.arrow_back_ios_rounded, color: Colors.black), onPressed: () => Navigator.pop(context), ), actions: [ TextButton( onPressed: (){}, child: TextFrave(text: 'Add Card', color: ColorsFrave.primaryColorFrave, fontSize: 17), ) ], ), body: ListView.builder( padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0), itemCount: cards.length, itemBuilder: (_, i) { final CreditCardFrave card = cards[i]; return BlocBuilder<CartBloc, CartState>( builder: (context, state) => GestureDetector( onTap: () => cartBloc.add( OnSelectCardEvent(card) ), child: Container( margin: EdgeInsets.only(bottom: 20.0), padding: EdgeInsets.all(10.0), height: 80, decoration: BoxDecoration( borderRadius: BorderRadius.circular(15.0), border: Border.all( color: state.creditCardFrave == null ? Colors.black : state.creditCardFrave!.cvv == card.cvv ? Colors.blue : Colors.black ) ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( height: 80, width: 80, child: SvgPicture.asset('Assets/${card.brand}.svg') ), Container( child: TextFrave(text: '**** **** **** ${card.cardNumberHidden}') ), Container( child: state.creditCardFrave == null ? Icon(Icons.radio_button_off_rounded, size: 31) : state.creditCardFrave!.cvv == card.cvv ? Icon(Icons.radio_button_checked_rounded, size: 31, color: Colors.blue,) : Icon(Icons.radio_button_off_rounded, size: 31) ) ], ), ), ), ); } , ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/login/register_page.dart
import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/helpers/validation_form.dart'; import 'package:e_commers/presentation/screen/login/login_page.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:form_field_validator/form_field_validator.dart'; class SignUpPage extends StatefulWidget { @override State<SignUpPage> createState() => _SignUpPageState(); } class _SignUpPageState extends State<SignUpPage> { late final TextEditingController userController; late final TextEditingController emailController; late final TextEditingController passowrdController; late final TextEditingController passController; final _formKey = GlobalKey<FormState>(); @override void initState() { userController = TextEditingController(); emailController = TextEditingController(); passowrdController = TextEditingController(); passController = TextEditingController(); super.initState(); } @override void dispose() { clear(); userController.dispose(); emailController.dispose(); passowrdController.dispose(); passController.dispose(); super.dispose(); } void clear(){ userController.clear(); emailController.clear(); passowrdController.clear(); passController.clear(); } @override Widget build(BuildContext context) { final userBloc = BlocProvider.of<UserBloc>(context); final size = MediaQuery.of(context).size; return BlocListener<UserBloc, UserState>( listener: (context, state) { if( state is LoadingUserState ){ modalLoading(context, 'Validating...'); } if( state is SuccessUserState ){ Navigator.of(context).pop(); modalSuccess(context,'USER CREATED', onPressed: (){ clear(); Navigator.pushReplacement(context, routeSlide(page: SignInPage())); }); } if( state is FailureUserState ){ Navigator.of(context).pop(); errorMessageSnack(context, state.error); } }, child: Scaffold( backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.white, elevation: 0, leading: IconButton( splashRadius: 20, icon: const Icon(Icons.close_rounded, color: Colors.black,), onPressed: () => Navigator.pop(context), ), actions: [ TextButton( child: const TextFrave( text: 'Log In', fontSize: 17, color: ColorsFrave.primaryColorFrave, fontWeight: FontWeight.w500, ), onPressed: () => Navigator.of(context).pushReplacementNamed('signInPage'), ), const SizedBox(width: 5) ], ), body: Form( key: _formKey, child: ListView( padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0), keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, physics: const BouncingScrollPhysics(), children: [ const TextFrave( text: 'Welcome to Fraved Shop', fontSize: 24, fontWeight: FontWeight.bold, isTitle: true, ), const SizedBox(height: 5.0), TextFrave( text: 'Create Account', fontSize: 17, color: Colors.blue.shade600, ), const SizedBox(height: 20.0), TextFormFrave( hintText: 'Username', prefixIcon: const Icon(Icons.person), controller: userController, validator: RequiredValidator(errorText: 'Username is required'), ), const SizedBox(height: 15.0), TextFormFrave( hintText: 'Email Address', keyboardType: TextInputType.emailAddress, prefixIcon: const Icon(Icons.email_outlined), controller: emailController, validator: validatedEmail ), const SizedBox(height: 15.0), TextFormFrave( hintText: 'Password', prefixIcon: const Icon(Icons.vpn_key_rounded), isPassword: true, controller: passowrdController, validator: passwordValidator, ), const SizedBox(height: 15.0), TextFormFrave( hintText: 'Repeat Password', controller: passController, prefixIcon: const Icon(Icons.vpn_key_rounded), isPassword: true, validator: (val) => MatchValidator(errorText: 'Password do not macth ').validateMatch(val!, passowrdController.text) ), const SizedBox(height: 25.0), Row( children: const [ Icon(Icons.check_circle_rounded, color: Color(0xff0C6CF2)), TextFrave(text: ' I Agree to Frave Shop ', fontSize: 15,), TextFrave(text: ' Terms of Use', fontSize: 15, fontWeight: FontWeight.bold, color: Color(0xff0C6CF2)), ], ), ], ), ), bottomNavigationBar: SafeArea( child: Padding( padding: const EdgeInsets.all(8.0), child: BtnFrave( text: 'Sign up', width: size.width, fontSize: 18, isTitle: true, fontWeight: FontWeight.w600, border: 60, onPressed: (){ if( _formKey.currentState!.validate() ){ userBloc.add( OnAddNewUser( userController.text.trim(), emailController.text.trim(), passowrdController.text.trim() )); } }, ), ), ), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/login/loading_page.dart
import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/screen/home/home_page.dart'; import 'package:e_commers/presentation/screen/start/start_home_page.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class LoadingPage extends StatefulWidget { @override State<LoadingPage> createState() => _LoadingPageState(); } class _LoadingPageState extends State<LoadingPage> with TickerProviderStateMixin { late AnimationController _animationController; late Animation<double> _animation; @override void initState() { super.initState(); _animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 500)); _animation = Tween<double>(begin: 1.0, end: 0.8).animate(_animationController); _animation.addStatusListener( _animationListener ); _animationController.forward(); } _animationListener(AnimationStatus status){ if( status == AnimationStatus.completed ){ _animationController.reverse(); }else if( status == AnimationStatus.dismissed ) { _animationController.forward(); } } @override void dispose() { _animationController.dispose(); _animation.removeStatusListener( _animationListener); super.dispose(); } @override Widget build(BuildContext context){ final userBloc = BlocProvider.of<UserBloc>(context); return BlocListener<AuthBloc, AuthState>( listener: (context, state) { if( state is LogOutState ){ Navigator.of(context).pushAndRemoveUntil(routeFade(page: StartHomePage()), (_) => false); } else if ( state is SuccessAuthState){ userBloc.add( OnGetUserEvent() ); Navigator.of(context).pushAndRemoveUntil(routeSlide(page: HomePage()), (_) => false); } }, child: Scaffold( backgroundColor: Color(0xff1E4DD8), body: Center( child: SizedBox( height: 212, width: 181, child: Column( children: [ AnimatedBuilder( animation: _animationController, builder: (_, child) => Transform.scale( scale: _animation.value, child: Image.asset('assets/fraved_logo.png'), ), ), const SizedBox(height: 10.0), const TextFrave(text: 'Verifying your device...', color: Colors.white60 ) ], ), ) ), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/login/login_page.dart
import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/helpers/validation_form.dart'; import 'package:e_commers/presentation/screen/home/home_page.dart'; import 'package:e_commers/presentation/screen/login/loading_page.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class SignInPage extends StatefulWidget { @override _SignInPageState createState() => _SignInPageState(); } class _SignInPageState extends State<SignInPage> { late final TextEditingController _emailController; late final TextEditingController _passowrdController; final _keyForm = GlobalKey<FormState>(); bool isChangeSuffixIcon = true; @override void initState() { _emailController = TextEditingController(); _passowrdController = TextEditingController(); super.initState(); } @override void dispose() { _emailController.clear(); _emailController.dispose(); _passowrdController.clear(); _passowrdController.dispose(); super.dispose(); } @override Widget build(BuildContext context){ final size = MediaQuery.of(context).size; final userBloc = BlocProvider.of<UserBloc>(context); final authBloc = BlocProvider.of<AuthBloc>(context); return BlocListener<AuthBloc, AuthState>( listener: (context, state) { if( state is LoadingAuthState ){ modalLoading(context, 'Checking...'); }else if( state is FailureAuthState ){ Navigator.pop(context); errorMessageSnack(context, state.error); }else if( state is SuccessAuthState ){ Navigator.pop(context); userBloc.add(OnGetUserEvent()); Navigator.pushAndRemoveUntil(context, routeSlide(page: HomePage()), (_) => false); } }, child: Scaffold( backgroundColor: Colors.white, appBar: AppBar( leading: IconButton( splashRadius: 20, icon: const Icon(Icons.close_rounded, size: 25, color: Colors.black), onPressed: () => Navigator.pop(context), ), actions: [ TextButton( child: TextFrave( text: 'Register', fontSize: 18, color: ColorsFrave.primaryColorFrave, ), onPressed: () => Navigator.of(context).pushReplacementNamed('signUpPage'), ) ], elevation: 0, backgroundColor: Colors.white, ), body: SafeArea( child: Form( key: _keyForm, child: ListView( padding: const EdgeInsets.symmetric(horizontal: 10.0), physics: const BouncingScrollPhysics(), children: [ const SizedBox(height: 20), const TextFrave(text: 'Welcome Back!', fontSize: 34, fontWeight: FontWeight.bold, color: Color(0xff0C6CF2)), const SizedBox(height: 5), const TextFrave(text: 'Sign In to your account', fontSize: 18), const SizedBox(height: 35), TextFormFrave( controller: _emailController, keyboardType: TextInputType.emailAddress, validator: validatedEmail, hintText: 'Enter your Email ID', prefixIcon: const Icon(Icons.alternate_email_rounded), ), const SizedBox(height: 20), TextFormFrave( controller: _passowrdController, isPassword: isChangeSuffixIcon, hintText: 'Enter your password', prefixIcon: const Icon(Icons.password_rounded), validator: passwordValidator, ), const SizedBox(height: 40), BtnFrave( text: 'Continue', width: size.width, fontSize: 18, isTitle: true, fontWeight: FontWeight.w600, onPressed: (){ if( _keyForm.currentState!.validate() ){ authBloc.add(LoginEvent(_emailController.text.trim(), _passowrdController.text.trim())); } }, ), const SizedBox(height: 10), Align( alignment: Alignment.center, child: TextButton( child: TextFrave( text: 'Forgot password?', color: Colors.black, fontSize: 17, isTitle: true, fontWeight: FontWeight.w500, ), onPressed: () => Navigator.push(context, routeSlide(page: LoadingPage())) ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile/information_page.dart
import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/presentation/components/shimmer_frave.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class InformationPage extends StatefulWidget{ @override _InformationPageState createState() => _InformationPageState(); } class _InformationPageState extends State<InformationPage> { late TextEditingController _firstnameController; late TextEditingController _lastnameController; late TextEditingController _phoneController; late TextEditingController _addressController; late TextEditingController _referenceController; final _keyForm = GlobalKey<FormState>(); @override void initState() { initData(); super.initState(); } @override void dispose() { _firstnameController.dispose(); _lastnameController.dispose(); _phoneController.dispose(); _addressController.dispose(); _referenceController.dispose(); super.dispose(); } void initData(){ final userBloc = BlocProvider.of<UserBloc>(context).state.user!; _firstnameController = TextEditingController(text: userBloc.firstName); _lastnameController = TextEditingController(text: userBloc.lastName); _phoneController = TextEditingController(text: userBloc.phone); _addressController = TextEditingController(text: userBloc.address); _referenceController = TextEditingController(text: userBloc.reference); } @override Widget build(BuildContext context){ final userBloc = BlocProvider.of<UserBloc>(context); return BlocListener<UserBloc, UserState>( listener: (context, state) { if( state is LoadingUserState ) { modalLoading(context, 'Checking...'); }else if( state is FailureUserState ) { Navigator.pop(context); errorMessageSnack(context, state.error); } else if( state is SetUserState ){ Navigator.pop(context); } }, child: Scaffold( backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.white, elevation: 0, title: const TextFrave(text: 'My Profile', color: Colors.black, fontWeight: FontWeight.w500), centerTitle: true, leading: IconButton( splashRadius: 20, icon: const Icon(Icons.arrow_back_ios_rounded, color: Colors.black,), onPressed: () => Navigator.of(context).pop(), ), actions: [ TextButton( onPressed: (){ userBloc.add(OnUpdateInformationUserEvent( _firstnameController.text.trim(), _lastnameController.text.trim(), _phoneController.text.trim(), _addressController.text.trim(), _referenceController.text.trim() )); }, child: const TextFrave(text: 'Save', color: ColorsFrave.primaryColorFrave, fontSize: 18,) ) ], ), body: Form( key: _keyForm, child: ListView( physics: BouncingScrollPhysics(), keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0), children: [ const TextFrave(text: 'Account data', fontSize: 18), const SizedBox(height: 10.0), BlocBuilder<UserBloc, UserState>( buildWhen: (previous, current) => previous != current, builder: (context, state) => state.user != null ? Container( padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10), height: 80, width: MediaQuery.of(context).size.width, decoration: BoxDecoration( color: Color(0xff4C98EE).withOpacity(.1), borderRadius: BorderRadius.circular(10.0) ), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const TextFrave(text: 'User', fontSize: 18, fontWeight: FontWeight.w500), TextFrave(text: state.user!.users, fontSize: 18), ], ), SizedBox(height: 15.0), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const TextFrave(text: 'Email', fontSize: 18, fontWeight: FontWeight.w500), TextFrave(text: state.user!.email, fontSize: 18), ], ), ], ), ) : const ShimmerFrave() ), const SizedBox(height: 30.0), const TextFrave(text: 'Personal Information', fontSize: 18), const SizedBox(height: 10.0), TextFormFrave( controller: _firstnameController, hintText: 'Enter your First Name', prefixIcon: const Icon(Icons.person_outline_rounded), ), const SizedBox(height: 20.0), TextFormFrave( controller: _lastnameController, hintText: 'Enter Last Name', prefixIcon: const Icon(Icons.person_outline_rounded), ), const SizedBox(height: 20.0), TextFormFrave( controller: _phoneController, hintText: 'Enter your Phone Number', prefixIcon: const Icon(Icons.phone_android_rounded), keyboardType: TextInputType.phone, ), const SizedBox(height: 20.0), TextFormFrave( controller: _addressController, hintText: 'Street Address', prefixIcon: const Icon(Icons.home_outlined), keyboardType: TextInputType.streetAddress, ), const SizedBox(height: 20.0), TextFormFrave( controller: _referenceController, hintText: 'Reference', prefixIcon: const Icon(Icons.home_outlined), keyboardType: TextInputType.streetAddress, ), ], ), ), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile/profile_page.dart
// import 'dart:io'; import 'package:e_commers/data/env/env.dart'; import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/presentation/components/shimmer_frave.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/screen/profile/add_product/add_product_page.dart'; import 'package:e_commers/presentation/screen/profile/card/credit_card_page.dart'; import 'package:e_commers/presentation/screen/profile/information_page.dart'; import 'package:e_commers/presentation/screen/profile/shopping/shopping_page.dart'; import 'package:e_commers/presentation/screen/profile/widgets/card_item_profile.dart'; import 'package:e_commers/presentation/screen/profile/widgets/divider_line.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; import 'package:animate_do/animate_do.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:image_picker/image_picker.dart'; import 'package:permission_handler/permission_handler.dart'; class ProfilePage extends StatelessWidget { @override Widget build(BuildContext context){ final size = MediaQuery.of(context).size; return BlocListener<UserBloc, UserState>( listener: (context, state) { if( state is LoadingUserState ){ modalLoading(context, 'Loading...'); }else if( state is FailureUserState ){ Navigator.pop(context); errorMessageSnack(context, state.error); }else if( state is SetUserState ){ Navigator.pop(context); } }, child: Scaffold( backgroundColor: Color(0xffF5F5F5), body: Stack( children: [ ListProfile(), Positioned( bottom: 20, child: Container( width: size.width, child: Align( child: BottomNavigationFrave(index: 5) ) ), ), ], ), ), ); } } class ListProfile extends StatefulWidget { @override _ListProfileState createState() => _ListProfileState(); } class _ListProfileState extends State<ListProfile> { late ScrollController _scrollController; double scrollPrevious = 0; @override void initState() { _scrollController = ScrollController(); _scrollController.addListener(addListenerScroll); super.initState(); } void addListenerScroll(){ if( _scrollController.offset > scrollPrevious ){ BlocProvider.of<GeneralBloc>(context).add( OnShowOrHideMenuEvent(showMenu: false)); }else{ BlocProvider.of<GeneralBloc>(context).add( OnShowOrHideMenuEvent(showMenu: true)); } scrollPrevious = _scrollController.offset; } @override void dispose() { _scrollController.removeListener(addListenerScroll); _scrollController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return ListView( controller: _scrollController, padding: EdgeInsets.only(top: 35.0, bottom: 20.0), children: [ BlocBuilder<UserBloc, UserState>( buildWhen: (previous, current) => previous != current, builder: (context, state) => state.user != null ? Row( children: [ Padding( padding: EdgeInsets.only(left: 15.0), child: state.user != null && state.user?.image == '' ? GestureDetector( onTap: () => modalSelectPicture( context: context, onPressedImage: () async { Navigator.pop(context); AccessPermission().permissionAccessGalleryOrCameraForProfile( await Permission.storage.request(), context, ImageSource.gallery ); }, onPressedPhoto: () async { Navigator.pop(context); AccessPermission().permissionAccessGalleryOrCameraForProfile( await Permission.camera.request(), context, ImageSource.camera ); }, ), child: CircleAvatar( radius: 40, backgroundColor: ColorsFrave.primaryColorFrave, child: TextFrave(text: state.user!.users.substring(0,2).toUpperCase(), fontSize: 40, color: Colors.white, fontWeight: FontWeight.bold), ) ) : GestureDetector( onTap: () => modalSelectPicture( context: context, onPressedImage: () async { Navigator.pop(context); AccessPermission().permissionAccessGalleryOrCameraForProfile( await Permission.storage.request(), context, ImageSource.gallery ); }, onPressedPhoto: () async { Navigator.pop(context); AccessPermission().permissionAccessGalleryOrCameraForProfile( await Permission.camera.request(), context, ImageSource.camera ); }, ), child: Container( height: 90, width: 90, decoration: BoxDecoration( shape: BoxShape.circle, image: DecorationImage( fit: BoxFit.cover, image: NetworkImage(Environment.baseUrl + state.user!.image ) ) ), ), ) ), const SizedBox(width: 15.0), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BounceInRight( child: Align( alignment: Alignment.center, child: TextFrave(text: state.user!.users , fontSize: 21, fontWeight: FontWeight.w500 ) ), ), FadeInRight( child: Align( alignment: Alignment.center, child: TextFrave(text: state.user!.email, fontSize: 18, color: Colors.grey) ), ), ], ), ], ) : const ShimmerFrave() ), const SizedBox(height: 25.0), Container( height: 182, width: size.width, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(30.0) ), child: Column( children: [ CardItemProfile( text: 'Personal Information', borderRadius: BorderRadius.circular(50.0), icon: Icons.person_outline_rounded, backgroundColor: Color(0xff7882ff), onPressed: () => Navigator.push(context, routeSlide(page: InformationPage())), ), DividerLine(size: size), CardItemProfile( text: 'Credit Card', borderRadius: BorderRadius.circular(50.0), icon: Icons.credit_card_rounded, backgroundColor: Color(0xffFFCD3A), onPressed: () => Navigator.push(context, routeSlide(page: CreditCardPage())), ), DividerLine(size: size), CardItemProfile( text: 'Add Product', borderRadius: BorderRadius.only(bottomLeft: Radius.circular(30), bottomRight: Radius.circular(30.0)), icon: Icons.add, backgroundColor: Color(0xff02406F), onPressed: () => Navigator.push(context, routeSlide(page: AddProductPage())), ), ], ), ), const SizedBox(height: 15.0), Padding( padding: const EdgeInsets.only(left: 25.0), child: const TextFrave(text: 'General', fontSize: 17, color: Colors.grey,), ), const SizedBox(height: 10.0), Container( height: 243, width: size.width, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(30.0) ), child: Column( children: [ CardItemProfile( text: 'Settings', borderRadius: BorderRadius.only(topLeft: Radius.circular(30), topRight: Radius.circular(30.0)), backgroundColor: Color(0xff2EAA9B), icon: Icons.settings_applications, onPressed: (){}, ), DividerLine(size: size), CardItemProfile( text: 'Notifications', borderRadius: BorderRadius.zero, backgroundColor: Color(0xffE87092), icon: Icons.notifications_none_rounded, onPressed: () {}, ), DividerLine(size: size), CardItemProfile( text: 'Favorites', backgroundColor: Color(0xfff28072), icon: Icons.favorite_border_rounded, borderRadius: BorderRadius.zero, onPressed: (){}, ), DividerLine(size: size), CardItemProfile( text: 'My Shopping', backgroundColor: Color(0xff0716A5), icon: Icons.shopping_bag_outlined, borderRadius: BorderRadius.only(bottomLeft: Radius.circular(30), bottomRight: Radius.circular(30.0)), onPressed: () => Navigator.push(context, routeSlide(page: ShoppingPage())), ), ], ), ), const SizedBox(height: 15.0), Padding( padding: EdgeInsets.only(left: 25.0), child: const TextFrave(text: 'Personal', fontSize: 17, color: Colors.grey,), ), const SizedBox(height: 10.0), Container( height: 243, width: size.width, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(30.0) ), child: Column( children: [ CardItemProfile( text: 'Privacy & Policy', borderRadius: BorderRadius.only(topLeft: Radius.circular(30), topRight: Radius.circular(30.0)), backgroundColor: Color(0xff6dbd63), icon: Icons.policy_rounded, onPressed: (){}, ), DividerLine(size: size), CardItemProfile( text: 'Security', borderRadius: BorderRadius.zero, backgroundColor: Color(0xff1F252C), icon: Icons.lock_outline_rounded, onPressed: (){}, ), DividerLine(size: size), CardItemProfile( text: 'Term & Conditions', borderRadius: BorderRadius.zero, backgroundColor: Color(0xff458bff), icon: Icons.description_outlined, onPressed: (){}, ), DividerLine(size: size), CardItemProfile( text: 'Help', backgroundColor: Color(0xff4772e6), icon: Icons.help_outline, borderRadius: BorderRadius.only(bottomLeft: Radius.circular(30), bottomRight: Radius.circular(30.0)), onPressed: (){}, ), ], ), ), SizedBox(height: 25.0), CardItemProfile( text: 'Sign Out', borderRadius: BorderRadius.circular(50.0), icon: Icons.power_settings_new_sharp, backgroundColor: Colors.red, onPressed: () {}, ), ], ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile/widgets/card_item_profile.dart
import 'package:e_commers/presentation/components/widgets.dart'; import 'package:flutter/material.dart'; class CardItemProfile extends StatelessWidget { final String text; final VoidCallback onPressed; final BorderRadius borderRadius; final Color backgroundColor; final IconData icon; CardItemProfile({ required this.text, required this.onPressed, required this.borderRadius, required this.backgroundColor, required this.icon }); @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return Container( height: 60, width: size.width, decoration: BoxDecoration( color: Colors.white, borderRadius: borderRadius ), child: Card( shape: RoundedRectangleBorder(borderRadius: borderRadius), elevation: 0.0, margin: EdgeInsets.all(0.0), child: InkWell( borderRadius: borderRadius, onTap: onPressed, child: Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.only(left: 25.0), child: Row( children: [ Container( height: 35, width: 35, decoration: BoxDecoration( color: backgroundColor, borderRadius: BorderRadius.circular(12.0) ), child: Icon(icon, color: Colors.white,), ), SizedBox(width: 10.0), TextFrave(text: text, fontSize: 18,), ], ), ) ), ), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile/widgets/divider_line.dart
import 'package:flutter/material.dart'; class DividerLine extends StatelessWidget { final Size size; DividerLine({ Key? key, required this.size }); @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.only(left: 65.0, right: 25.0), child: Container( height: 1, width: size.width, color: Colors.grey[300], ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile/shopping/order_details_page.dart
import 'package:e_commers/data/env/env.dart'; import 'package:e_commers/domain/models/response/response_order_details.dart'; import 'package:e_commers/domain/services/services.dart'; import 'package:e_commers/presentation/components/shimmer_frave.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:flutter/material.dart'; class OrderDetailsPage extends StatelessWidget { final String uidOrder; const OrderDetailsPage({Key? key, required this.uidOrder}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: FutureBuilder<List<OrderDetail>>( future: productServices.getOrderDetails(uidOrder), builder: (context, snapshot) => !snapshot.hasData ? const ShimmerFrave() : _ListOrderDetails(orderDetails: snapshot.data!) ), ), ); } } class _ListOrderDetails extends StatelessWidget { final List<OrderDetail> orderDetails; const _ListOrderDetails({ Key? key, required this.orderDetails }) : super(key: key); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( margin: const EdgeInsets.only(left: 5.0, top: 5.0, ), child: IconButton( splashRadius: 20, onPressed: () => Navigator.pop(context), icon: Icon(Icons.arrow_back_ios_new_rounded) ) ), Expanded( child: ListView.builder( padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0), itemCount: orderDetails.length, itemBuilder: (context, i) => Padding( padding: const EdgeInsets.only(bottom: 20.0), child: Container( padding: const EdgeInsets.all(10.0), height: 150, width: MediaQuery.of(context).size.width, decoration: BoxDecoration( color: Colors.grey[200], borderRadius: BorderRadius.circular(12.0) ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Flexible( child: TextFrave(text: orderDetails[i].nameProduct.toUpperCase(), fontSize: 19, overflow: TextOverflow.ellipsis, fontWeight: FontWeight.w500 ) ), const SizedBox(height: 15.0), Row( children: [ SizedBox( height: 90, width: 90, child: Image.network(Environment.baseUrl + orderDetails[i].picture ) ), const SizedBox(width: 10.0), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TextFrave(text: 'Price: \$ ${orderDetails[i].price}', fontSize: 20, ), const SizedBox(height: 5.0), TextFrave(text: 'Quantity: ${orderDetails[i].quantity}', fontSize: 20), ], ) ], ), ], ), ), ), ), ), ], ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile/shopping/shopping_page.dart
import 'package:e_commers/domain/models/response/response_order_buy.dart'; import 'package:e_commers/domain/services/services.dart'; import 'package:e_commers/presentation/components/shimmer_frave.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/screen/profile/shopping/order_details_page.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; import 'package:timeago/timeago.dart' as timeago; class ShoppingPage extends StatelessWidget{ @override Widget build(BuildContext context){ return Scaffold( backgroundColor: Color(0xfff5f5f5), appBar: AppBar( backgroundColor: Colors.white, title: const TextFrave(text: 'Purchased', color: Colors.black87, fontWeight: FontWeight.w500, fontSize: 20 ), centerTitle: true, elevation: 0, leading: IconButton( splashRadius: 20, icon: const Icon(Icons.arrow_back_ios_new_rounded, color: Colors.black ), onPressed: () => Navigator.of(context).pop(), ), ), body: FutureBuilder<List<OrderBuy>>( future: productServices.getPurchasedProducts(), builder: (_, snapshot) { return ( !snapshot.hasData ) ? const ShimmerFrave() : _DetailsProductsBuy(ordersBuy: snapshot.data! ); } , ), ); } } class _DetailsProductsBuy extends StatelessWidget { final List<OrderBuy> ordersBuy; const _DetailsProductsBuy({Key? key, required this.ordersBuy}):super(key: key); @override Widget build(BuildContext context) { return ListView.builder( physics: const BouncingScrollPhysics(), padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0), itemCount: ordersBuy.length, itemBuilder: (_, i) => InkWell( onTap: () => Navigator.push(context, routeSlide(page: OrderDetailsPage(uidOrder: ordersBuy[i].uidOrderBuy.toString()))), child: Container( height: 110, padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0), margin: EdgeInsets.only(bottom: 15.0), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(15.0) ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TextFrave(text: ordersBuy[i].receipt, fontSize: 21, color: ColorsFrave.primaryColorFrave, fontWeight: FontWeight.w500), const SizedBox(height: 10.0), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const TextFrave(text: 'Date ', fontSize: 18, color: Colors.grey ), TextFrave(text: timeago.format(ordersBuy[i].createdAt, locale: 'es'), fontSize: 18 ), ], ), const SizedBox(height: 10.0), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const TextFrave(text: 'Amount ', fontSize: 18, color: Colors.grey ), TextFrave(text: '\$ ${ordersBuy[i].amount}', fontSize: 20, fontWeight: FontWeight.w500 ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile/card/add_card.dart
import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; class AddCreditCardPage extends StatelessWidget{ @override Widget build(BuildContext context){ return Scaffold( backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.white, title: const TextFrave(text: 'Add Cards', color: ColorsFrave.primaryColorFrave, fontWeight: FontWeight.w600), centerTitle: true, elevation: 0, leading: IconButton( splashRadius: 20, icon: const Icon(Icons.arrow_back_ios_rounded, color: ColorsFrave.primaryColorFrave), onPressed: () => Navigator.of(context).pop(), ) ), body: Center( child: const Text('Hola Frave Developer'), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile/card/credit_card_page.dart
import 'package:e_commers/data/list_card.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/screen/profile/card/add_card.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; class CreditCardPage extends StatelessWidget { @override Widget build(BuildContext context){ return Scaffold( backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.white, title: const TextFrave(text: 'My Cards', color: ColorsFrave.primaryColorFrave, fontWeight: FontWeight.w600), elevation: 0, leading: IconButton( splashRadius: 20, icon: const Icon(Icons.arrow_back_ios_rounded, color: ColorsFrave.primaryColorFrave), onPressed: () => Navigator.of(context).pop(), ), actions: [ InkWell( onTap: (){}, child: Row( children: [ const Icon(Icons.add_circle_outline_rounded, color: ColorsFrave.primaryColorFrave, size: 17), const SizedBox(width: 5.0), GestureDetector( child: const TextFrave(text: 'Add Card', color: ColorsFrave.primaryColorFrave, fontSize: 15), onTap: () => Navigator.of(context).push(routeSlide(page: AddCreditCardPage())), ), const SizedBox(width: 7.0), ], ), ) ], ), body: Padding( padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( height: 200, child: PageView.builder( controller: PageController(viewportFraction: .9), physics: const BouncingScrollPhysics(), itemCount: cards.length, itemBuilder: (_, i){ final card = cards[i]; return _CreditCard( cardHolderName: card.cardHolderName, cardNumber: card.cardNumber, expiryDate: card.expiracyDate, cvvCode: card.cvv, brand: card.brand, ); }, ), ), const SizedBox(height: 15), const TextFrave(text: 'Last movements', fontSize: 19), const SizedBox(height: 15), Expanded( child: Container( decoration: BoxDecoration( color: Color(0xffF5F5F5), borderRadius: BorderRadius.circular(20.0) ), ), ) ], ), ), ); } } class _CreditCard extends StatelessWidget { final String cardNumber; final String expiryDate; final String cardHolderName; final String cvvCode; final String brand; const _CreditCard({ required this.cardNumber, required this.expiryDate, required this.cardHolderName, required this.cvvCode, required this.brand }); @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return Container( padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0), margin: const EdgeInsets.only(right: 15.0), height: 220, width: size.width, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20.0), color: Color(0xFF3A4960) ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Image.asset('Assets/card-chip.png', height: 60), SvgPicture.asset('Assets/$brand.svg', height: 80 ) ], ), const SizedBox(height: 5.0), Padding( padding: EdgeInsets.only(left: 5.0), child: TextFrave(text: cardNumber, fontSize: 30, color: Colors.white, fontWeight: FontWeight.w700), ), const SizedBox(height: 25.0), Padding( padding: EdgeInsets.only(left: 5.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ TextFrave(text: cardHolderName, fontSize: 23, color: Colors.white ), TextFrave(text: expiryDate, color: Colors.white, fontSize: 19), ], ), ) ], ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/profile/add_product/add_product_page.dart
import 'dart:io'; import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/screen/profile/profile_page.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:form_field_validator/form_field_validator.dart'; import 'package:image_picker/image_picker.dart'; import 'package:permission_handler/permission_handler.dart'; class AddProductPage extends StatefulWidget { AddProductPage({Key? key}) : super(key: key); @override _AddProductPageState createState() => _AddProductPageState(); } class _AddProductPageState extends State<AddProductPage> { late TextEditingController _nameProductController; late TextEditingController _descriptionProductController; late TextEditingController _stockController; late TextEditingController _priceController; final _keyForm = GlobalKey<FormState>(); @override void initState() { _nameProductController = TextEditingController(); _descriptionProductController = TextEditingController(); _stockController = TextEditingController(); _priceController = TextEditingController(); super.initState(); } @override void dispose() { _nameProductController.clear(); _nameProductController.dispose(); _descriptionProductController.clear(); _descriptionProductController.dispose(); _stockController.clear(); _stockController.dispose(); _priceController.clear(); _priceController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; final productBloc = BlocProvider.of<ProductBloc>(context); final categoryBloc = BlocProvider.of<CategoryBloc>(context); return BlocListener<ProductBloc, ProductState>( listener: (context, state) { if(state is LoadingProductState){ modalLoading(context, 'Checking...'); }else if(state is FailureProductState){ Navigator.pop(context); errorMessageSnack(context, state.error); }else if( state is SuccessProductState ){ Navigator.pop(context); modalSuccess(context, 'Product Added!', onPressed: (){ Navigator.pushAndRemoveUntil(context, routeSlide(page: ProfilePage()), (_) => false); }); } }, child: Scaffold( backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.white, title: const TextFrave(text: 'Add New Product', fontSize: 20, fontWeight: FontWeight.bold ), elevation: 0, centerTitle: true, leading: IconButton( splashRadius: 20, onPressed: () => Navigator.pop(context), icon: const Icon(Icons.arrow_back_ios_new_rounded, color: Colors.black87), ), actions: [ TextButton( onPressed: () { if(_keyForm.currentState!.validate()){ productBloc.add( OnSaveNewProductEvent( _nameProductController.text.trim(), _descriptionProductController.text.trim(), _stockController.text.trim(), _priceController.text.trim(), categoryBloc.state.uidCategory.toString(), productBloc.state.pathImage! )); } }, child: const TextFrave(text: 'Save', color: ColorsFrave.primaryColorFrave, fontWeight: FontWeight.w500 ) ) ], ), body: Form( key: _keyForm, child: ListView( padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0), children: [ InkWell( onTap: () => modalSelectPicture( context: context, onPressedImage: () async { Navigator.pop(context); AccessPermission().permissionAccessGalleryOrCameraForProduct( await Permission.storage.request(), context, ImageSource.gallery ); }, onPressedPhoto: () async { Navigator.pop(context); AccessPermission().permissionAccessGalleryOrCameraForProduct( await Permission.camera.request(), context, ImageSource.camera ); }, ), child: BlocBuilder<ProductBloc, ProductState>( builder: (_, state) => state.pathImage != null ? Container( height: 190, width: size.width, decoration: BoxDecoration( borderRadius: BorderRadius.circular(12.0), image: DecorationImage( fit: BoxFit.cover, image: FileImage(File(state.pathImage!)) ) ), ) : Container( height: 190, width: size.width, decoration: BoxDecoration( color: Color(0xfff3f3f3), borderRadius: BorderRadius.circular(12.0) ), child: const Icon(Icons.wallpaper_rounded, size: 80), ), ), ), const SizedBox(height: 20.0), TextFormFrave( controller: _nameProductController, prefixIcon: const Icon(Icons.add), hintText: 'Name Product', validator: RequiredValidator(errorText: 'name is required'), ), const SizedBox(height: 20.0), TextFormFrave( controller: _descriptionProductController, prefixIcon: const Icon(Icons.add), hintText: 'Description Product', validator: RequiredValidator(errorText: 'Description is required'), ), const SizedBox(height: 20.0), TextFormFrave( controller: _stockController, prefixIcon: const Icon(Icons.add), hintText: 'Stock', keyboardType: TextInputType.number, validator: RequiredValidator(errorText: 'Stock is required'), ), const SizedBox(height: 20.0), TextFormFrave( controller: _priceController, prefixIcon: const Icon(Icons.add), hintText: 'Price', keyboardType: TextInputType.number, validator: RequiredValidator(errorText: 'Price is required'), ), const SizedBox(height: 20.0), InkWell( onTap: () => modalCategoies(context, size), borderRadius: BorderRadius.circular(10.0), child: Container( alignment: Alignment.centerLeft, padding: const EdgeInsets.only(left: 20.0), height: 50, width: size.width, decoration: BoxDecoration( color: Color(0xfff3f3f3), borderRadius: BorderRadius.circular(10.0) ), child: BlocBuilder<CategoryBloc, CategoryState>( builder: (_, state) => state.uidCategory != null ? TextFrave(text: state.nameCategory!, color: Colors.black54) : TextFrave(text: 'Select Category', color: Colors.black54) ) ), ), ], ), ), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/categories/product_for_category_page.dart
import 'package:e_commers/data/env/env.dart'; import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/domain/models/response/response_products_home.dart'; import 'package:e_commers/domain/services/services.dart'; import 'package:e_commers/presentation/components/shimmer_frave.dart'; import 'package:e_commers/presentation/components/staggered_dual_view.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/screen/products/details_product_page.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class CategoryProductsPage extends StatefulWidget { final String uidCategory; final String category; const CategoryProductsPage({ required this.uidCategory, required this.category}); @override _CategoryProductsPageState createState() => _CategoryProductsPageState(); } class _CategoryProductsPageState extends State<CategoryProductsPage> { @override Widget build(BuildContext context){ final productBloc = BlocProvider.of<ProductBloc>(context); return BlocListener<ProductBloc, ProductState>( listener: (context, state){ if( state is LoadingProductState ){ modalLoadingShort(context); }else if( state is FailureProductState ){ Navigator.pop(context); errorMessageSnack(context, state.error); }else if( state is SuccessProductState ){ Navigator.pop(context); setState(() {}); } }, child: Scaffold( backgroundColor: Color(0xfff5f5f5), appBar: AppBar( title: TextFrave(text: widget.category, color: Colors.black, fontWeight: FontWeight.w500, fontSize: 20), centerTitle: true, elevation: 0, backgroundColor: Colors.white, leading: IconButton( splashRadius: 20, icon: Icon(Icons.arrow_back_ios_new_rounded, color: Colors.black), onPressed: () => Navigator.pop(context), ), ), body: FutureBuilder<List<ListProducts>>( future: productServices.getProductsForCategories(widget.uidCategory), builder: (context, snapshot) => !snapshot.hasData ? Column( children: const [ ShimmerFrave(), SizedBox(height: 10.0), ShimmerFrave(), SizedBox(height: 10.0), ShimmerFrave(), ], ) : Padding( padding: EdgeInsets.all(10.0), child: StaggeredDualView( itemCount: snapshot.data!.length, spacing: 5, alturaElement: 0.15, aspectRatio: 0.8, itemBuilder: (context, i) => Card( shadowColor: Colors.black26, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20) ), elevation: 10.0, child: InkWell( borderRadius: BorderRadius.circular(20), splashColor: Colors.blue[300], onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => DetailsProductPage(product: snapshot.data![i]))), child: Padding( padding: const EdgeInsets.all(15.0), child: Stack( children: [ Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( child: Hero( tag: snapshot.data![i].uidProduct.toString(), child: Image.network(Environment.baseUrl+ snapshot.data![i].picture, height: 120) ), ), const SizedBox(height: 10.0), TextFrave(text: snapshot.data![i].nameProduct, fontWeight: FontWeight.w500 ), TextFrave(text: '\$ ${snapshot.data![i].price}', fontSize: 16 ), ], ), Positioned( right: 0, child: snapshot.data![i].isFavorite == 1 ? InkWell( onTap: () => productBloc.add( OnAddOrDeleteProductFavoriteEvent(uidProduct: snapshot.data![i].uidProduct.toString())), child: const Icon(Icons.favorite_rounded, color: Colors.red), ) : InkWell( onTap: () => productBloc.add( OnAddOrDeleteProductFavoriteEvent(uidProduct: snapshot.data![i].uidProduct.toString())), child: Icon(Icons.favorite_outline_rounded) ) ), ], ), ), ), ) ), ), ) ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/categories/categories_page.dart
import 'package:e_commers/data/env/env.dart'; import 'package:e_commers/domain/models/response/response_categories_home.dart'; import 'package:e_commers/domain/services/services.dart'; import 'package:e_commers/presentation/components/shimmer_frave.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/screen/categories/product_for_category_page.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; class CategoriesPage extends StatelessWidget { const CategoriesPage({Key? key}):super(key: key); @override Widget build(BuildContext context){ return Scaffold( backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.white, leading: IconButton( splashRadius: 20, icon: Icon(Icons.arrow_back_ios_rounded, color: Colors.black87), onPressed: () => Navigator.pop(context), ), elevation: 0, title: const TextFrave(text: 'Categories', color: Colors.black87, fontWeight: FontWeight.w500, fontSize: 20), centerTitle: true, ), body: FutureBuilder<List<Categories>>( future: productServices.getAllCategories(), builder: (context, snapshot){ return !snapshot.hasData ? Column( children: const [ ShimmerFrave(), SizedBox(height: 10.0), ShimmerFrave(), SizedBox(height: 10.0), ShimmerFrave(), ], ) : _ListCategories(categories: snapshot.data!); }, ), ); } } class _ListCategories extends StatelessWidget { final List<Categories> categories; const _ListCategories({ Key? key, required this.categories}): super(key: key); @override Widget build(BuildContext context) { return GridView.builder( physics: BouncingScrollPhysics(), padding: EdgeInsets.all(10.0), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 15, mainAxisSpacing: 15, mainAxisExtent: 180 ), itemCount: categories.length, itemBuilder: (context, i) => GestureDetector( child: Container( padding: EdgeInsets.all(15.0), decoration: BoxDecoration( color: ColorsFrave.primaryColorFrave.withOpacity(.2), borderRadius: BorderRadius.circular(10.0) ), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ SvgPicture.network(Environment.baseUrl+ categories[i].picture, height: 85), const SizedBox(height: 10.0), TextFrave(text: categories[i].category, fontSize: 20, overflow: TextOverflow.ellipsis ) ], ), ), onTap: () => Navigator.push(context, routeSlide(page: CategoryProductsPage(uidCategory: categories[i].uidCategory.toString(), category: categories[i].category))) ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/favorite/favorite_page.dart
import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/domain/models/response/response_products_home.dart'; import 'package:e_commers/domain/services/services.dart'; import 'package:e_commers/presentation/components/shimmer_frave.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/screen/favorite/widgets/list_favorite.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class FavoritePage extends StatefulWidget { @override State<FavoritePage> createState() => _FavoritePageState(); } class _FavoritePageState extends State<FavoritePage> { @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return BlocListener<ProductBloc, ProductState>( listener: (context, state){ if( state is LoadingProductState ){ modalLoadingShort(context); }else if( state is FailureProductState ){ Navigator.pop(context); errorMessageSnack(context, state.error); }else if( state is SuccessProductState ){ Navigator.pop(context); setState(() {}); } }, child: Scaffold( backgroundColor: Color(0xffF5F5F5), appBar: AppBar( title: const TextFrave(text: 'Favorites', color: Colors.black, fontSize: 20, fontWeight: FontWeight.w500 ), centerTitle: true, backgroundColor: Color(0xfff2f2f2), elevation: 0, automaticallyImplyLeading: false, ), body: Stack( children: [ FutureBuilder<List<ListProducts>>( future: productServices.allFavoriteProducts(), builder: (context, snapshot) => !snapshot.hasData ? Column( children: const [ ShimmerFrave(), SizedBox(height: 10.0), ShimmerFrave(), SizedBox(height: 10.0), ShimmerFrave(), ], ) : ListFavoriteProduct(products: snapshot.data! ) ), Positioned( bottom: 20, child: Container( width: size.width, child: Align( child: BottomNavigationFrave(index: 2) ) ), ), ], ), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/favorite
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/favorite/widgets/list_favorite.dart
import 'package:e_commers/data/env/env.dart'; import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/domain/models/response/response_products_home.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/screen/products/details_product_page.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class ListFavoriteProduct extends StatelessWidget { final List<ListProducts> products; const ListFavoriteProduct({Key? key, required this.products}): super(key: key); @override Widget build(BuildContext context) { return GridView.builder( physics: BouncingScrollPhysics(), padding: EdgeInsets.only(left: 15.0, right: 15.0, bottom: 90), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 25, mainAxisSpacing: 20, mainAxisExtent: 220 ), itemCount: products.length, itemBuilder: (context, i) => ProductFavorite( product: products[i] ) ); } } class ProductFavorite extends StatelessWidget { final ListProducts product; ProductFavorite({Key? key, required this.product}): super(key: key); @override Widget build(BuildContext context) { final productBloc = BlocProvider.of<ProductBloc>(context); return GestureDetector( onTap: () => Navigator.push(context, routeSlide(page: DetailsProductPage(product: product))), child: Container( padding: EdgeInsets.all(10.0), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20.0) ), child: Stack( children: [ Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image.network(Environment.baseUrl + product.picture, height: 120 ), TextFrave(text: product.nameProduct, fontSize: 17, overflow: TextOverflow.ellipsis ), const SizedBox(height: 10.0), TextFrave(text: '\$ ${product.price}', fontSize: 21, fontWeight: FontWeight.bold), ], ), Positioned( right: 0, child: InkWell( onTap: () => productBloc.add( OnAddOrDeleteProductFavoriteEvent(uidProduct: product.uidProduct.toString())), child: const Icon(Icons.favorite_rounded, color: Colors.red), ) ), ], ), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/home/home_page.dart
import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/screen/categories/categories_page.dart'; import 'package:e_commers/presentation/screen/home/widgets/carousel_home.dart'; import 'package:e_commers/presentation/screen/home/widgets/header_home.dart'; import 'package:e_commers/presentation/screen/home/widgets/list_categories_home.dart'; import 'package:e_commers/presentation/screen/home/widgets/list_products_home.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class HomePage extends StatefulWidget { @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context){ final size = MediaQuery.of(context).size; return BlocListener<ProductBloc, ProductState>( listener: (context, state){ if( state is LoadingProductState ){ modalLoadingShort(context); }else if( state is FailureProductState ){ Navigator.pop(context); errorMessageSnack(context, state.error); }else if( state is SuccessProductState ){ Navigator.pop(context); setState(() {}); } }, child: Scaffold( backgroundColor: Color(0xfff5f5f5), body: Stack( children: [ ListHome(), Positioned( bottom: 20, child: Container( width: size.width, child: Align( alignment: Alignment.center, child: BottomNavigationFrave(index: 1) ) ), ), ], ), ), ); } } class ListHome extends StatefulWidget { @override _ListHomeState createState() => _ListHomeState(); } class _ListHomeState extends State<ListHome> { late ScrollController _scrollControllerHome; double scrollPrevious = 0; @override void initState() { _scrollControllerHome = ScrollController(); _scrollControllerHome.addListener(addListenerMenu); super.initState(); } void addListenerMenu(){ if( _scrollControllerHome.offset > scrollPrevious ){ BlocProvider.of<GeneralBloc>(context).add( OnShowOrHideMenuEvent(showMenu: false)); } else { BlocProvider.of<GeneralBloc>(context).add( OnShowOrHideMenuEvent(showMenu: true)); } scrollPrevious = _scrollControllerHome.offset; } @override void dispose() { _scrollControllerHome.removeListener(addListenerMenu); _scrollControllerHome.dispose(); super.dispose(); } @override Widget build(BuildContext context){ return SafeArea( child: ListView( padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0), controller: _scrollControllerHome, children: [ const HeaderHome(), const SizedBox(height: 10.0), const CardCarousel(), const SizedBox(height: 15.0), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const TextFrave(text: 'Categories', fontSize: 18, fontWeight: FontWeight.w600,), GestureDetector( onTap: () => Navigator.of(context).push(routeSlide(page: CategoriesPage())), child: Row( children: const [ TextFrave(text: 'See All', fontSize: 17 ), SizedBox(width: 5.0), Icon(Icons.arrow_forward_ios_rounded, size: 18, color: Color(0xff006CF2)) ], ), ), ], ), const SizedBox(height: 15.0), const ListCategoriesHome(), const SizedBox(height: 15.0), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const TextFrave(text: 'Popular Products', fontSize: 18, fontWeight: FontWeight.w600,), Row( children: const [ TextFrave(text: 'See All', fontSize: 17 ), SizedBox(width: 5.0), Icon(Icons.arrow_forward_ios_rounded, size: 18, color: Color(0xff006CF2)) ], ), ], ), const SizedBox(height: 15.0), ListProductsForHome() ], ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/home
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/home/widgets/carousel_home.dart
import 'package:carousel_slider/carousel_slider.dart'; import 'package:e_commers/data/env/env.dart'; import 'package:e_commers/domain/models/response/response_slide_products.dart'; import 'package:e_commers/domain/services/services.dart'; import 'package:e_commers/presentation/components/shimmer_frave.dart'; import 'package:flutter/material.dart'; class CardCarousel extends StatelessWidget { const CardCarousel({Key? key}):super(key: key); @override Widget build(BuildContext context) { return Container( height: 190, width: MediaQuery.of(context).size.width, child: FutureBuilder<List<SlideProduct>>( future: productServices.listProductsHomeCarousel(), builder: (context, snapshot) { return !snapshot.hasData ? const ShimmerFrave() : CarouselSlider.builder( itemCount: snapshot.data!.length, options: CarouselOptions( enableInfiniteScroll: true, autoPlay: true, autoPlayInterval: const Duration(seconds: 3), viewportFraction: 1, ), itemBuilder: (context, index, realIndex) { return Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), image: DecorationImage( fit: BoxFit.cover, image: NetworkImage(Environment.baseUrl + snapshot.data![index].image) ) ), ); }, ); } ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/home
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/home/widgets/list_categories_home.dart
import 'package:e_commers/domain/models/response/response_categories_home.dart'; import 'package:e_commers/domain/services/services.dart'; import 'package:e_commers/presentation/components/shimmer_frave.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; class ListCategoriesHome extends StatelessWidget { const ListCategoriesHome({Key? key}): super(key: key); @override Widget build(BuildContext context) { return Container( height: 40, width: MediaQuery.of(context).size.width, child: FutureBuilder<List<Categories>>( future: productServices.listCategoriesHome(), builder: (context, snapshot) { return !snapshot.hasData ? const ShimmerFrave() : ListView.builder( physics: BouncingScrollPhysics(), scrollDirection: Axis.horizontal, itemCount: snapshot.data!.length, itemBuilder: (context, i) => Container( margin: EdgeInsets.only(right: 8.0), padding: EdgeInsets.symmetric(horizontal: 10.0), width: 150, decoration: BoxDecoration( color: Color(0xff0C6CF2).withOpacity(.1), borderRadius: BorderRadius.circular(10.0) ), child: Center( child: TextFrave( text: snapshot.data![i].category, color: ColorsFrave.primaryColorFrave, overflow: TextOverflow.ellipsis, fontSize: 17, ) ), ), ); }, ), ); } }
0