repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/mynotes/lib/pages/auth
mirrored_repositories/mynotes/lib/pages/auth/widgets/head_title.dart
import 'package:flutter/material.dart'; import 'package:mynotes/pages/utility/util.dart'; class HeadTitle extends StatelessWidget { const HeadTitle({ Key? key }) : super(key: key); @override Widget build(BuildContext context) { return Column( children: [ Container( child: txt("Hello, Guest 👋 ",font: 'Open Sans',size: 20.0), ), SizedBox(height: 5,), Container( child: txt("Start noting your works now",font: 'Open Sans',size: 15.0), ), ], ); } }
0
mirrored_repositories/mynotes/lib/pages/auth
mirrored_repositories/mynotes/lib/pages/auth/widgets/login_header.dart
import 'package:flutter/material.dart'; import 'package:mynotes/pages/utility/util.dart'; class LoginHeader extends StatelessWidget { const LoginHeader({ Key? key }) : super(key: key); @override Widget build(BuildContext context) { return Container( height: h(context) * 0.3, width: w(context), margin: EdgeInsets.only(top: h(context)*0.2), decoration:BoxDecoration( image: DecorationImage( fit: BoxFit.cover, image: AssetImage('assets/loginImg.png')) ) ); } }
0
mirrored_repositories/mynotes/lib/pages/auth
mirrored_repositories/mynotes/lib/pages/auth/widgets/auth_loader.dart
import 'package:flutter/material.dart'; class AuthLoader extends StatelessWidget { const AuthLoader({ Key? key }) : super(key: key); @override Widget build(BuildContext context) { return Container( ); } }
0
mirrored_repositories/mynotes/lib/pages
mirrored_repositories/mynotes/lib/pages/splash/splash.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:mynotes/pages/utility/util.dart'; import 'package:shimmer_animation/shimmer_animation.dart'; class Splash extends StatelessWidget { const Splash({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Shimmer( color: Colors.purple, child: Scaffold( backgroundColor: darkBg, body: Column( mainAxisAlignment:MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Center( child: Text('My Notes', style: GoogleFonts.getFont('Open Sans', color: Colors.white, fontSize: 30, fontWeight: FontWeight.bold ), ), ) ],), ), ); } }
0
mirrored_repositories/mynotes/lib
mirrored_repositories/mynotes/lib/models/note.dart
class Note { String title; String desc; String tag; Note({required this.title, required this.desc, required this.tag}); factory Note.fromJson(Map<String, dynamic> json) { return Note(title: json['title'], desc: json['desc'], tag: json['tag']); } }
0
mirrored_repositories/mynotes/lib
mirrored_repositories/mynotes/lib/models/user.dart
class Users { String email; String name; String photoUrl; Users({required this.email, required this.name, required this.photoUrl}); factory Users.fromJson(Map<String, dynamic> json) { return Users( email: json['email'], name: json['name'], photoUrl: json['photoUrl']); } Map<String,dynamic> toJson(Users user) { Map<String, dynamic> json ={ 'email':user.email, 'name' :user.name, 'photoUrl':user.photoUrl }; return json; } }
0
mirrored_repositories/mynotes/lib
mirrored_repositories/mynotes/lib/services/local_storage.dart
import 'package:get_storage/get_storage.dart'; import 'package:mynotes/models/user.dart'; import 'package:shared_preferences/shared_preferences.dart'; class LocalStorage { void addUserInfoToLocalStorage(Users user) async { final box = GetStorage(); box.write('isLogged', true); box.write('email', user.email); box.write('name', user.name); box.write('photoUrl', user.photoUrl); box.write('isDark', false); } Future<bool> isLogged() async { final box = GetStorage(); bool res = false; if (box.hasData('isLogged')) res = box.read('isLogged'); return res; } Future<Map<String, dynamic>> getSavedUser() async { final box = GetStorage(); Map<String, dynamic> data = {'user': null, 'success': false}; try { String name = box.read('name')!; String email = box.read('email')!; String photoUrl = box.read('photoUrl')!; print('photo url is : ' + photoUrl.toString()); Users user = new Users(email: email, name: name, photoUrl: photoUrl); data['user'] = user; data['success'] = true; } catch (e) { print(e); } finally { return data; } } void removeLoginData() { final box = GetStorage(); try { box.write('isLogged', false); } catch (e) { print(e); } } void setDarkMode() { final box = GetStorage(); box.write('isDark', true); } void setLightMode() { final box = GetStorage(); box.write('isDark', false); } }
0
mirrored_repositories/mynotes/lib
mirrored_repositories/mynotes/lib/services/firebase_service.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:mynotes/models/note.dart'; import 'package:mynotes/models/user.dart'; class FirebaseService { final FirebaseAuth _auth = FirebaseAuth.instance; final GoogleSignIn _googleSignIn = GoogleSignIn(); Future<User?> signInwithGoogle() async { try { final GoogleSignInAccount? googleSignInAccount = await _googleSignIn.signIn(); final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount!.authentication; final AuthCredential credential = GoogleAuthProvider.credential( accessToken: googleSignInAuthentication.accessToken, idToken: googleSignInAuthentication.idToken, ); await _auth.signInWithCredential(credential); User? user = FirebaseAuth.instance.currentUser; return user; } on FirebaseAuthException catch (e) { print(e.message); throw e; } } Future<void> signOutFromGoogle() async { await _googleSignIn.signOut(); await _auth.signOut(); } addUserToFirebase(Users user) async { final FirebaseFirestore _firestore = FirebaseFirestore.instance; final CollectionReference _user = _firestore.collection('users'); QuerySnapshot existingUser = await _user.where('email', isEqualTo: user.email).get(); if (existingUser.docs.isEmpty) { _user.doc(user.email).set({ 'email': user.email, 'name': user.name, 'photoUrl': user.photoUrl, }); } } Future<bool> addNoteToFirebase(String email, Note note) async { try { final FirebaseFirestore _firestore = FirebaseFirestore.instance; final CollectionReference _note = _firestore.collection('notes'); _note.add({ 'email': email, 'title': note.title, 'desc': note.desc, 'tag': note.tag }); return true; } catch (e) { print(e); return false; } } Future<bool> removeNoteFromFirebase(Note note, String email) async { try { final FirebaseFirestore _firestore = FirebaseFirestore.instance; final CollectionReference _note = _firestore.collection('notes'); QuerySnapshot _thisNote = await _note .where('email', isEqualTo: email) .where('title', isEqualTo: note.title) .where('desc', isEqualTo: note.desc) .where('tag', isEqualTo: note.tag) .get(); if (_thisNote.docs.isNotEmpty) { _note.doc(_thisNote.docs[0].id).delete(); return true; } return false; } catch (e) { print(e); return false; } } Future<bool> editNoteInFirebase( String email, Note newNote, Note oldNote) async { try { final FirebaseFirestore _firestore = FirebaseFirestore.instance; final CollectionReference _note = _firestore.collection('notes'); QuerySnapshot _thisNote = await _note .where('email', isEqualTo: email) .where('title', isEqualTo: oldNote.title) .where('desc', isEqualTo: oldNote.desc) .where('tag', isEqualTo: oldNote.tag) .get(); if (_thisNote.docs.isNotEmpty) { _note.doc(_thisNote.docs[0].id).set({ 'email':email, 'title':newNote.title, 'desc':newNote.desc, 'tag':newNote.tag },SetOptions(merge: true)); return true; } return false; } catch (e) { print(e); return false; } } Future<bool> removeAllNotes(String email) async { try { final FirebaseFirestore _firestore = FirebaseFirestore.instance; final CollectionReference _note = _firestore.collection('notes'); QuerySnapshot _thisNote = await _note.where('email', isEqualTo: email).get(); if (_thisNote.docs.isNotEmpty) { _thisNote.docs.forEach((element) { _note.doc(element.id).delete(); }); return true; } return false; } catch (e) { print(e); return false; } } }
0
mirrored_repositories/Booking-app
mirrored_repositories/Booking-app/lib/constants.dart
import 'package:flutter/material.dart'; import 'package:line_icons/line_icons.dart'; InputDecoration kInputField = InputDecoration( contentPadding: EdgeInsets.symmetric(vertical: 10), fillColor: Colors.white.withAlpha(200), filled: true, errorStyle: TextStyle(fontFamily: 'Patrick'), hintStyle: TextStyle(fontSize: 16, color: Colors.black54, fontFamily: 'Sans'), prefixIcon: Icon( LineIcons.search, color: Color(0xFFCE832D).withOpacity(0.8), size: 24, ), border: outlineBorder, enabledBorder: outlineBorder, focusedBorder: outlineBorder); final outlineBorder = OutlineInputBorder( borderSide: BorderSide.none, borderRadius: BorderRadius.circular(10), ); TextStyle kFieldTitle = TextStyle( fontFamily: 'Patrick', fontSize: 18, color: Colors.black.withOpacity(0.8), fontWeight: FontWeight.bold); TextStyle kCardTitle = TextStyle( fontSize: 26.0, fontWeight: FontWeight.bold, color: Colors.black, fontFamily: 'Patrick', ); TextStyle kInputText = TextStyle( fontSize: 18.0, fontWeight: FontWeight.w500, color: Colors.black87, fontFamily: 'Sans', ); ShapeBorder kBackButtonShape = RoundedRectangleBorder( borderRadius: BorderRadius.only( topRight: Radius.circular(30), ), ); Widget kBackBtn = Icon( Icons.arrow_back_ios, // color: Colors.black54, ); final kHotelCard = TextStyle( color: Colors.black, fontSize: 18.0, fontWeight: FontWeight.bold, fontFamily: 'Sans'); final kBlueColor = Color(0xFF2A6CDC); final kGoldColor = Color(0xFFE0B84C);
0
mirrored_repositories/Booking-app
mirrored_repositories/Booking-app/lib/main.dart
import 'package:booking_app/screens/search_screen.dart'; import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData.light(), home: WelcomScreen(), ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/widgets/row_item_widget.dart
import 'package:flutter/material.dart'; class RowItemWidget extends StatelessWidget { final String name; final String value; const RowItemWidget({Key key, this.name, this.value}) : super(key: key); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( name, style: TextStyle( fontFamily: 'Sans', fontWeight: FontWeight.bold, fontSize: 16.0, ), ), Text( value, style: TextStyle( fontFamily: 'Sans', color: Colors.black38, height: 1.5, fontSize: 16.0), ) ], ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/widgets/details_widget.dart
import 'package:booking_app/constants.dart'; import 'package:flutter/material.dart'; class DetailsWidget extends StatelessWidget { const DetailsWidget({ Key key, @required this.data, this.title, }) : super(key: key); final String data; final String title; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(12.0), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text( title, style: kCardTitle.copyWith( color: kGoldColor, ), ), Text( data, textAlign: TextAlign.center, style: TextStyle( fontFamily: 'Sans', fontWeight: FontWeight.bold, fontSize: 20.0, ), ), ], ), ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/widgets/size_confige.dart
import 'package:flutter/material.dart'; class SizeConfig { static double screenWidth; static double screenHeight; static initSize(BuildContext context) { final mediaQuery = MediaQuery.of(context); screenWidth = mediaQuery.size.width; screenHeight = mediaQuery.size.height; } } double getRelativeHeight(double percentage) { return 10; } double getRelativeWidth(double percentage) { return 30; }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/widgets/image_slider_indicator.dart
import 'package:flutter/material.dart'; import 'package:flutter_slider_indicator/flutter_slider_indicator.dart'; class ImageSliderIndicator extends StatelessWidget { const ImageSliderIndicator({ Key key, @required this.imgCount, @required int currentIndex, }) : _currentIndex = currentIndex, super(key: key); final imgCount; final int _currentIndex; @override Widget build(BuildContext context) { return Align( alignment: Alignment.topCenter, child: Padding( padding: EdgeInsets.only(top: MediaQuery.of(context).size.height * .45), child: SliderIndicator( length: imgCount, activeIndex: _currentIndex, indicator: Icon( Icons.radio_button_unchecked, color: Colors.white, size: 10.0, ), activeIndicator: Icon( Icons.fiber_manual_record, color: Colors.white, size: 12.0, )), ), ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/widgets/complete_search_field.dart
import 'package:booking_app/constants.dart'; import 'package:flutter/material.dart'; class SearchField extends StatelessWidget { const SearchField({ Key key, @required this.checkInController, @required this.searchButtonPressed, this.title, this.hintText, this.width, this.textInputType, }) : super(key: key); final TextEditingController checkInController; final bool searchButtonPressed; final String title; final String hintText; final width; final TextInputType textInputType; @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: const EdgeInsets.only(left: 16.0), child: Text( title, style: kFieldTitle, textAlign: TextAlign.start, ), ), Padding( padding: const EdgeInsets.fromLTRB(12, 0, 12, 0), child: Container( width: width, child: Center( child: TextField( keyboardType: textInputType, controller: checkInController, style: kInputText, decoration: kInputField.copyWith( hintText: hintText, errorText: checkInController.text.isEmpty && searchButtonPressed ? 'Value Can\'t Be Empty' : null, ), ), ), ), ), ], ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/widgets/image_slider_widget.dart
import 'package:flutter/material.dart'; class ImageSliderWidget extends StatelessWidget { const ImageSliderWidget({ Key key, @required PageController pageController, @required this.url, }) : _pageController = pageController, super(key: key); final PageController _pageController; final url; @override Widget build(BuildContext context) { return Container( height: MediaQuery.of(context).size.height * .6, child: PageView.builder( controller: _pageController, itemBuilder: (context, index) { return Image.network( url[index]['baseUrl'].replaceAll('_{size}', '').toString(), fit: BoxFit.cover, ); }), ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/widgets/back_button_widget.dart
import 'package:flutter/material.dart'; class BackButtonWidget extends StatelessWidget { const BackButtonWidget({ Key key, }) : super(key: key); @override Widget build(BuildContext context) { return Align( alignment: Alignment.topRight, child: Container( margin: EdgeInsets.only(right: 24, top: 45), child: IconButton( icon: Icon( Icons.close, color: Colors.white, ), onPressed: () { Navigator.pop(context); }, ), ), ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/widgets/price_widget.dart
import 'package:flutter/material.dart'; class PriceWidget extends StatelessWidget { final price; const PriceWidget({ Key key, this.price, }) : super(key: key); @override Widget build(BuildContext context) { return Container( margin: EdgeInsets.only(left: 24, top: 50), padding: EdgeInsets.symmetric(vertical: 6, horizontal: 12), decoration: BoxDecoration( color: Colors.white70, borderRadius: BorderRadius.circular(25), ), child: Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[ Text( price + ' /per day', style: TextStyle( fontFamily: 'Sans', fontSize: 16.2, color: Colors.black, ), ), ], )); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/widgets/star_display.dart
import 'package:flutter/material.dart'; class StarDisplay extends StatelessWidget { final int value; const StarDisplay({Key key, this.value = 0}) : assert(value != null), super(key: key); @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, children: List.generate(5, (index) { return Icon( index < value ? Icons.star : Icons.star_border, color: Color(0xFFF6AA3F), ); }), ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/widgets/search_field.dart
import 'package:booking_app/constants.dart'; import 'package:flutter/material.dart'; // ignore: must_be_immutable class SearchField extends StatelessWidget { var myController = TextEditingController(); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.fromLTRB(12, 0, 12, 0), child: Container( width: MediaQuery.of(context).size.width / 2.55, child: Center( child: TextFormField( controller: myController, decoration: kInputField ), ), ), ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/widgets/loading_spin.dart
import 'package:flutter/material.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; class LoadingSpinWidget extends StatelessWidget { const LoadingSpinWidget({ Key key, @required this.searchButtonPressed, }) : super(key: key); final bool searchButtonPressed; @override Widget build(BuildContext context) { return Visibility( visible: searchButtonPressed, child: Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, decoration: BoxDecoration( color: Colors.black54, ), child: Center( child: Container( width: 100.0, height: 100.0, decoration: BoxDecoration( color: Colors.black26, borderRadius: BorderRadius.circular(45), ), child: SpinKitCircle( color: Color(0xFFE0B84C), size: 60.0, ), ), ), ), ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/widgets/app_bar.dart
import 'package:booking_app/constants.dart'; import 'package:booking_app/screens/search_screen.dart'; import 'package:flutter/material.dart'; class AppBarWidget extends StatelessWidget { const AppBarWidget({ Key key, }) : super(key: key); @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration(boxShadow: [ BoxShadow(color: Color(0xFFF9F9F9), spreadRadius: 5, blurRadius: 2) ]), height: 84, child: Container( decoration: BoxDecoration( color: kGoldColor, borderRadius: BorderRadius.only( bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20))), child: Container( margin: EdgeInsets.fromLTRB(0, 20, 0, 0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ GestureDetector( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return WelcomScreen(); })); }, child: Padding( padding: const EdgeInsets.fromLTRB(12, 10, 0, 0), child: Icon( Icons.navigate_before, size: 25, color: Color(0xFFF9F9F9), ), ), ), Padding( padding: const EdgeInsets.fromLTRB(0, 10, 12, 0), child: Text( "Available Hotels", style: TextStyle( fontSize: 30, color: Color(0xFFF9F9F9), fontFamily: 'Sans', ), ), ), Icon( Icons.navigate_before, color: Colors.transparent, ), ], ), ), ), ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/widgets/hotel_card.dart
import 'package:booking_app/constants.dart'; import 'package:booking_app/widgets/star_display.dart'; import 'package:flutter/material.dart'; class HotelCard extends StatelessWidget { HotelCard( {@required this.imgUrl, @required this.placeName, @required this.rate, @required this.price}); final String imgUrl; final String placeName; final double rate; final String price; @override Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(12.0), height: 250, child: Stack( children: <Widget>[ Align( alignment: Alignment.centerRight, child: Container( width: MediaQuery.of(context).size.width * .59, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), image: DecorationImage( image : NetworkImage(imgUrl), fit: BoxFit.cover, ), boxShadow: [ BoxShadow( blurRadius : 7, spreadRadius: 1, color: Colors.black12, ) ] ), ), ), Align( alignment: Alignment.centerLeft, child: Container( width: MediaQuery.of(context).size.width * .43, height: 250.0, padding: EdgeInsets.all(12), decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(20)), color: Colors.white, boxShadow: [ BoxShadow( blurRadius : 7, spreadRadius: 1, color: Colors.black12, ) ] ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( placeName, style: kHotelCard, textAlign: TextAlign.left, ), StarDisplay( value: rate.toInt(), ), Text( price + ' /per night', style: kHotelCard, textAlign: TextAlign.left, ), ], ), ), ) ], ), ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/services/networking.dart
import 'dart:convert'; import 'package:http/http.dart' as http; class NetworkHelper { final String apiKey = "f1025a44cbmshae5cfb6a84ccd5dp1ef9d9jsn0f2cd8f80dcf"; final headers = { 'x-rapidapi-key': "f1025a44cbmshae5cfb6a84ccd5dp1ef9d9jsn0f2cd8f80dcf", 'x-rapidapi-host': "hotels4.p.rapidapi.com" }; Future getData() async { http.Response response = await http.get( "https://api.opentripmap.com/0.1/en/places/xid/R4682064?apikey=5ae2e3f221c38a28845f05b6862cadcee936a16d50308813cb45978b"); if (response.statusCode == 200) { return jsonDecode(response.body); } else { print('404 error'); } } Future getHotel(String hotelID) async { var endpointUrl = "https://hotels4.p.rapidapi.com/properties/list"; String queryString = Uri(queryParameters: { "destinationId": hotelID, "pageNumber": "1", "checkIn": "2021-04-12", "checkOut": "2021-04-15", "pageSize": "25", "adults1": "1", "currency": "USD", "locale": "en_US", "sortOrder": "PRICE" }).query; var requestUrl = endpointUrl + '?' + queryString; http.Response response = await http.get( requestUrl, headers: headers, ); print(response); return jsonDecode(response.body); } Future getDetails(String hotelID) async { var endpointUrl = "https://hotels4.p.rapidapi.com/properties/get-details"; String queryString = Uri(queryParameters: { "id": hotelID, "locale": "en_US", "currency": "USD", "checkOut": "2020-01-15", "adults1": "1", "checkIn": "2020-01-08" }).query; var requestUrl = endpointUrl + '?' + queryString; http.Response response = await http.get( requestUrl, headers: headers, ); return jsonDecode(response.body); } Future getImages(String hotelID) async { var endpointUrl = "https://hotels4.p.rapidapi.com/properties/get-hotel-photos"; String queryString = Uri(queryParameters: {"id": hotelID}).query; print(queryString); var requestUrl = endpointUrl + '?' + queryString; http.Response response = await http.get( requestUrl, headers: headers, ); return jsonDecode(response.body); } Future getLocation(String str) async { var endpointUrl = "https://hotels4.p.rapidapi.com/locations/search"; String queryString = Uri(queryParameters: {"query": str, "locale": "en_US"}).query; var requestUrl = endpointUrl + '?' + queryString; print(requestUrl); http.Response response = await http.get( requestUrl, headers: headers, ); return jsonDecode(response.body); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/screens/home_screen.dart
import 'package:flutter/cupertino.dart'; class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return WillPopScope( // ignore: missing_return onWillPop: () { int count = 0; Navigator.of(context).popUntil((_) => count++ >= 2); }, child: Container( ), ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/screens/details_screen.dart
import 'dart:convert'; import 'package:booking_app/constants.dart'; import 'package:booking_app/widgets/back_button_widget.dart'; import 'package:booking_app/widgets/details_widget.dart'; import 'package:booking_app/widgets/image_slider_indicator.dart'; import 'package:booking_app/widgets/image_slider_widget.dart'; import 'package:booking_app/widgets/price_widget.dart'; import 'package:booking_app/widgets/row_item_widget.dart'; import 'package:flutter/material.dart'; class DetailsPage extends StatefulWidget { DetailsPage( {@required this.hotelImages, @required this.hotelDetails, this.jsnData}); final hotelImages; final hotelDetails; final jsnData; @override _DetailsPageState createState() => _DetailsPageState(); } class _DetailsPageState extends State<DetailsPage> { var _pageController = PageController(); var _currentIndex = 0; @override Widget build(BuildContext context) { var data = widget.jsnData; _pageController.addListener(() { setState(() { _currentIndex = _pageController.page.round(); }); }); dynamic tag = widget.hotelDetails['data']['body']['propertyDescription'] ['tagline'][0] .replaceAll('<b>', ''); dynamic imgCount = widget.hotelImages['hotelImages'].length; if (imgCount > 12) imgCount = 12; tag = tag.replaceAll('</b>', ''); return Scaffold( body: Stack( children: <Widget>[ ImageSliderWidget( pageController: _pageController, url: widget.hotelImages['hotelImages']), ImageSliderIndicator(imgCount: imgCount, currentIndex: _currentIndex), BackButtonWidget(), PriceWidget( price: widget.hotelDetails['data']['body']['propertyDescription'] ['featuredPrice']['currentPrice']['formatted'], ), DraggableScrollableSheet( initialChildSize: .5, maxChildSize: .8, minChildSize: .5, builder: (context, controller) { return SingleChildScrollView( controller: controller, child: Stack( children: <Widget>[ Container( margin: EdgeInsets.only(top: 25), width: MediaQuery.of(context).size.width, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topLeft: Radius.circular(25), topRight: Radius.circular(25)), ), child: Column( children: <Widget>[ Center( child: Icon(Icons.drag_handle, color: Colors.black38), ), Padding( padding: EdgeInsets.all(24.0), child: Text( widget.hotelDetails['data']['body'] ['propertyDescription']['name'], style: TextStyle( color: Colors.black, fontFamily: 'Sans', fontSize: 30.0)), ), Padding( padding: const EdgeInsets.all(8.0), child: Expanded( child: Text( tag, style: kCardTitle.copyWith( color: kGoldColor, ), textAlign: TextAlign.center, ), ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 24.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ RowItemWidget( name: 'Guest Rate', value: widget.hotelDetails['data']['body'] ['guestReviews']['brands'] ['formattedRating'] .toString()), Container( width: 1.0, height: 50, color: Colors.black26, ), RowItemWidget( name: 'No. of Floors', value: '12'), Container( width: 1.0, height: 50, color: Colors.black26, ), RowItemWidget( name: 'No. of Rooms', value: '199', ), ], ), ), DetailsWidget( data: data['INTERNET'][0].toString() + ' & ' + data['INTERNET'][1].toString(), title: 'Freebies'), DetailsWidget( data: data['HYGIENE'].toString(), title: 'HYGIENE'), DetailsWidget( data: data['PETS'][0].toString() + '\n' + data['PETS'][1].toString(), title: 'Pets'), DetailsWidget( data: data['ROOMS'][0].toString() + '\n' + data['ROOMS'][1].toString() + '\n' + data['ROOMS'][2].toString() + '\n' + data['ROOMS'][3].toString() + '\n' + data['ROOMS'][4].toString(), title: 'Rooms'), DetailsWidget( data: data['CHECKIN_REQUIRED'][0].toString() + '\n' + data['CHECKIN_REQUIRED'][1].toString() + '\n' + data['CHECKIN_REQUIRED'][2].toString(), title: 'Check-In Required'), DetailsWidget( data: data['HOTEL_FEATURE'][0].toString() + '\n' + data['HOTEL_FEATURE'][1].toString() + '\n' + data['HOTEL_FEATURE'][2].toString() + '\n' + data['HOTEL_FEATURE'][3].toString() + '\n' + data['HOTEL_FEATURE'][4].toString() + '\n' + data['HOTEL_FEATURE'][5].toString() + '\n' + data['HOTEL_FEATURE'][6].toString(), title: 'Hotel Features'), ], ), ), ], ), ); }, ) ], ), ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/screens/search_screen.dart
import 'package:booking_app/constants.dart'; import 'package:booking_app/screens/hotels_screen.dart'; import 'package:booking_app/services/networking.dart'; import 'package:booking_app/widgets/complete_search_field.dart'; import 'package:booking_app/widgets/loading_spin.dart'; import 'package:flutter/material.dart'; class WelcomScreen extends StatefulWidget { @override _WelcomScreenState createState() => _WelcomScreenState(); } class _WelcomScreenState extends State<WelcomScreen> { var cityFieldController = TextEditingController(); var checkInController = TextEditingController(); var checkOutController = TextEditingController(); var guestCountController = TextEditingController(); bool searchButtonPressed = false; bool check() { if (cityFieldController.text.isEmpty || checkInController.text.isEmpty || checkOutController.text.isEmpty || guestCountController.text.isEmpty) { return false; } return true; } void getLocation() async { NetworkHelper nh = NetworkHelper(); var loc = await nh.getLocation(cityFieldController.text); var res = await nh .getHotel(loc['suggestions'][0]['entities'][0]['destinationId']); searchButtonPressed = false; Navigator.push(context, MaterialPageRoute(builder: (context) { return LocationScreen( locationPlaces: res, ); })); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, body: Stack( children: <Widget>[ Container( width: double.infinity, height: double.infinity, decoration: new BoxDecoration( image: new DecorationImage( image: new AssetImage("assets/hotel3.jpg"), fit: BoxFit.fill, )), ), Container( height: MediaQuery.of(context).size.height, child: SingleChildScrollView( child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.white.withOpacity(0.7), ), margin: EdgeInsets.fromLTRB(20, 140, 20, 140), padding: EdgeInsets.fromLTRB(0, 20, 0, 20), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Text( 'FIND YOUR HOTEL', style: kCardTitle, textAlign: TextAlign.center, ), SizedBox( height: 10, ), SearchField( title: 'City Name', hintText: 'City, Country, etc..', width: MediaQuery.of(context).size.width, checkInController: cityFieldController, searchButtonPressed: searchButtonPressed, textInputType: TextInputType.name, ), SizedBox( height: 20, ), Row( children: <Widget>[ SearchField( title: 'Check-In', hintText: '10/06/2021', width: MediaQuery.of(context).size.width / 2.55, checkInController: checkInController, searchButtonPressed: searchButtonPressed, textInputType: TextInputType.numberWithOptions(),), SearchField( title: 'Check-Out', hintText: '23/06/2021', width: MediaQuery.of(context).size.width / 2.55, checkInController: checkOutController, searchButtonPressed: searchButtonPressed, textInputType: TextInputType.numberWithOptions(),), ], ), SizedBox( height: 20, ), SearchField( title: 'Number of Guest', hintText: '2 Guests', width: MediaQuery.of(context).size.width, checkInController: guestCountController, searchButtonPressed: searchButtonPressed, textInputType: TextInputType.numberWithOptions(),), SizedBox( height: 30, ), Padding( padding: const EdgeInsets.symmetric(horizontal: 142), child: FloatingActionButton.extended( backgroundColor: Color(0xFFE0B84C), onPressed: () { setState(() { searchButtonPressed = true; }); if (check()) { getLocation(); } }, label: Text( 'Search', style: TextStyle( color: Colors.black54, fontFamily: 'Lobster', fontWeight: FontWeight.bold, fontSize: 18.0), ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(15.0))), ), ), ], ), ), ), ), LoadingSpinWidget( searchButtonPressed: searchButtonPressed && check()), ], ), ); } }
0
mirrored_repositories/Booking-app/lib
mirrored_repositories/Booking-app/lib/screens/hotels_screen.dart
import 'dart:convert'; import 'package:booking_app/screens/details_screen.dart'; import 'package:booking_app/services/networking.dart'; import 'package:booking_app/widgets/app_bar.dart'; import 'package:booking_app/widgets/hotel_card.dart'; import 'package:booking_app/widgets/loading_spin.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class LocationScreen extends StatefulWidget { LocationScreen({@required this.locationPlaces}); final locationPlaces; @override _LocationScreenState createState() => _LocationScreenState(); } class _LocationScreenState extends State<LocationScreen> { var data; Future<void> readJson() async { final String response = await rootBundle.loadString('assets/details_sample.json'); data = await json.decode(response); } // ignore: non_constant_identifier_names bool hotel_pressed = false; @override Widget build(BuildContext context) { readJson(); dynamic ress = widget.locationPlaces['data']['body']['searchResults']['results']; print(ress.toString()); int l = ress.length; return Stack( children: <Widget>[ Scaffold( appBar: PreferredSize( preferredSize: Size(double.infinity, 100), child: AppBarWidget(), ), body: Stack( children: <Widget>[ Container( child: ListView.builder( scrollDirection: Axis.vertical, itemCount: l, itemBuilder: (context, index) { return GestureDetector( onTap: () async { setState(() { hotel_pressed = true; }); NetworkHelper nh = NetworkHelper(); var imgs = await nh.getImages(widget .locationPlaces['data']['body']['searchResults'] ['results'][index]['id'] .toString()); var details = await nh.getDetails(widget .locationPlaces['data']['body']['searchResults'] ['results'][index]['id'] .toString()); setState(() { hotel_pressed = false; }); Navigator.push(context, MaterialPageRoute(builder: (context) { return DetailsPage( hotelImages: imgs, hotelDetails: details, jsnData: data, ); })); }, child: HotelCard( imgUrl: widget.locationPlaces['data']['body'] ['searchResults']['results'][index] ['optimizedThumbUrls']['srpDesktop'], rate: widget.locationPlaces['data']['body'] ['searchResults']['results'][index] ['starRating'], placeName: widget.locationPlaces['data']['body'] ['searchResults']['results'][index]['name'], price: widget.locationPlaces['data']['body'] ['searchResults']['results'][index] ['ratePlan']['price']['current'], ), ); })), ], ), ), LoadingSpinWidget(searchButtonPressed: hotel_pressed), ], ); } }
0
mirrored_repositories/Booking-app
mirrored_repositories/Booking-app/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:booking_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/extract
mirrored_repositories/extract/lib/extract_method_channel.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'extract_platform_interface.dart'; /// An implementation of [ExtractPlatform] that uses method channels. class MethodChannelExtract extends ExtractPlatform { /// The method channel used to interact with the native platform. @visibleForTesting final methodChannel = const MethodChannel('extract'); @override Future<String?> getPlatformVersion() async { final version = await methodChannel.invokeMethod<String>('getPlatformVersion'); return version; } }
0
mirrored_repositories/extract
mirrored_repositories/extract/lib/extract.dart
import 'extract_platform_interface.dart'; class Extract { Future<String?> getPlatformVersion() { return ExtractPlatform.instance.getPlatformVersion(); } /// Extracts phone numbers from the provided [text]. /// /// This function uses a regular expression to identify and extract phone numbers /// from the input [text]. /// /// Example: /// ```dart /// String text = 'Contact us at +1234567890 for assistance.'; /// List<String> extractedPhoneNumbers = Extract.phoneNumbers(text); /// ``` /// /// The [text] parameter represents the text in which phone numbers are to be identified /// and extracted. /// /// Returns a [List<String>] containing the identified phone numbers extracted from the input [text]. /// /// Note: /// - The regular expression pattern used captures phone numbers consisting of digits and hyphens, /// allowing variations in phone number formats. /// - It may capture phone numbers that include country codes (e.g., '+1' for the United States) /// followed by the number digits and optional spaces or hyphens. /// /// Considerations: /// - Validate the extracted phone numbers based on specific formatting or country code requirements. /// - This method doesn't verify the existence or correctness of the identified phone numbers; it solely extracts patterns matching the defined regular expression. static List<String> phoneNumbers(String text) { RegExp phoneRegex = RegExp(r'(\+?\d{1,2}\s?)?[\d-]{8,}'); Iterable<Match> matches = phoneRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts URLs from the provided [text]. /// /// This function uses a regular expression to identify and extract URLs /// from the input [text]. /// /// Example: /// ```dart /// String text = 'Check out https://example.com for more information.'; /// List<String> extractedURLs = Extract.urls(text); /// ``` /// /// The [text] parameter represents the text in which URLs are to be identified /// and extracted. /// /// Returns a [List<String>] containing the identified URLs extracted from the input [text]. /// /// Note: /// - This method uses a regular expression pattern to capture URLs adhering to common formats /// (e.g., 'http://', 'https://'). /// - It might not cover all URL patterns and specialized cases. /// /// Considerations: /// - Validate the URL extraction based on specific use cases if specialized URL formats are involved. /// - The method doesn't perform validation for the existence or accessibility of the URLs. static List<String> urls(String text) { RegExp urlRegex = RegExp(r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+'); Iterable<Match> matches = urlRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts dates in various formats from the provided [text]. /// /// This function identifies and extracts dates in different formats, such as: /// - DD/MM/YYYY or DD-MM-YYYY /// - MM/DD/YYYY or MM-DD-YYYY /// - Day Mon YYYY or Mon Day, YYYY /// - YYYY-MM-DD or YYYY/MM/DD /// - DD Mon YY or Mon DD, YY /// - DD.MM.YYYY /// - DD Mon YYYY /// - Mon DD, YYYY /// - Mon DD, YY /// - DD-Mon-YY or DD Mon YY /// - DD Mon YYYY /// - Mon DD YYYY /// - Mon-DD-YYYY /// /// The [text] parameter represents the text from which dates are to be identified and extracted. /// /// Returns a [List<String>] containing the identified dates in various formats extracted from the input [text]. /// /// Note: /// - The function uses a predefined list of regular expressions for various date formats. /// - It collects dates matching the defined patterns, potentially capturing a wide range of date representations. /// /// Considerations: /// - Validate the extracted dates based on specific formatting or context requirements. /// - This method doesn't verify the correctness of the identified dates; it solely extracts patterns matching the defined regular expressions. static List<String> allDates(String text) { List<String> dateFormats = [ r'\b\d{1,2}/\d{1,2}/\d{2,4}\b', // 12/31/2023 r'\b\d{1,2}-\d{1,2}-\d{2,4}\b', // 12-31-2023 r'\b\d{1,2}\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2,4}\b', // 31 Dec 2023 r'\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{1,2},?\s\d{2,4}\b', // Dec 31, 2023 r'\b\d{4}[-/]\d{1,2}[-/]\d{1,2}\b', // 2023-12-31 or 2023/12/31 r'\b\d{1,2}\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\b', // 31 Dec 2023 r'\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{1,2},?\s\d{4}\b', // Dec 31, 2023 r'\b\d{1,2}/\d{1,2}/\d{2}\b', // 12/31/23 r'\b\d{1,2}-\d{1,2}-\d{2}\b', // 12-31-23 r'\b\d{1,2}\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2}\b', // 31 Dec 23 r'\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{1,2},?\s\d{2}\b', // Dec 31, 23 r'\b\d{4}[-/]\d{1,2}[-/]\d{2}\b', // 2023-12-31 or 2023/12/31 r'\b\d{1,2}\.\d{1,2}\.\d{2,4}\b', // 12.31.2023 r'\b\d{1,2}\s(?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d{2,4}\b', // 31 December 2023 r'\b(?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d{1,2},?\s\d{2,4}\b', // December 31, 2023 r'\b\d{1,2}\s(?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d{4}\b', // 31 December 2023 r'\b(?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d{1,2},?\s\d{4}\b', // December 31, 2023 r'\b\d{1,2}-\w{3}-\d{2}\b', // 31-Dec-23 r'\b\d{1,2}\s\w{3}\s\d{2,4}\b', // 31 Dec 2023 r'\b\w{3}\s\d{1,2},?\s\d{2,4}\b', // Dec 31, 2023 r'\b\d{1,2}-\w{3}-\d{4}\b', // 31-Dec-2023 ]; List<String> extractedDates = []; for (String format in dateFormats) { RegExp dateRegex = RegExp(format); Iterable<Match> matches = dateRegex.allMatches(text); extractedDates.addAll(matches.map((match) => match.group(0)!).toList()); } return extractedDates; } /// Extracts occurrences of a specific [word] from the provided [text]. /// /// This function identifies and extracts occurrences of the specified [word] in the input [text]. /// /// The [text] parameter represents the text in which occurrences of [word] are to be identified and extracted. /// The [word] parameter represents the specific word to search for in the input [text]. /// /// Returns a [List<String>] containing instances of the specified [word] extracted from the input [text]. /// /// Note: /// - The function uses a regular expression pattern to identify the [word] in the [text]. /// - It collects instances where the [word] appears as a standalone word, ignoring case sensitivity. static List<String> specificWords(String text, String word) { RegExp wordRegex = RegExp(r'\b' + word + r'\b', caseSensitive: false); Iterable<Match> matches = wordRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts addresses from the provided [text]. /// /// This function identifies and extracts addresses from the input [text]. /// Addresses are expected to follow the format: [Street Address, City, State ZIPCode]. /// /// The [text] parameter represents the text in which addresses are to be identified and extracted. /// /// Returns a [List<String>] containing identified addresses extracted from the input [text]. /// /// Note: /// - The function uses a regular expression pattern to capture address structures adhering to a predefined format. /// - It aims to extract addresses following a specific pattern and might not cover all possible address variations. static List<String> addresses(String text) { RegExp addressRegex = RegExp( r'\d{1,5}\s\w+\s\w+,\s?\w+,\s\w+\s\d{5}|\d{1,5}\s\w+\s\w+\s\w+,\s\w+,\s\w+\s\d{5}'); Iterable<Match> matches = addressRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts numeric values from the provided [text]. /// /// This function identifies and extracts numeric values from the input [text]. /// /// The [text] parameter represents the text in which numeric values are to be identified and extracted. /// The optional parameter [includeDecimals] indicates whether to include decimal numbers. /// /// If [includeDecimals] is set to `true`, the function captures both integers and decimal numbers. /// If set to `false` (default), the function captures only integers. /// /// Returns a [List<String>] containing identified numeric values extracted from the input [text]. /// /// Note: /// - When [includeDecimals] is `true`, the function captures numbers with or without decimal points. /// - When [includeDecimals] is `false`, the function captures only whole numbers (integers). /// - The function utilizes regular expressions to extract numeric patterns from the text. static List<String> numericValues(String text, {bool includeDecimals = false}) { RegExp numericRegex = includeDecimals ? RegExp(r'\b\d+(\.\d+)?\b') : RegExp(r'\b\d+\b'); Iterable<Match> matches = numericRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts hashtags and, optionally, mentions from the provided [text]. /// /// This function identifies and extracts hashtags and, if specified, mentions from the input [text]. /// /// The [text] parameter represents the text in which hashtags and/or mentions are to be identified and extracted. /// The optional parameter [includeMentions] determines whether mentions (starting with '@') should be included. /// /// If [includeMentions] is set to `true` (default), the function captures both hashtags (starting with '#') /// and mentions. /// If set to `false`, the function captures only hashtags. /// /// Returns a [List<String>] containing identified hashtags and, optionally, mentions extracted from the input [text]. /// /// Note: /// - When [includeMentions] is `true`, the function captures both hashtags and mentions. /// - When [includeMentions] is `false`, the function captures only hashtags. /// - The function uses regular expressions to extract hashtags and mentions based on predefined patterns. static List<String> hashtagsMentions(String text, {bool includeMentions = true}) { RegExp tagRegex = includeMentions ? RegExp(r'#[^\s#]+|\B@\w+') : RegExp(r'#[^\s#]+'); Iterable<Match> matches = tagRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts file paths from the provided [text]. /// /// This function identifies and extracts file paths from the input [text]. /// /// The [text] parameter represents the text in which file paths are to be identified and extracted. /// The optional parameter [separator] specifies the path separator character. /// /// The default [separator] value is '/' (forward slash), commonly used in Unix-based systems. /// /// Returns a [List<String>] containing identified file paths extracted from the input [text]. /// /// Note: /// - The function uses a regular expression pattern to capture file path structures based on the provided [separator]. /// - It aims to extract file paths that conform to the defined structure and separator. static List<String> filePaths(String text, {String separator = '/'}) { RegExp filePathRegex = RegExp('(?:$separator[\\w-]+)+$separator?'); Iterable<Match> matches = filePathRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts special characters from the provided [text]. /// /// This function identifies and extracts special characters from the input [text]. /// /// The [text] parameter represents the text in which special characters are to be identified and extracted. /// The optional parameter [characterSet] specifies the set of characters to extract. /// /// The default [characterSet] is '[^\w\s]', capturing any character that's not alphanumeric or whitespace. /// /// Returns a [List<String>] containing identified special characters extracted from the input [text]. /// /// Note: /// - The function utilizes a regular expression pattern to capture characters based on the provided [characterSet]. /// - It collects characters that match the specified set. static List<String> specialCharacters(String text, {String characterSet = r'[^\w\s]'}) { RegExp specialCharRegex = RegExp(characterSet); Iterable<Match> matches = specialCharRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts occurrences of a specific [keyword] or phrase from the provided [text]. /// /// This function identifies and extracts occurrences of the specified [keyword] or phrase in the input [text]. /// /// The [text] parameter represents the text in which occurrences of [keyword] or phrase are to be identified and extracted. /// The [keyword] parameter represents the specific word or phrase to search for in the input [text]. /// The optional parameter [caseSensitive] determines whether the search is case-sensitive. /// /// If [caseSensitive] is set to `true`, the function matches the [keyword] or phrase exactly. /// If set to `false` (default), the function captures occurrences regardless of case. /// /// Returns a [List<String>] containing instances of the specified [keyword] or phrase extracted from the input [text]. /// /// Note: /// - The function uses a regular expression pattern to identify the [keyword] or phrase in the [text]. /// - It collects instances where the [keyword] or phrase appears as a standalone word, considering case sensitivity if specified. static List<String> keywordsPhrases(String text, String keyword, {bool caseSensitive = false}) { RegExp keywordRegex = RegExp(r'\b' + keyword + r'\b', caseSensitive: caseSensitive); Iterable<Match> matches = keywordRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Separates text into sentences or paragraphs based on the provided [separator]. /// /// This function segments the input [text] into sentences or paragraphs using the specified [separator]. /// /// The [text] parameter represents the text to be segmented into sentences or paragraphs. /// The optional parameter [separator] determines the character that signifies the end of a sentence or paragraph. /// /// By default, [separator] is set to '.' (period) for sentence segmentation. /// /// Returns a [List<String>] containing individual sentences or paragraphs extracted from the input [text]. /// /// Note: /// - The function utilizes a regular expression to split the text based on the provided [separator]. /// - It separates the text into sentences or paragraphs based on the occurrence of the [separator] character. static List<String> sentencesParagraphs(String text, {String separator = '.'}) { RegExp sentenceRegex = RegExp('.+?(?=$separator)'); Iterable<Match> matches = sentenceRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts acronyms and abbreviations from the provided [text]. /// /// This function identifies and extracts acronyms and abbreviations from the input [text]. /// /// The [text] parameter represents the text in which acronyms and abbreviations are to be identified and extracted. /// /// Returns a [List<String>] containing identified acronyms and abbreviations extracted from the input [text]. /// /// Note: /// - The function captures strings of capital letters (2 or more) as potential acronyms or abbreviations. /// - It identifies strings where all characters are uppercase letters as potential acronyms or abbreviations. static List<String> acronymsAbbreviations(String text) { RegExp acronymRegex = RegExp(r'\b[A-Z]{2,}\b'); Iterable<Match> matches = acronymRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts Social Security Numbers (SSNs) from the provided [text]. /// /// This function identifies and extracts Social Security Numbers (SSNs) from the input [text]. /// /// The [text] parameter represents the text in which SSNs are to be identified and extracted. /// /// Returns a [List<String>] containing identified Social Security Numbers (SSNs) extracted from the input [text]. /// /// Note: /// - The function captures strings matching the format: 123-45-6789 as potential SSNs. static List<String> ssns(String text) { RegExp ssnRegex = RegExp(r'\b\d{3}-\d{2}-\d{4}\b'); Iterable<Match> matches = ssnRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts IP addresses from the provided [text]. /// /// This function identifies and extracts IP addresses from the input [text]. /// /// The [text] parameter represents the text in which IP addresses are to be identified and extracted. /// /// Returns a [List<String>] containing identified IP addresses extracted from the input [text]. /// /// Note: /// - The function captures strings matching the format: 192.168.1.1 as potential IP addresses. static List<String> iPAddresses(String text) { RegExp ipRegex = RegExp(r'\b(?:\d{1,3}\.){3}\d{1,3}\b'); Iterable<Match> matches = ipRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts potential credit card numbers from the provided [text]. /// /// This function identifies and extracts potential credit card numbers from the input [text]. /// /// The [text] parameter represents the text in which credit card numbers are to be identified and extracted. /// /// Returns a [List<String>] containing potential credit card numbers extracted from the input [text]. /// /// Note: /// - The function captures sequences of digits possibly separated by spaces or hyphens, ranging from 13 to 16 digits. static List<String> creditCardNumbers(String text) { RegExp creditCardRegex = RegExp(r'\b(?:\d[ -]*?){13,16}\b'); Iterable<Match> matches = creditCardRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts code snippets from the provided [text] optionally filtered by [language]. /// /// This function identifies and extracts code snippets from the input [text]. /// Optionally, specifying a [language] parameter filters snippets written in a particular programming language. /// /// The [text] parameter represents the text containing code snippets to be extracted. /// The optional [language] parameter filters code snippets in the specified programming language. /// /// Returns a [List<String>] containing identified code snippets from the input [text]. /// /// Note: /// - The function utilizes triple backticks (`) as delimiters for code blocks. /// - Optionally specifying the [language] parameter filters code snippets written in a specific programming language. static List<String> codeSnippets(String text, {String language = ''}) { RegExp codeRegex = RegExp(r'```(?:$language\n)?([\s\S]+?)```'); Iterable<Match> matches = codeRegex.allMatches(text); return matches.map((match) => match.group(1)!).toList(); } /// Extracts units of measurement from the provided [text]. /// /// This function identifies and extracts units of measurement from the input [text]. /// /// The [text] parameter represents the text containing units of measurement to be extracted. /// /// Returns a [List<String>] containing identified units of measurement extracted from the input [text]. /// /// Note: /// - The function captures sequences of digits followed by a space and alphanumeric characters representing units. static List<String> unitsOfMeasurement(String text) { RegExp unitRegex = RegExp(r'\b\d+\s?\w+\b'); Iterable<Match> matches = unitRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts product codes or IDs from the provided [text]. /// /// This function identifies and extracts product codes or IDs from the input [text]. /// /// The [text] parameter represents the text containing product codes or IDs to be extracted. /// /// Returns a [List<String>] containing identified product codes or IDs extracted from the input [text]. /// /// Note: /// - The function captures alphanumeric strings of 6 or more characters typically used as product codes or IDs. static List<String> productCodesIDs(String text) { RegExp productCodeRegex = RegExp(r'\b[A-Z0-9]{6,}\b'); Iterable<Match> matches = productCodeRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts sentiment-related keywords from the provided [text]. /// /// This function identifies and extracts keywords related to sentiment (e.g., good, bad, excellent, poor, great) from the input [text]. /// /// The [text] parameter represents the text in which sentiment keywords are to be identified and extracted. /// /// Returns a [List<String>] containing sentiment-related keywords extracted from the input [text]. /// /// Note: /// - The function is case insensitive while capturing sentiment-related keywords. static List<String> sentimentKeywords(String text) { RegExp sentimentRegex = RegExp(r'\b(?:good|bad|excellent|poor|great)\b', caseSensitive: false); Iterable<Match> matches = sentimentRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts time patterns from the provided [text]. /// /// This function identifies and extracts time patterns in 24-hour format (HH:MM) or with optional seconds (HH:MM:SS) from the input [text]. /// /// The [text] parameter represents the text in which time patterns are to be identified and extracted. /// /// Returns a [List<String>] containing time patterns extracted from the input [text]. /// /// Note: /// - The function captures time patterns adhering to the 24-hour clock format. static List<String> time(String text) { RegExp timeRegex = RegExp(r'\b(?:[01]\d|2[0-3]):(?:[0-5]\d)(?::(?:[0-5]\d))?\b'); Iterable<Match> matches = timeRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts potential company names from the provided [text]. /// /// This function identifies and extracts potential company names from the input [text]. /// /// The [text] parameter represents the text in which company names are to be identified and extracted. /// /// Returns a [List<String>] containing potential company names extracted from the input [text]. /// /// Note: /// - The function captures strings that represent potential company name formats. static List<String> companyNames(String text) { RegExp companyRegex = RegExp(r'\b[A-Z][a-z]+(?:\s[A-Z][a-z]+)*\b'); Iterable<Match> matches = companyRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts potential job titles from the provided [text]. /// /// This function identifies and extracts potential job titles from the input [text]. /// /// The [text] parameter represents the text in which job titles are to be identified and extracted. /// /// Returns a [List<String>] containing potential job titles extracted from the input [text]. /// /// Note: /// - The function captures strings that represent potential job title formats. static List<String> jobTitles(String text) { RegExp jobTitleRegex = RegExp(r'\b(?:[A-Z][a-z]*\s?)+\b'); Iterable<Match> matches = jobTitleRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts Vehicle Identification Numbers (VINs) from the provided [text]. /// /// This function identifies and extracts VINs, which are alphanumeric strings of 17 characters, from the input [text]. /// /// The [text] parameter represents the text in which VINs are to be identified and extracted. /// /// Returns a [List<String>] containing identified VINs extracted from the input [text]. /// /// Note: /// - The function captures alphanumeric strings of 17 characters, adhering to the VIN format. static List<String> vins(String text) { RegExp vinRegex = RegExp(r'\b[A-HJ-NPR-Z0-9]{17}\b'); Iterable<Match> matches = vinRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts Twitter handles from the provided [text]. /// /// This function identifies and extracts Twitter handles (e.g., @username) from the input [text]. /// /// The [text] parameter represents the text in which Twitter handles are to be identified and extracted. /// /// Returns a [List<String>] containing identified Twitter handles extracted from the input [text]. /// /// Note: /// - The function captures strings starting with '@' followed by letters, numbers, or underscores. static List<String> twitterHandles(String text) { RegExp twitterRegex = RegExp(r'@[A-Za-z0-9_]+'); Iterable<Match> matches = twitterRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts YouTube video IDs from the provided [text]. /// /// This function identifies and extracts YouTube video IDs from the input [text]. /// /// The [text] parameter represents the text in which YouTube video IDs are to be identified and extracted. /// /// Returns a [List<String>] containing identified YouTube video IDs extracted from the input [text]. /// /// Note: /// - The function captures 11-character alphanumeric strings typically found in YouTube URLs. static List<String> youTubeVideoIDs(String text) { RegExp youtubeRegex = RegExp(r'(?<=youtu\.be\/|watch\?v=)[A-Za-z0-9_-]{11}'); Iterable<Match> matches = youtubeRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts ISBNs (International Standard Book Numbers) from the provided [text]. /// /// This function identifies and extracts ISBNs from the input [text]. /// /// The [text] parameter represents the text in which ISBNs are to be identified and extracted. /// /// Returns a [List<String>] containing identified ISBNs extracted from the input [text]. /// /// Note: /// - The function captures ISBNs with different formats, including ISBN-10 and ISBN-13. static List<String> isbns(String text) { RegExp isbnRegex = RegExp( r'\b(?:ISBN(?:-1[03])?:?\s*)?(?=[-0-9X ]{10,17}$|97[89][-0-9X ]{10}$|(?=(?:[-0-9X ]+){13}$|(?=(?:[-0-9X ]+){17}$) 97[89][-0-9X ]{13})[-0-9X]{1,5}[- ](?:[0-9]+[- ]){2}[0-9X]\b)'); Iterable<Match> matches = isbnRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts HTML tags and their attributes from the provided [text]. /// /// This function identifies and extracts HTML tags and their attributes from the input [text]. /// /// The [text] parameter represents the text in which HTML tags and attributes are to be identified and extracted. /// /// Returns a [List<String>] containing identified HTML tags and their attributes extracted from the input [text]. /// /// Note: /// - The function captures HTML tags and their associated attributes. static List<String> htmlTagsAttributes(String text) { RegExp htmlRegex = RegExp(r'<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\/\1>'); Iterable<Match> matches = htmlRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts hexadecimal color codes from the provided [text]. /// /// This function identifies and extracts hexadecimal color codes from the input [text]. /// /// The [text] parameter represents the text in which hexadecimal color codes are to be identified and extracted. /// /// Returns a [List<String>] containing identified hexadecimal color codes extracted from the input [text]. /// /// Note: /// - The function captures 6-character hexadecimal strings typically representing colors (e.g., #RRGGBB). static List<String> hexColorCodes(String text) { RegExp hexColorRegex = RegExp(r'#[0-9a-fA-F]{6}\b'); Iterable<Match> matches = hexColorRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts statistical terms (e.g., mean, median, mode, range) from the provided [text]. /// /// This function identifies and extracts statistical terms from the input [text]. /// /// The [text] parameter represents the text in which statistical terms are to be identified and extracted. /// /// Returns a [List<String>] containing identified statistical terms extracted from the input [text]. /// /// Note: /// - The function captures statistical terms like mean, median, mode, and range. static List<String> statisticalData(String text) { RegExp statisticsRegex = RegExp(r'\b(mean|median|mode|range)\b'); Iterable<Match> matches = statisticsRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts Twitter or Facebook post IDs based on the provided [text] and [platform]. /// /// This function identifies and extracts post IDs from either Twitter or Facebook URLs, /// based on the specified [platform]. /// /// The [text] parameter represents the text in which post IDs are to be identified and extracted. /// The [platform] parameter specifies the social media platform ('Twitter' or 'Facebook'). /// /// Returns a [List<String>] containing identified post IDs extracted from the input [text]. /// /// Note: /// - For Twitter, the function captures numeric IDs following 'twitter.com/username/status/' in URLs. /// - For Facebook, the function captures numeric IDs following 'facebook.com/username/posts/' in URLs. static List<String> twiiterAndFacebookPostIDs(String text, String platform) { String regexPattern = platform == 'Twitter' ? r'(?<=twitter\.com\/\w+\/status\/)\d+' : r'(?<=facebook\.com\/\w+\/posts\/)\d+'; RegExp socialMediaRegex = RegExp(regexPattern); Iterable<Match> matches = socialMediaRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts employee IDs from the provided [text]. /// /// This function identifies and extracts employee IDs from the input [text]. /// /// The [text] parameter represents the text in which employee IDs are to be identified and extracted. /// /// Returns a [List<String>] containing identified employee IDs extracted from the input [text]. /// /// Note: /// - The function captures alphanumeric strings with a minimum length of 5 characters. static List<String> employeeIDs(String text) { RegExp employeeIDRegex = RegExp(r'\b[A-Za-z0-9]{5,}\b'); Iterable<Match> matches = employeeIDRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts bank account numbers from the provided [text]. /// /// This function identifies and extracts bank account numbers from the input [text]. /// /// The [text] parameter represents the text in which bank account numbers are to be identified and extracted. /// /// Returns a [List<String>] containing identified bank account numbers extracted from the input [text]. /// /// Note: /// - The function captures numeric strings with a length ranging from 9 to 12 digits. static List<String> bankAccountNumbers(String text) { RegExp bankAccountRegex = RegExp(r'\b\d{9,12}\b'); Iterable<Match> matches = bankAccountRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts API endpoints from the provided [text]. /// /// This function identifies and extracts API endpoints from the input [text]. /// /// The [text] parameter represents the text in which API endpoints are to be identified and extracted. /// /// Returns a [List<String>] containing identified API endpoints extracted from the input [text]. /// /// Note: /// - The function captures strings representing API endpoint paths. static List<String> apiEndpoints(String text) { RegExp apiEndpointRegex = RegExp(r'\/[a-zA-Z0-9\/\-\_]+'); Iterable<Match> matches = apiEndpointRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts OS file paths from the provided [text]. /// /// This function identifies and extracts OS file paths from the input [text]. /// /// The [text] parameter represents the text in which OS file paths are to be identified and extracted. /// /// Returns a [List<String>] containing identified OS file paths extracted from the input [text]. /// /// Note: /// - The function captures strings representing file paths specific to the operating system. static List<String> osPaths(String text) { RegExp osPathRegex = RegExp(r'([A-Za-z]):(\\[A-Za-z0-9_\-\.]+)+'); Iterable<Match> matches = osPathRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts Twitter or Facebook post IDs from the provided [text] based on the [platform]. /// /// This function extracts post IDs from Twitter or Facebook URLs /// depending on the specified [platform] ('Twitter' or 'Facebook') in the [text]. /// /// The [text] parameter represents the text containing URLs of Twitter or Facebook posts. /// The [platform] parameter specifies the social media platform ('Twitter' or 'Facebook'). /// /// Returns a [List<String>] containing post IDs extracted from the input [text]. /// /// Note: /// - For Twitter, the function captures numeric IDs following 'twitter.com/username/status/' in URLs. /// - For Facebook, the function captures numeric IDs following 'facebook.com/username/posts/' in URLs. static List<String> twitterAndFacebookPostContent( String text, String platform) { String regexPattern = platform == 'Twitter' ? r'(?<=twitter\.com\/\w+\/status\/)\d+' : r'(?<=facebook\.com\/\w+\/posts\/)\d+'; RegExp socialMediaRegex = RegExp(regexPattern); Iterable<Match> matches = socialMediaRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts software version numbers from the provided [text]. /// /// This function identifies and extracts software version numbers from the input [text]. /// /// The [text] parameter represents the text containing software version numbers. /// /// Returns a [List<String>] containing identified software version numbers from the input [text]. /// /// Note: /// - The function captures version numbers in the format x.y.z where 'x', 'y', 'z' are digits. static List<String> softwareVersionNumbers(String text) { RegExp softwareVersionRegex = RegExp(r'\b\d+(\.\d+)+\b'); Iterable<Match> matches = softwareVersionRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts ordinal numbers (e.g., first, second, third) from the provided [text]. /// /// This function identifies and extracts ordinal numbers from the input [text]. /// /// The [text] parameter represents the text containing ordinal numbers. /// /// Returns a [List<String>] containing identified ordinal numbers from the input [text]. static List<String> ordinalNumbers(String text) { RegExp ordinalNumberRegex = RegExp( r'\b(first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth)\b', caseSensitive: false); Iterable<Match> matches = ordinalNumberRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts meta tags from HTML content in the provided [text]. /// /// This function identifies and extracts meta tags from HTML text. /// /// The [text] parameter represents the text containing HTML meta tags. /// /// Returns a [List<String>] containing identified meta tags from the input [text]. static List<String> metaTags(String text) { RegExp metaTagsRegex = RegExp(r'<meta [^>]*>'); Iterable<Match> matches = metaTagsRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts stock ticker symbols from the provided [text]. /// /// This function identifies and extracts stock ticker symbols from the input [text]. /// /// The [text] parameter represents the text containing stock ticker symbols. /// /// Returns a [List<String>] containing identified stock ticker symbols from the input [text]. /// /// Note: /// - The function captures uppercase alphabetic strings of 2 to 5 characters. static List<String> stockTickerSymbols(String text) { RegExp tickerSymbolRegex = RegExp(r'\b[A-Z]{2,5}\b'); Iterable<Match> matches = tickerSymbolRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts hash values from the provided [text]. /// /// This function identifies and extracts hash values (MD5, SHA-1, SHA-256) from the input [text]. /// /// The [text] parameter represents the text containing hash values. /// /// Returns a [List<String>] containing identified hash values from the input [text]. /// /// Note: /// - Hash values are captured in formats: 32, 40, or 64 characters long hexadecimal strings. static List<String> hashValues(String text) { RegExp hashValueRegex = RegExp(r'\b[A-Fa-f0-9]{32}\b|\b[A-Fa-f0-9]{40}\b|\b[A-Fa-f0-9]{64}\b'); Iterable<Match> matches = hashValueRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts chemical compound names from the provided [text]. /// /// This function identifies and extracts chemical compound names from the input [text]. /// /// The [text] parameter represents the text containing chemical compound names. /// /// Returns a [List<String>] containing identified chemical compound names from the input [text]. /// /// Note: /// - The function captures compound names starting with an uppercase letter followed by lowercase letters. static List<String> chemicalCompoundNames(String text) { RegExp compoundNameRegex = RegExp(r'\b[A-Z][a-z]+\b'); Iterable<Match> matches = compoundNameRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts MIME types from the provided [text]. /// /// This function identifies and extracts MIME types from the input [text]. /// /// The [text] parameter represents the text containing MIME types. /// /// Returns a [List<String>] containing identified MIME types from the input [text]. /// /// Note: /// - MIME types are captured in the format 'type/subtype'. static List<String> mimeTypes(String text) { RegExp mimeTypeRegex = RegExp(r'\b[a-zA-Z\-]+\/[a-zA-Z\-]+\b'); Iterable<Match> matches = mimeTypeRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts HTTP status codes from the provided [text]. /// /// This function identifies and extracts HTTP status codes from the input [text]. /// /// The [text] parameter represents the text containing HTTP status codes. /// /// Returns a [List<String>] containing identified HTTP status codes from the input [text]. /// /// Note: /// - Status codes are captured as 3-digit numeric values. static List<String> httpStatusCodes(String text) { RegExp httpStatusCodeRegex = RegExp(r'\b\d{3}\b'); Iterable<Match> matches = httpStatusCodeRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts coordinates from the provided [text]. /// /// This function identifies and extracts geographical coordinates from the input [text]. /// /// The [text] parameter represents the text containing coordinates. /// /// Returns a [List<String>] containing identified coordinates from the input [text]. /// /// Note: /// - Coordinates are captured in various formats like degrees (°) with optional N/S/E/W indicators. static List<String> coordinates(String text) { RegExp coordinateRegex = RegExp( r'\b-?\d+(\.\d+)?\s*[°º]\s*[NS]?\b|\b-?\d+(\.\d+)?\s*[°º]\s*[WE]?\b'); Iterable<Match> matches = coordinateRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } /// Extracts programming keywords from the provided [text] based on the specified [language]. /// /// This function identifies and extracts programming keywords from the input [text]. /// /// The [text] parameter represents the text containing programming keywords. /// The [language] parameter specifies the programming language ('Dart' or others). /// /// Returns a [List<String>] containing identified programming keywords from the input [text]. /// /// Note: /// - The function captures keywords specific to the provided programming language in a case-insensitive manner. static List<String> extractProgrammingKeywords(String text, String language) { String keywordList = language == 'Dart' ? 'abstract|dynamic|implements|show|as|else|import|static|assert|enum|in|super|async|export|interface|switch|await|external|is|sync|break|extends|library|this|case|factory|mixin|throw|catch|false|new|true|class|final|null|try|const|finally|operator|typedef|continue|for|part|var|covariant|Function|rethrow|void|default|get|required|while|deferred|hide|return|with|do|if' : ''; RegExp keywordRegex = RegExp(r'\b(?:' + keywordList + r')\b', caseSensitive: false); Iterable<Match> matches = keywordRegex.allMatches(text); return matches.map((match) => match.group(0)!).toList(); } }
0
mirrored_repositories/extract
mirrored_repositories/extract/lib/extract_web.dart
// In order to *not* need this ignore, consider extracting the "web" version // of your plugin as a separate package, instead of inlining it in the same // package as the core of your plugin. // ignore: avoid_web_libraries_in_flutter import 'dart:html' as html show window; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'extract_platform_interface.dart'; /// A web implementation of the ExtractPlatform of the Extract plugin. class ExtractWeb extends ExtractPlatform { /// Constructs a ExtractWeb ExtractWeb(); static void registerWith(Registrar registrar) { ExtractPlatform.instance = ExtractWeb(); } /// Returns a [String] containing the version of the platform. @override Future<String?> getPlatformVersion() async { final version = html.window.navigator.userAgent; return version; } }
0
mirrored_repositories/extract
mirrored_repositories/extract/lib/extract_platform_interface.dart
import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'extract_method_channel.dart'; abstract class ExtractPlatform extends PlatformInterface { /// Constructs a ExtractPlatform. ExtractPlatform() : super(token: _token); static final Object _token = Object(); static ExtractPlatform _instance = MethodChannelExtract(); /// The default instance of [ExtractPlatform] to use. /// /// Defaults to [MethodChannelExtract]. static ExtractPlatform get instance => _instance; /// Platform-specific implementations should set this with their own /// platform-specific class that extends [ExtractPlatform] when /// they register themselves. static set instance(ExtractPlatform instance) { PlatformInterface.verifyToken(instance, _token); _instance = instance; } Future<String?> getPlatformVersion() { throw UnimplementedError('platformVersion() has not been implemented.'); } }
0
mirrored_repositories/extract
mirrored_repositories/extract/test/extract_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:extract/extract.dart'; import 'package:extract/extract_platform_interface.dart'; import 'package:extract/extract_method_channel.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; class MockExtractPlatform with MockPlatformInterfaceMixin implements ExtractPlatform { @override Future<String?> getPlatformVersion() => Future.value('42'); } void main() { final ExtractPlatform initialPlatform = ExtractPlatform.instance; test('$MethodChannelExtract is the default instance', () { expect(initialPlatform, isInstanceOf<MethodChannelExtract>()); }); test('getPlatformVersion', () async { Extract extractPlugin = Extract(); MockExtractPlatform fakePlatform = MockExtractPlatform(); ExtractPlatform.instance = fakePlatform; expect(await extractPlugin.getPlatformVersion(), '42'); }); }
0
mirrored_repositories/extract
mirrored_repositories/extract/test/extract_method_channel_test.dart
import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:extract/extract_method_channel.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); MethodChannelExtract platform = MethodChannelExtract(); const MethodChannel channel = MethodChannel('extract'); setUp(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( channel, (MethodCall methodCall) async { return '42'; }, ); }); tearDown(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(channel, null); }); test('getPlatformVersion', () async { expect(await platform.getPlatformVersion(), '42'); }); }
0
mirrored_repositories/extract/example
mirrored_repositories/extract/example/lib/main.dart
import 'package:flutter/material.dart'; import 'dart:async'; import 'package:flutter/services.dart'; import 'package:extract/extract.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { String _platformVersion = 'Unknown'; final _extractPlugin = Extract(); @override void initState() { super.initState(); initPlatformState(); } // Platform messages are asynchronous, so we initialize in an async method. Future<void> initPlatformState() async { String platformVersion; // Platform messages may fail, so we use a try/catch PlatformException. // We also handle the message potentially returning null. try { platformVersion = await _extractPlugin.getPlatformVersion() ?? 'Unknown platform version'; } on PlatformException { platformVersion = 'Failed to get platform version.'; } // If the widget was removed from the tree while the asynchronous platform // message was in flight, we want to discard the reply rather than calling // setState to update our non-existent appearance. if (!mounted) return; setState(() { _platformVersion = platformVersion; }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Plugin example app'), ), body: Center( child: Text('Running on: $_platformVersion\n'), ), ), ); } }
0
mirrored_repositories/extract/example
mirrored_repositories/extract/example/integration_test/plugin_integration_test.dart
// This is a basic Flutter integration test. // // Since integration tests run in a full Flutter application, they can interact // with the host side of a plugin implementation, unlike Dart unit tests. // // For more information about Flutter integration tests, please see // https://docs.flutter.dev/cookbook/testing/integration/introduction import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:extract/extract.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('getPlatformVersion test', (WidgetTester tester) async { final Extract plugin = Extract(); final String? version = await plugin.getPlatformVersion(); // The version string depends on the host platform running the test, so // just assert that some non-empty string is returned. expect(version?.isNotEmpty, true); }); }
0
mirrored_repositories/extract/example
mirrored_repositories/extract/example/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:extract_example/main.dart'; void main() { testWidgets('Verify Platform version', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that platform version is retrieved. expect( find.byWidgetPredicate( (Widget widget) => widget is Text && widget.data!.startsWith('Running on:'), ), findsOneWidget, ); }); }
0
mirrored_repositories/Smart_home
mirrored_repositories/Smart_home/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:smart_home/router/router_config.dart'; void main() { runApp(const MainApp()); } class MainApp extends StatelessWidget { const MainApp({super.key}); @override Widget build(BuildContext context) { return ScreenUtilInit( designSize: const Size(360, 690), minTextAdapt: true, splitScreenMode: true, child: MaterialApp.router( debugShowCheckedModeBanner: false, routeInformationParser: router.routeInformationParser, routeInformationProvider: router.routeInformationProvider, routerDelegate: router.routerDelegate, theme: ThemeData.light(useMaterial3: true), darkTheme: ThemeData.dark(useMaterial3: true), themeMode: ThemeMode.system, ), ); } }
0
mirrored_repositories/Smart_home/lib/features
mirrored_repositories/Smart_home/lib/features/datails/datails_screen.dart
// ignore_for_file: public_member_api_docs, sort_constructors_first import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:iconsax/iconsax.dart'; import 'package:sleek_circular_slider/sleek_circular_slider.dart'; import 'package:smart_home/common/common_color.dart'; import 'package:smart_home/features/datails/model/model.dart'; import 'package:smart_home/features/datails/widgets/animation.dart'; import 'package:smart_home/features/datails/widgets/bounce_animation.dart'; import 'package:smart_home/features/datails/widgets/custom_cards.dart'; import 'package:smart_home/features/datails/widgets/custom_paint.dart'; import 'package:smart_home/features/datails/widgets/fade_animation.dart'; class DetailsScreen extends StatefulWidget { const DetailsScreen({ Key? key, required this.model, }) : super(key: key); final CustompageModel model; @override State<DetailsScreen> createState() => _DetailsScreenState(); } class _DetailsScreenState extends State<DetailsScreen> { bool flag = false; Mode selectedMode = Mode.cold; @override Widget build(BuildContext context) { return Scaffold( body: CustomPaint( painter: MasterPainter1(), size: Size(MediaQuery.sizeOf(context).width, MediaQuery.sizeOf(context).height), child: Column( children: [ const SizedBox( height: 60, ), Padding( padding: const EdgeInsets.only(right: 12, left: 10), child: BounceFromBottomAnimation( delay: 2, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( onPressed: () { // GoRouter.of(context).push(Routes.homescreen.path); context.pop(); }, icon: const Icon( Icons.arrow_back_ios, size: 30, )), Text( // "Air Conditioner", widget.model.detail_name, style: GoogleFonts.rubik( fontSize: 22, fontWeight: FontWeight.bold), ), RotateFadeAnimation( delay: 2, child: IconButton( onPressed: () {}, icon: const Icon(Iconsax.setting)), ), ], ), ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "Working Space", style: GoogleFonts.rubik( fontSize: 12, letterSpacing: 1, color: Colors.grey, fontWeight: FontWeight.w400), ), IconButton( onPressed: () {}, icon: const Icon( Iconsax.arrow_down_1, color: Colors.grey, size: 16, )) ], ), const SizedBox( height: 80, ), Stack( children: [ SleekCircularSlider( initialValue: widget.model.value, appearance: CircularSliderAppearance( size: 320, customColors: CustomSliderColors(progressBarColors: [ const Color(0xFF9C7B86), const Color(0xFF4A86FC), const Color(0xFF4795EE), const Color(0xFFF4B0AA) ]), animationEnabled: true, angleRange: 240, spinnerDuration: Duration.microsecondsPerSecond, animDurationMultiplier: 2, customWidths: CustomSliderWidths( progressBarWidth: 8, handlerSize: 20, shadowWidth: 8, trackWidth: 8)), onChange: (double val) { setState(() { widget.model.value = val; }); }), Padding( padding: const EdgeInsets.only(top: 23, left: 20), child: Container( height: 280, width: 280, decoration: BoxDecoration( shape: BoxShape.circle, color: maincolor, ), child: Center( child: Column( children: [ const SizedBox( height: 100, ), Text( "${widget.model.value.toStringAsFixed(0)} ${widget.model.detail_value}", style: GoogleFonts.rubik( fontSize: 50, fontWeight: FontWeight.w600), ), const SizedBox( height: 20, ), Text( widget.model.detail_value1, style: GoogleFonts.roboto( letterSpacing: 1, fontSize: 14, fontWeight: FontWeight.w600, color: Colors.grey), ), Text( widget.model.detail_value3, style: GoogleFonts.roboto( fontSize: 14, letterSpacing: 1, fontWeight: FontWeight.w600, color: Colors.grey), ), ], )), ), ), ], ), const SizedBox( height: 30, ), BounceFromBottomAnimation( delay: 2, child: Text( widget.model.detail_mode, style: GoogleFonts.roboto( fontSize: 14, letterSpacing: 1, color: Colors.grey, fontWeight: FontWeight.w400), ), ), const SizedBox( height: 10, ), Text( widget.model.detail_modename, style: GoogleFonts.rubik( fontSize: 20, letterSpacing: 1, color: Colors.white, fontWeight: FontWeight.bold), ), const SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ScaleFadeBounceAnimation( delay: 0.5, child: GestureDetector( onTap: () { setState(() { selectedMode = Mode.cold; }); }, child: CustomCardView( selectedMode: selectedMode == Mode.cold, model: widget.model.model1, ), ), ), ScaleFadeBounceAnimation( delay: 1.5, child: GestureDetector( onTap: () { setState(() { selectedMode = Mode.fan; }); }, child: CustomCardView( selectedMode: selectedMode == Mode.fan, model: widget.model.model2, ), ), ), ScaleFadeBounceAnimation( delay: 2.5, child: GestureDetector( onTap: () { setState(() { selectedMode = Mode.dry; }); }, child: CustomCardView( selectedMode: selectedMode == Mode.dry, model: widget.model.model3, ), ), ), ], ), const SizedBox( height: 20, ), RotateFadeAnimation( delay: 2, child: GestureDetector( onTap: () { setState(() { widget.model.value = 0; flag = true; }); Timer(Duration(milliseconds: 300), () { setState(() { flag = false; }); }); }, child: AnimatedContainer( duration: Duration(milliseconds: 500), height: flag ? 60 : 70, width: flag ? 60 : 70, decoration: const BoxDecoration( shape: BoxShape.circle, gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Colors.blue, Colors.tealAccent]), ), child: Icon( CupertinoIcons.power, size: flag ? 30 : 35, ), ), ), ), ], ), ), ); } } enum Mode { cold, fan, dry, }
0
mirrored_repositories/Smart_home/lib/features/datails
mirrored_repositories/Smart_home/lib/features/datails/widgets/custom_paint.dart
import 'package:flutter/material.dart'; class MasterPainter1 extends CustomPainter { @override void paint(Canvas canvas, Size size) { Paint paint = Paint(); paint.strokeWidth = 2; paint.color = const Color.fromARGB(255, 134, 172, 230); paint.maskFilter = const MaskFilter.blur(BlurStyle.normal, 72); canvas.drawCircle(Offset(size.width / 2, size.height / 2 - 80), 140, paint); canvas.drawCircle(Offset(size.width / 2, size.height - 60), 100, paint); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return false; } }
0
mirrored_repositories/Smart_home/lib/features/datails
mirrored_repositories/Smart_home/lib/features/datails/widgets/animation.dart
import 'package:flutter/material.dart'; class BounceFromBottomAnimation extends StatefulWidget { const BounceFromBottomAnimation( {Key? key, required this.child, required this.delay}); final Widget child; final double delay; @override _BounceFromBottomAnimationState createState() => _BounceFromBottomAnimationState(); } class _BounceFromBottomAnimationState extends State<BounceFromBottomAnimation> with TickerProviderStateMixin { late AnimationController controller; late Animation<double> animation; @override void initState() { super.initState(); controller = AnimationController( duration: Duration(milliseconds: (500 * widget.delay).round()), vsync: this, ); final Animation<double> curve = CurvedAnimation(parent: controller, curve: Curves.elasticOut); animation = Tween<double>(begin: 100.0, end: 0.0).animate(curve) ..addListener(() { setState(() {}); }); controller.forward(); } @override Widget build(BuildContext context) { return Transform.translate( offset: Offset(0, animation.value), child: widget.child, ); } @override void dispose() { controller.dispose(); super.dispose(); } }
0
mirrored_repositories/Smart_home/lib/features/datails
mirrored_repositories/Smart_home/lib/features/datails/widgets/custom_cards.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:smart_home/common/common_color.dart'; import 'package:smart_home/features/datails/model/model.dart'; class CustomCardView extends StatefulWidget { const CustomCardView({ super.key, required this.model, required this.selectedMode, }); final CustomModel model; final bool selectedMode; // final Function(bool value) onpress; @override State<CustomCardView> createState() => _CustomCardViewState(); } class _CustomCardViewState extends State<CustomCardView> { // onpress() { // setState(() { // if (widget.flag == false) { // setState(() { // widget.flag = true; // }); // } else if (widget.flag == true) { // setState(() { // widget.flag = false; // }); // } // }); // } @override Widget build(BuildContext context) { return AnimatedContainer( duration: const Duration(milliseconds: 300), height: 150, width: 120, decoration: BoxDecoration( color: maincolor, gradient: widget.selectedMode ? const LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Colors.blue, Colors.tealAccent]) : null, borderRadius: BorderRadius.circular(20), ), child: Center( child: Column( children: [ const SizedBox( height: 20, ), Container( height: 60, width: 60, decoration: BoxDecoration( color: Colors.transparent.withOpacity(0.3), shape: BoxShape.circle), child: Icon( widget.model.icon, size: 30, ), ), const SizedBox( height: 20, ), FittedBox( child: Padding( padding: const EdgeInsets.all(8.0), child: Text( widget.model.value, style: GoogleFonts.rubik( letterSpacing: 1, fontSize: 18, fontWeight: FontWeight.w500, color: widget.selectedMode ? Colors.black : Colors.white), ), ), ), ], ), ), ); } }
0
mirrored_repositories/Smart_home/lib/features/datails
mirrored_repositories/Smart_home/lib/features/datails/widgets/fade_animation.dart
import 'package:flutter/material.dart'; class RotateFadeAnimation extends StatefulWidget { const RotateFadeAnimation({Key? key, required this.child, required this.delay}); final Widget child; final double delay; @override _RotateFadeAnimationState createState() => _RotateFadeAnimationState(); } class _RotateFadeAnimationState extends State<RotateFadeAnimation> with TickerProviderStateMixin { late AnimationController controller; late Animation<double> animation; late Animation<double> rotateAnimation; @override void initState() { super.initState(); controller = AnimationController( duration: Duration(milliseconds: (800 * widget.delay).round()), vsync: this, ); animation = Tween<double>(begin: 0, end: 1).animate( CurvedAnimation( parent: controller, curve: Curves.easeInOut, ), )..addListener(() { setState(() {}); }); rotateAnimation = Tween<double>(begin: 0, end: 2 * 3.14).animate( CurvedAnimation( parent: controller, curve: Curves.easeInOut, ), )..addListener(() { setState(() {}); }); controller.forward(); } @override Widget build(BuildContext context) { return Transform.rotate( angle: rotateAnimation.value, child: Opacity( opacity: animation.value, child: widget.child, ), ); } @override void dispose() { controller.dispose(); super.dispose(); } }
0
mirrored_repositories/Smart_home/lib/features/datails
mirrored_repositories/Smart_home/lib/features/datails/widgets/bounce_animation.dart
import 'package:flutter/material.dart'; class ScaleFadeBounceAnimation extends StatefulWidget { const ScaleFadeBounceAnimation({Key? key, required this.child, required this.delay}); final Widget child; final double delay; @override _ScaleFadeBounceAnimationState createState() => _ScaleFadeBounceAnimationState(); } class _ScaleFadeBounceAnimationState extends State<ScaleFadeBounceAnimation> with TickerProviderStateMixin { late AnimationController controller; late Animation<double> scaleAnimation; late Animation<double> fadeAnimation; @override void initState() { super.initState(); controller = AnimationController( duration: Duration(milliseconds: (800 * widget.delay).round()), vsync: this, ); scaleAnimation = Tween<double>(begin: 0.5, end: 1.0).animate( CurvedAnimation( parent: controller, curve: Curves.fastOutSlowIn, ), ); fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate( CurvedAnimation( parent: controller, curve: const Interval(0.5, 1.0, curve: Curves.easeInOut), ), ); controller.forward(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: controller, builder: (context, child) { return Transform.scale( scale: scaleAnimation.value, child: Opacity( opacity: fadeAnimation.value, child: child, ), ); }, child: widget.child, ); } @override void dispose() { controller.dispose(); super.dispose(); } }
0
mirrored_repositories/Smart_home/lib/features/datails
mirrored_repositories/Smart_home/lib/features/datails/model/model.dart
// ignore_for_file: public_member_api_docs, sort_constructors_first, non_constant_identifier_names import 'package:flutter/cupertino.dart'; class CustomModel { IconData icon; String value; bool flag; CustomModel({ required this.icon, required this.value, required this.flag, }); } class CustompageModel { final String detail_name; final String detail_value; final String detail_value1; final String detail_value3; final String detail_mode; final String detail_modename; final CustomModel model1; final CustomModel model2; final CustomModel model3; double value; CustompageModel( { required this.detail_name, required this.detail_value, required this.detail_value1, required this.detail_value3, required this.detail_mode, required this.detail_modename, required this.model1, required this.model2, required this.model3, required this.value, }); }
0
mirrored_repositories/Smart_home/lib/features
mirrored_repositories/Smart_home/lib/features/navigation/navigation.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:iconsax/iconsax.dart'; import 'package:smart_home/common/common_color.dart'; import 'package:smart_home/features/graph/graph_screen.dart'; import 'package:smart_home/features/home/homescreen.dart'; class Navigation extends StatefulWidget { const Navigation({super.key}); @override State<Navigation> createState() => _NavigationState(); } class _NavigationState extends State<Navigation> { int selectedIndex = 0; List<IconData> icondata = [ Iconsax.home, Iconsax.graph, Icons.switch_access_shortcut_add_rounded, Iconsax.setting, ]; List<Widget> pages = [ const HomeScreenView(), GraphScreen(), const Center( child: Text("Center"), ), const Center( child: Text("Center"), ), ]; @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: SizedBox( height: 80, width: 80, child: FloatingActionButton( materialTapTargetSize: MaterialTapTargetSize.padded, autofocus: true, splashColor: Colors.lightBlueAccent, hoverColor: Colors.blue, backgroundColor: Colors.lightBlue, shape: const CircleBorder(side: BorderSide(color: Colors.teal)), onPressed: () {}, child: const Icon( Iconsax.microphone, size: 45, color: Colors.white, )), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, floatingActionButtonAnimator: FloatingActionButtonAnimator.scaling, bottomNavigationBar: Material( child: Container( height: 100, decoration: const BoxDecoration(color: Color(0xFF282636)), child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: icondata.length, padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10), itemBuilder: (context, index) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 33, vertical: 10), child: GestureDetector( onTap: () { setState(() { selectedIndex = index; }); }, child: SizedBox( width: index == 0 ? 40 : index == 3 ? 35 : 30, height: 30, child: Icon( icondata[index], color: index == selectedIndex ? Colors.white : Colors.grey, ), ), ), ); }, ), ), ), body: pages[selectedIndex], ); } }
0
mirrored_repositories/Smart_home/lib/features
mirrored_repositories/Smart_home/lib/features/home/homescreen.dart
// ignore_for_file: non_constant_identifier_names import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:iconsax/iconsax.dart'; import 'package:smart_home/features/datails/widgets/animation.dart'; import 'package:smart_home/features/home/controller/controller.dart'; import 'package:smart_home/features/home/widgets/add_device.dart'; import 'package:smart_home/features/home/widgets/custom_card.dart'; import 'package:smart_home/features/home/widgets/electricity_card.dart'; import 'package:smart_home/features/home/widgets/scale_fadeanimation.dart'; import 'package:smart_home/features/home/widgets/master_painter.dart'; import 'widgets/topbar.dart'; import 'package:smart_home/router/router.dart'; class HomeScreenView extends StatefulWidget { const HomeScreenView({super.key}); @override State<HomeScreenView> createState() => _HomeScreenViewState(); } class _HomeScreenViewState extends State<HomeScreenView> { var model_list = Controller().model_list; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: const Color(0xFF1B1D30), body: CustomPaint( painter: MasterPainter(), child: BounceFromBottomAnimation( delay: 10, child: Column( children: [ const SizedBox( height: 60, ), BounceFromBottomAnimation(delay: 6, child: topbar()), BounceFromBottomAnimation(delay: 6, child: addDevice()), const SizedBox( height: 20, ), BounceFromBottomAnimation(delay: 4, child: electricitycard()), const SizedBox( height: 10, ), BounceFromBottomAnimation( delay: 2, child: Padding( padding: const EdgeInsets.all(12.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( "Linked to you ", style: GoogleFonts.roboto( fontSize: 16, fontWeight: FontWeight.bold), ), CupertinoButton( alignment: Alignment.center, borderRadius: BorderRadius.circular(15), padding: const EdgeInsets.only(left: 10, right: 10), minSize: 20, child: Row( children: [ Text( "See all ", style: GoogleFonts.roboto( fontSize: 14, color: Colors.grey), ), const Icon( Iconsax.arrow_right_1, color: Colors.grey, size: 18, ) ], ), onPressed: () {}) ], ), ), ), const SizedBox( height: 10, ), SizedBox( height: 420, width: 420, child: GridView.builder( padding: EdgeInsets.zero, physics: const NeverScrollableScrollPhysics(), itemCount: Controller().model_list.length, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2), itemBuilder: (context, index) { var data = Controller().model_list[index]; return ScaleFadeAnimation( delay: 2.5, child: Padding( padding: const EdgeInsets.all(5.0), child: GestureDetector( onTap: () { // context.go(Routes.detailsscreen.path); GoRouter.of(context).push( Routes.detailsscreen.path, extra: data.model); }, child: CustomCardView(model: data)), ), ); }, ), ), ], ), ), ), ); } }
0
mirrored_repositories/Smart_home/lib/features/home
mirrored_repositories/Smart_home/lib/features/home/widgets/topbar.dart
import 'package:flutter/material.dart'; import 'package:iconsax/iconsax.dart'; import 'package:smart_home/features/datails/widgets/fade_animation.dart'; Widget topbar() { return Padding( padding: const EdgeInsets.all(12.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const RotateFadeAnimation( delay: 2, child: Icon( Iconsax.menu, size: 30, ), ), Container( height: 55, width: 55, decoration: const BoxDecoration( shape: BoxShape.circle, gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ Colors.teal, Colors.purple, ])), clipBehavior: Clip.antiAlias, child: const Padding( padding: EdgeInsets.all(2.0), child: CircleAvatar( backgroundImage: AssetImage("assets/images/girl.webp"), )), ), ], ), ); }
0
mirrored_repositories/Smart_home/lib/features/home
mirrored_repositories/Smart_home/lib/features/home/widgets/animation.dart
import 'package:flutter/material.dart'; class BounceFromBottomAnimation extends StatefulWidget { const BounceFromBottomAnimation({Key? key, required this.child, required this.delay}); final Widget child; final double delay; @override _BounceFromBottomAnimationState createState() => _BounceFromBottomAnimationState(); } class _BounceFromBottomAnimationState extends State<BounceFromBottomAnimation> with TickerProviderStateMixin { late AnimationController controller; late Animation<double> animation; @override void initState() { super.initState(); controller = AnimationController( duration: Duration(milliseconds: (1500 * widget.delay).round()), // Adjust the duration vsync: this, ); final Animation<double> curve = CurvedAnimation(parent: controller, curve: Curves.easeInOutQuint); // Use a smoother curve animation = Tween<double>(begin: 100.0, end: 0.0).animate(curve) // Adjust the end value for less bounce ..addListener(() { setState(() {}); }); controller.forward(); } @override Widget build(BuildContext context) { return Transform.translate( offset: Offset(0, animation.value), child: widget.child, ); } @override void dispose() { controller.dispose(); super.dispose(); } }
0
mirrored_repositories/Smart_home/lib/features/home
mirrored_repositories/Smart_home/lib/features/home/widgets/scale_fadeanimation.dart
// ignore_for_file: use_key_in_widget_constructors import 'package:flutter/material.dart'; class ScaleFadeAnimation extends StatefulWidget { const ScaleFadeAnimation({Key? key, required this.child, required this.delay}); final Widget child; final double delay; @override // ignore: library_private_types_in_public_api _ScaleFadeAnimationState createState() => _ScaleFadeAnimationState(); } class _ScaleFadeAnimationState extends State<ScaleFadeAnimation> with TickerProviderStateMixin { late AnimationController controller; late Animation<double> animation; late Animation<double> scaleAnimation; @override void initState() { super.initState(); controller = AnimationController( duration: Duration(milliseconds: (500 * widget.delay).round()), vsync: this, ); animation = Tween<double>(begin: 0, end: 1).animate( CurvedAnimation( parent: controller, curve: Curves.easeInOut, ), )..addListener(() { setState(() {}); }); scaleAnimation = Tween<double>(begin: 0.5, end: 1).animate( CurvedAnimation( parent: controller, curve: Curves.easeInOut, ), )..addListener(() { setState(() {}); }); controller.forward(); } @override Widget build(BuildContext context) { return Transform.scale( scale: scaleAnimation.value, child: Opacity( opacity: animation.value, child: widget.child, ), ); } @override void dispose() { controller.dispose(); super.dispose(); } }
0
mirrored_repositories/Smart_home/lib/features/home
mirrored_repositories/Smart_home/lib/features/home/widgets/custom_card.dart
// ignore_for_file: public_member_api_docs, sort_constructors_first, must_be_immutable import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:smart_home/common/common_color.dart'; import 'package:smart_home/features/datails/widgets/fade_animation.dart'; import 'package:smart_home/features/home/model/model.dart'; class CustomCardView extends StatefulWidget { Model model; bool flag = false; CustomCardView({Key? key, required this.model}) : super(key: key); @override State<CustomCardView> createState() => _CustomCardViewState(); } class _CustomCardViewState extends State<CustomCardView> { onpress(bool value) { setState(() { widget.flag = value; }); } @override Widget build(BuildContext context) { return AnimatedContainer( duration: const Duration(milliseconds: 300), height: 200, width: 200, decoration: BoxDecoration( color: maincolor, borderRadius: BorderRadius.circular(20), gradient: widget.flag ? const LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Colors.blue, Colors.tealAccent]) : null, ), child: Padding( padding: const EdgeInsets.only(top: 10, left: 20, right: 20, bottom: 0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ widget.flag ? RotateFadeAnimation( delay: 2, child: Container( height: 50, width: 50, decoration: BoxDecoration( shape: BoxShape.circle, color: widget.flag ? Colors.white : const Color(0xFF1E1B29)), child: Icon( widget.model.icon, size: 28, color: widget.flag ? Colors.black : Colors.white, ), ), ) : Container( height: 50, width: 50, decoration: BoxDecoration( shape: BoxShape.circle, color: widget.flag ? Colors.white : const Color(0xFF1E1B29)), child: Icon( widget.model.icon, size: 28, color: widget.flag ? Colors.black : Colors.white, ), ), Column( children: [ Text( "${widget.model.model.value.toStringAsFixed(0)} ${widget.model.value}", style: GoogleFonts.rubik( fontSize: 26, fontWeight: FontWeight.bold), ), Text( widget.model.desc, style: GoogleFonts.rubik( fontSize: 10, fontWeight: FontWeight.w400, letterSpacing: 1, color: widget.flag ? Colors.white : Colors.grey.shade400), ) ], ) ], ), const SizedBox( height: 40, ), Text( widget.model.title1, style: GoogleFonts.roboto( fontSize: 12, fontWeight: FontWeight.w300, letterSpacing: 1, color: widget.flag ? Colors.grey.shade800 : Colors.grey.shade400), ), Text( widget.model.title2, style: GoogleFonts.roboto( fontSize: 18, fontWeight: FontWeight.bold, color: widget.flag ? Colors.black : Colors.white), ), const SizedBox( height: 5, ), CupertinoSwitch( activeColor: const Color(0xFF1B1D30), value: widget.flag, onChanged: (value) { onpress(value); }, ), ], ), ), ); } }
0
mirrored_repositories/Smart_home/lib/features/home
mirrored_repositories/Smart_home/lib/features/home/widgets/add_device.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:iconsax/iconsax.dart'; Widget addDevice() { return Padding( padding: const EdgeInsets.all(12.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Hello Hoe Rang 👋", style: GoogleFonts.rubik(fontSize: 25, fontWeight: FontWeight.bold), ), Text( "Welcome back at home", style: GoogleFonts.rubik( fontSize: 15, color: Colors.grey.shade400, ), ), ], ), CupertinoButton( alignment: Alignment.center, borderRadius: BorderRadius.circular(15), padding: const EdgeInsets.only(left: 20, right: 20), minSize: 50, color: const Color(0xFF282636), child: Row( children: [ Text( "Add Device ", style: GoogleFonts.rubik(fontSize: 20, color: Colors.grey), ), const Icon( Iconsax.add_circle, color: Colors.grey, size: 25, ) ], ), onPressed: () {}) ], ), ); }
0
mirrored_repositories/Smart_home/lib/features/home
mirrored_repositories/Smart_home/lib/features/home/widgets/rotation_animaiton.dart
// ignore_for_file: use_key_in_widget_constructors import 'package:flutter/material.dart'; class RotateFadeAnimation extends StatefulWidget { const RotateFadeAnimation({Key? key, required this.child, required this.delay}); final Widget child; final double delay; @override _RotateFadeAnimationState createState() => _RotateFadeAnimationState(); } class _RotateFadeAnimationState extends State<RotateFadeAnimation> with TickerProviderStateMixin { late AnimationController controller; late Animation<double> animation; late Animation<double> rotateAnimation; @override void initState() { super.initState(); controller = AnimationController( duration: Duration(milliseconds: (800 * widget.delay).round()), vsync: this, ); animation = Tween<double>(begin: 0, end: 1).animate( CurvedAnimation( parent: controller, curve: Curves.easeInOut, ), )..addListener(() { setState(() {}); }); rotateAnimation = Tween<double>(begin: 0, end: 2 * 3.14).animate( CurvedAnimation( parent: controller, curve: Curves.easeInOut, ), )..addListener(() { setState(() {}); }); controller.forward(); } @override Widget build(BuildContext context) { return Transform.rotate( angle: rotateAnimation.value, child: Opacity( opacity: animation.value, child: widget.child, ), ); } @override void dispose() { controller.dispose(); super.dispose(); } }
0
mirrored_repositories/Smart_home/lib/features/home
mirrored_repositories/Smart_home/lib/features/home/widgets/electricity_card.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:iconsax/iconsax.dart'; import 'package:smart_home/common/common_color.dart'; Widget electricitycard() { return Container( height: 100, width: 400, decoration: BoxDecoration( color: maincolor, borderRadius: BorderRadius.circular(20), ), child: Row(crossAxisAlignment: CrossAxisAlignment.center, children: [ const SizedBox( width: 10, ), Container( height: 50, width: 50, clipBehavior: Clip.antiAlias, decoration: const BoxDecoration( shape: BoxShape.circle, gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Color(0xFF457BFE), Color(0xFF71CDFB)])), child: const Icon( Icons.electric_bolt_rounded, size: 30, ), ), const SizedBox( width: 20, ), Padding( padding: const EdgeInsets.only(top: 23), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "63.2 kWh", style: GoogleFonts.roboto(fontSize: 20, fontWeight: FontWeight.bold), ), Text( "Electricity usage this month", style: GoogleFonts.roboto( fontSize: 12, color: Colors.grey.shade400, ), ) ], ), ), const Spacer(), CupertinoButton( alignment: Alignment.center, borderRadius: BorderRadius.circular(15), padding: const EdgeInsets.only(left: 20, right: 20), minSize: 50, color: const Color(0xFF1E1B29), child: const Icon( Iconsax.arrow_right_1, color: Colors.grey, size: 25, ), onPressed: () {}), const SizedBox( width: 10, ), ]), ); }
0
mirrored_repositories/Smart_home/lib/features/home
mirrored_repositories/Smart_home/lib/features/home/widgets/master_painter.dart
import 'package:flutter/material.dart'; class MasterPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { Paint paint = Paint(); paint.strokeWidth = 2; paint.color = const Color.fromARGB(255, 134, 172, 230); paint.maskFilter = const MaskFilter.blur(BlurStyle.normal, 92); canvas.drawCircle(Offset(size.width / 2, 30), 150, paint); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return false; } }
0
mirrored_repositories/Smart_home/lib/features/home
mirrored_repositories/Smart_home/lib/features/home/model/model.dart
// ignore_for_file: public_member_api_docs, sort_constructors_first import 'package:flutter/material.dart'; import 'package:smart_home/features/datails/model/model.dart'; class Model { final IconData icon; final String value; final String desc; final String title1; final String title2; final bool flag; final CustompageModel model; Model( {required this.icon, required this.value, required this.desc, required this.title1, required this.title2, required this.flag, required this.model}); }
0
mirrored_repositories/Smart_home/lib/features/home
mirrored_repositories/Smart_home/lib/features/home/controller/controller.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:iconsax/iconsax.dart'; import 'package:smart_home/features/datails/model/model.dart'; import 'package:smart_home/features/home/model/model.dart'; class Controller { // ignore: non_constant_identifier_names List<Model> model_list = [ Model( icon: Icons.air_rounded, value: "°C", desc: '', title1: "Working space", title2: "Air Conditioner", flag: false, model: CustompageModel( detail_name: "Air Condititioner", detail_value: "°C", detail_value1: "Room", detail_value3: "Temperature", detail_mode: "Mode", detail_modename: "POWER FULL", model1: CustomModel(icon: Icons.coronavirus, value: "COLD", flag: true), model2: CustomModel(icon: Icons.air, value: "FAN", flag: false), model3: CustomModel( icon: Icons.water_drop_outlined, value: "DRY", flag: false), value: 24)), Model( icon: CupertinoIcons.speaker_2, value: "%", desc: 'Volume', title2: "Google Next", title1: "Working space", flag: false, model: CustompageModel( detail_name: "Google Next", detail_value: "%", detail_value1: "", detail_value3: "Volume", detail_mode: "Mode", detail_modename: "Balance", model1: CustomModel(icon: Icons.speaker, value: "Volume", flag: false), model2: CustomModel( icon: Icons.surround_sound, value: "SURROUND", flag: false), model3: CustomModel( icon: Icons.auto_awesome, value: "Auto", flag: true), value: 60)), Model( icon: CupertinoIcons.light_max, value: "%", desc: 'Percentage', title1: "Working space", title2: "Desk Lamp", flag: false, model: CustompageModel( detail_name: "Desk Lamp", detail_value: "%", detail_value1: "", detail_value3: "Brightness", detail_mode: "Mode", detail_modename: "Manual", model1: CustomModel( icon: Icons.offline_bolt, value: "Off", flag: false), model2: CustomModel(icon: Icons.wifi, value: "Wifi", flag: true), model3: CustomModel( icon: Icons.auto_awesome, value: "Auto", flag: false), value: 70)), Model( icon: Iconsax.airdrop, value: "", desc: 'Users', title1: "Living Room", title2: "Mi Router 5 ", flag: false, model: CustompageModel( detail_name: "Mi Router 5", detail_value: "", detail_value1: "User", detail_value3: "Connected", detail_mode: "Maximun", detail_modename: "100", model1: CustomModel(icon: Iconsax.wifi5, value: "Wifi", flag: true), model2: CustomModel(icon: Icons.swipe, value: "Off", flag: false), model3: CustomModel( icon: Icons.connect_without_contact, value: "Auto", flag: false), value: 5)), ]; }
0
mirrored_repositories/Smart_home/lib/features
mirrored_repositories/Smart_home/lib/features/graph/graph_screen.dart
import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:smart_home/features/datails/widgets/custom_paint.dart'; import 'package:smart_home/features/home/controller/controller.dart'; import 'package:smart_home/features/home/widgets/custom_card.dart'; import 'package:smart_home/features/home/widgets/scale_fadeanimation.dart'; import 'package:smart_home/router/router.dart'; class GraphScreen extends StatefulWidget { const GraphScreen({super.key}); @override State<GraphScreen> createState() => _GraphScreenState(); } class _GraphScreenState extends State<GraphScreen> { @override Widget build(BuildContext context) { return Scaffold( body: CustomPaint( painter: MasterPainter1(), child: Padding( padding: const EdgeInsets.all(12.0), child: SingleChildScrollView( child: Column( children: [ const SizedBox( height: 70, ), SizedBox( height: 420, width: 420, child: GridView.builder( padding: EdgeInsets.zero, physics: const NeverScrollableScrollPhysics(), itemCount: Controller().model_list.length, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2), itemBuilder: (context, index) { var data = Controller().model_list[index]; return ScaleFadeAnimation( delay: 2.5, child: Padding( padding: const EdgeInsets.all(5.0), child: GestureDetector( onTap: () { // context.go(Routes.detailsscreen.path); GoRouter.of(context).push( Routes.detailsscreen.path, extra: data.model); }, child: CustomCardView(model: data)), ), ); }, ), ), SizedBox( height: 420, width: 420, child: GridView.builder( padding: EdgeInsets.zero, physics: const NeverScrollableScrollPhysics(), itemCount: Controller().model_list.length, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2), itemBuilder: (context, index) { var data = Controller().model_list[index]; return ScaleFadeAnimation( delay: 2.5, child: Padding( padding: const EdgeInsets.all(5.0), child: GestureDetector( onTap: () { // context.go(Routes.detailsscreen.path); GoRouter.of(context).push( Routes.detailsscreen.path, extra: data.model); }, child: CustomCardView(model: data)), ), ); }, ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/Smart_home/lib
mirrored_repositories/Smart_home/lib/router/router_config.dart
import 'package:flutter/cupertino.dart'; import 'package:go_router/go_router.dart'; import 'package:smart_home/features/datails/datails_screen.dart'; import 'package:smart_home/features/datails/model/model.dart'; import 'package:smart_home/features/home/homescreen.dart'; import 'package:smart_home/features/navigation/navigation.dart'; import 'package:smart_home/router/router.dart'; final router = GoRouter(routes: [ GoRoute( path: Routes.navigaiton.path, name: Routes.navigaiton.name, pageBuilder: (context, state) { return const CupertinoPage(child: Navigation()); }, ), GoRoute( path: Routes.detailsscreen.path, name: Routes.detailsscreen.name, pageBuilder: (context, state) { return CupertinoPage(child: DetailsScreen(model: state.extra as CustompageModel,)); }, ), GoRoute( path: Routes.homescreen.path, name: Routes.homescreen.name, pageBuilder: (context, state) { return const CupertinoPage(child: HomeScreenView()); }, ), ]);
0
mirrored_repositories/Smart_home/lib
mirrored_repositories/Smart_home/lib/router/router.dart
class AppRouter { String name; String path; AppRouter({ required this.name, required this.path, }); } class Routes { static AppRouter navigaiton = AppRouter(name: "/", path: '/'); static AppRouter homescreen = AppRouter(name: "/home", path: '/home'); static AppRouter detailsscreen = AppRouter(name: "/details", path: "/details"); }
0
mirrored_repositories/Smart_home/lib
mirrored_repositories/Smart_home/lib/common/common_color.dart
import 'package:flutter/material.dart'; Color maincolor = const Color(0xFF282636);
0
mirrored_repositories/Smart_home
mirrored_repositories/Smart_home/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:smart_home/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MainApp()); // 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/mobile_lab1
mirrored_repositories/mobile_lab1/Part_1/named_parameters.dart
void main() { test_param(123); test_param(123,s1:'hello'); test_param(123,s2:'hello',s1:'world'); } test_param(n1,{s1,s2}) { print(n1); print(s1); }
0
mirrored_repositories/mobile_lab1
mirrored_repositories/mobile_lab1/Part_1/getters_setters.dart
void main() { var s = SampleClass(15); print(s.datavalue); s.datavalue = 10; print(s.x); } class SampleClass { num x; SampleClass(this.x); //Getter which provides read access to the properties of an object num get datavalue => x*2; //Setter which provides write access to the properties of an object set datavalue(num value) => x=value+10; }
0
mirrored_repositories/mobile_lab1
mirrored_repositories/mobile_lab1/Part_1/private_fields.dart
class Star{ Star() { int _private = 16; print('May the Force be with you'); print('This qoute was said ${_private} times'); } } void main() { Star geek = new Star(); }
0
mirrored_repositories/mobile_lab1
mirrored_repositories/mobile_lab1/Part_1/main.dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'My first app', home: Scaffold( appBar: AppBar( title: Text('My first app'), ), body: Center( child: Text('Yelena Skrypnyk'), ), ), ); } }
0
mirrored_repositories/mobile_lab1/Part_1
mirrored_repositories/mobile_lab1/Part_1/constructors/named_constructor.dart
//Named constructor //Creating class named Star class Star{ //Creating named and parameterized constructor with one parameter Star.constructor1(int a) { print('You were supposed to fight evil, not join it'); print('Said Obi-Wan Kenobi in part ${a}'); } //Creating named and parameterized constructor with two parameters Star.constructor2(int a, int b) { print('The greates teacher, failure is'); print('Said master Yoda, who is ${a + b} years old'); } } void main() { //Creating Instance of class Star geek1 = new Star.constructor1(3); Star geek2 = new Star.constructor2(400, 500); }
0
mirrored_repositories/mobile_lab1/Part_1
mirrored_repositories/mobile_lab1/Part_1/constructors/default_constructor.dart
//Default constructor //Creating Class named Star class Star{ //Creating Constructor Star() { print('May the Force be with you'); } } void main() { //Creating Instance of class Star geek = new Star(); }
0
mirrored_repositories/mobile_lab1/Part_1
mirrored_repositories/mobile_lab1/Part_1/constructors/parameterized_constructor.dart
//Parameterized constructor //Creating class named Star class Star{ //Creating Parameterized constructor Star(int a) { print('You can go about your business'); print('Was said in the episode ${a}'); } } void main() { //Creating Instance of class Star geek = new Star(1); }
0
mirrored_repositories/mobile_lab1
mirrored_repositories/mobile_lab1/Part_2/4-2_Initializer_list.dart
import 'dart:math'; class Point { final num x; final num y; final num distanceFromOrigin; Point(x, y) : x = x, y = y, distanceFromOrigin = sqrt(x * x + y * y); } main() { var p = new Point(2, 3); print(p.distanceFromOrigin); }
0
mirrored_repositories/mobile_lab1
mirrored_repositories/mobile_lab1/Part_2/4-1_Factory_constructor.dart
//Factory constructor class Shape { //Type of the shape being created final String type; //Id of this shape for identifying what instance is it final int id; //Library private variable because of _ being used static final Map<String, Shape> _cache = <String, Shape>{}; //Factory constructor factory Shape(String type, {int id}) { //Puts new object in cache or returns existing object that is already stored in cache return _cache.putIfAbsent( type, () => Shape._init( type, id, )); } //Initialize new shape Shape._init(this.type, this.id); //Prints information about current shape void printInfo() { print('shape type is: ${type}, shape id is: ${id}'); } } main(List<String> args) { //Initializing a circle new Shape('circle', id: 2)..printInfo(); //No shape id is specified new Shape('circle')..printInfo(); }
0
mirrored_repositories/mobile_lab1
mirrored_repositories/mobile_lab1/Part_2/2_Lambda_and_closures.dart
//Lambda function int ShowSum(int numOne, int numTwo) => numOne + numTwo; //Closure //Returns a function that adds [addBy] to the function's argument. Function makeAdder(int addBy) { return (int i) => addBy + i; } void main() { // Create a function that adds 2. var add2 = makeAdder(2); // Create a function that adds 4. var add4 = makeAdder(4); assert(add2(3) == 5); assert(add4(3) == 7); print(ShowSum(10, 20)); }
0
mirrored_repositories/mobile_lab1
mirrored_repositories/mobile_lab1/Part_2/6_Assert.dart
//Using assert void main() { String geek = "Star Wars"; //Assert uses boolean condition for testing assert(geek != "Star Wars"); print("You can see Star Wars"); }
0
mirrored_repositories/mobile_lab1
mirrored_repositories/mobile_lab1/Part_2/5_Mixins.dart
mixin Swim { void swim() => print('Swimming'); } mixin Bite { void bite() => print('Chomp'); } mixin Crawl { void crawl() => print('Crawling'); } abstract class Reptile with Swim, Crawl, Bite { void hunt(food) { print('${this.runtimeType} -------'); swim(); crawl(); bite(); print('Eat $food'); } } class Alligator extends Reptile { // Alligator Specific stuff... } class Crocodile extends Reptile { // Crocodile Specific stuff... } class Fish with Swim, Bite { void feed() { print('Fish --------'); swim(); bite(); } } main() { Crocodile().hunt('Zebra'); Alligator().hunt('Fish'); Fish().feed(); }
0
mirrored_repositories/mobile_lab1
mirrored_repositories/mobile_lab1/Part_2/1_Null-aware_operators.dart
String foo = 'a string'; String bar; //Unassigned objects are null by default //Substitute an operator that makes 'a string' be assigned to baz. String baz = foo ?? bar; void main() { // Substitute an operator that makes 'a string' be assigned to bar. bar ??= 'a string'; print(bar); }
0
mirrored_repositories/mobile_lab1
mirrored_repositories/mobile_lab1/Part_2/3_Default_parameter_values.dart
void main() { var result = findVolume(3, 6); print(result); print(""); //Overriding the default parameter var result2 = findVolume(3, 6, height: 15); print(result2); } int findVolume(int length, int breadth, {int height = 12}) { return length * breadth * height; }
0
mirrored_repositories/mobile_lab1
mirrored_repositories/mobile_lab1/Part_2/7_Collections.dart
//List var list = [1, 2, 3]; //Map var fruits = { 'first': 'orange', 'second': 'apple', 'fifth': 'banana', 'sixth': 'pineapple' }; var vegetables = { 1: 'carrot', 2: 'cucumber', 3: 'onion' }; //Set var dishes = {'soup', 'steak', 'sushi', 'pizza', 'burger'}; var cars = <String>{}; void main() { //Show the second element print(list[1]); //Show an element that has a key 'first' in fruits print(fruits['first']); //Show an element that has a key 2 in vegetables print(vegetables[2]); //Show the set dishes print(dishes); //Add an element to an existing set cars.add('bmw'); print(cars); }
0
mirrored_repositories/Flutter.Bird
mirrored_repositories/Flutter.Bird/lib/main.dart
import 'package:flame/flame.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bird/game/game.dart'; void main() async { // initial settings WidgetsFlutterBinding.ensureInitialized(); Flame.audio.disableLog(); SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); SystemChrome.setEnabledSystemUIOverlays([]); var sprite = await Flame.images.loadAll(["sprite.png"]); var screenSize = await Flame.util.initialDimensions(); Singleton.instance.screenSize = screenSize; var flutterBirdGame = FlutterBirdGame(sprite[0], screenSize); runApp(MaterialApp( title: 'FlutterBirdGame', home: GestureDetector( onTapDown: (TapDownDetails evt) => flutterBirdGame.onTap(), child: Scaffold( body: GameWrapper(flutterBirdGame), ), ), )); } class GameWrapper extends StatelessWidget { final FlutterBirdGame flutterBirdGame; GameWrapper(this.flutterBirdGame); @override Widget build(BuildContext context) { return flutterBirdGame.widget; } } class Singleton { Size screenSize; Singleton._privateConstructor(); static final Singleton instance = Singleton._privateConstructor(); }
0
mirrored_repositories/Flutter.Bird/lib
mirrored_repositories/Flutter.Bird/lib/game/bird.dart
import 'dart:ui'; import 'package:flame/animation.dart'; import 'package:flame/components/animation_component.dart'; import 'package:flame/components/component.dart'; import 'package:flame/components/composed_component.dart'; import 'package:flame/flame.dart'; import 'package:flame/sprite.dart'; import 'package:flutter_bird/game/config.dart'; enum BirdStatus { waiting, flying} enum BirdFlyingStatus { up, down, none } class Bird extends PositionComponent with ComposedComponent { int _counter = 0; int _movingUpSteps = 15; Size _screenSize; double _heightDiff = 0.0; double _stepDiff = 0.0; BirdGround ground; BirdStatus status = BirdStatus.waiting; BirdFlyingStatus flyingStatus = BirdFlyingStatus.none; Bird(Image spriteImage, Size screenSize) { _screenSize = screenSize; List<Sprite> sprites = [ Sprite.fromImage( spriteImage, width: SpriteDimensions.birdWidth, height: SpriteDimensions.birdHeight, y: SpritesPostions.birdSprite1Y, x: SpritesPostions.birdSprite1X, ), Sprite.fromImage( spriteImage, width: SpriteDimensions.birdWidth, height: SpriteDimensions.birdHeight, y: SpritesPostions.birdSprite2Y, x: SpritesPostions.birdSprite2X, ), Sprite.fromImage( spriteImage, width: SpriteDimensions.birdWidth, height: SpriteDimensions.birdHeight, y: SpritesPostions.birdSprite3Y, x: SpritesPostions.birdSprite3X, ) ]; var animatedBird = new Animation.spriteList(sprites, stepTime: 0.15); this.ground = BirdGround(animatedBird); this..add(ground); } void setPosition(double x, double y) { this.ground.x = x; this.ground.y = y; } void update(double t) { if (status == BirdStatus.flying) { _counter++; if (_counter <= _movingUpSteps) { flyingStatus = BirdFlyingStatus.up; this.ground.showAnimation = true; this.ground.angle -= 0.01; this.ground.y -= t * 100 * getSpeedRatio(flyingStatus, _counter); } else { flyingStatus = BirdFlyingStatus.down; this.ground.showAnimation = false; if (_heightDiff == 0) _heightDiff = (_screenSize.height - this.ground.y); if (_stepDiff == 0) _stepDiff = this.ground.angle.abs() / (_heightDiff / 10); this.ground.angle += _stepDiff; this.ground.y += t * 100 * getSpeedRatio(flyingStatus, _counter); } this.ground.update(t); } } double getSpeedRatio(BirdFlyingStatus flyingStatus, int counter){ if (flyingStatus == BirdFlyingStatus.up) { var backwardCounter = _movingUpSteps - counter; return backwardCounter / 10.0; } if (flyingStatus == BirdFlyingStatus.down) { var diffCounter = counter - _movingUpSteps; return diffCounter / 10.0; } return 0.0; } void jump() { Flame.audio.play('wing.wav'); status = BirdStatus.flying; _counter = 0; this.ground.angle = 0; } } class BirdGround extends AnimationComponent { bool showAnimation = true; BirdGround(Animation animation) : super(ComponentDimensions.birdWidth, ComponentDimensions.birdHeight, animation); @override void update(double t){ if (showAnimation) { super.update(t); } } }
0
mirrored_repositories/Flutter.Bird/lib
mirrored_repositories/Flutter.Bird/lib/game/bottom.dart
import 'dart:ui'; import 'package:flame/components/component.dart'; import 'package:flame/components/composed_component.dart'; import 'package:flame/components/resizable.dart'; import 'package:flame/sprite.dart'; import 'package:flutter_bird/game/config.dart'; enum BottomStatus { waiting, moving } class Bottom extends PositionComponent with ComposedComponent { BottomGround firstGround; BottomGround secondGround; BottomStatus status = BottomStatus.waiting; Size _screenSize; Rect _rect; Rect get rect => _rect; Bottom(Image spriteImage, Size screenSize) { _screenSize = screenSize; Sprite sprite = Sprite.fromImage( spriteImage, width: SpriteDimensions.bottomWidth, height: SpriteDimensions.bottomHeight, y: SpritesPostions.bottomY, x: SpritesPostions.bottomX, ); this.firstGround = BottomGround(sprite, screenSize); this.secondGround = BottomGround(sprite, screenSize); this..add(firstGround)..add(secondGround); } void setPosition(double x, double y) { this.firstGround.x = x; this.firstGround.y = y; this.secondGround.x = this.firstGround.width; this.secondGround.y = y; _rect = Rect.fromLTWH(x, y, _screenSize.width, ComponentDimensions.bottomHeight); } void update(double t){ if (status == BottomStatus.moving) { this.firstGround.x -= t * Speed.GroundSpeed; this.secondGround.x -= t * Speed.GroundSpeed; if (this.firstGround.x + this.firstGround.width <= 0) { this.firstGround.x = this.secondGround.x + this.secondGround.width; } if (this.secondGround.x + this.secondGround.width <= 0) { this.secondGround.x = this.firstGround.x + this.firstGround.width; } } } void move() { status = BottomStatus.moving; } } class BottomGround extends SpriteComponent with Resizable { BottomGround(Sprite sprite, Size screenSize) : super.fromSprite( screenSize.width, ComponentDimensions.bottomHeight, sprite); }
0
mirrored_repositories/Flutter.Bird/lib
mirrored_repositories/Flutter.Bird/lib/game/gameover.dart
import 'dart:ui'; import 'package:flame/components/component.dart'; import 'package:flame/components/composed_component.dart'; import 'package:flame/components/resizable.dart'; import 'package:flame/sprite.dart'; import 'package:flutter_bird/game/config.dart'; class GameOver extends PositionComponent with ComposedComponent { GameOverGround ground; GameOver(Image spriteImage, Size screenSize){ var sprite = Sprite.fromImage( spriteImage, width: SpriteDimensions.gameOverWidth, height: SpriteDimensions.gameOverHeight, y: SpritesPostions.gameOverY, x: SpritesPostions.gameOverX, ); this.ground = GameOverGround(sprite); this.ground.x = (screenSize.width - ComponentDimensions.gameOverWidth) / 2; this.ground.y = (screenSize.height - ComponentDimensions.gameOverHeight) / 2; this..add(ground); } } class GameOverGround extends SpriteComponent with Resizable { GameOverGround(Sprite sprite) : super.fromSprite( ComponentDimensions.gameOverWidth, ComponentDimensions.gameOverHeight, sprite); }
0
mirrored_repositories/Flutter.Bird/lib
mirrored_repositories/Flutter.Bird/lib/game/config.dart
class SpriteDimensions { static double horizontWidth = 144.0; static double horizontHeight = 256.0; static double birdWidth = 17.0; static double birdHeight = 12.0; static double bottomWidth = 168.0; static double bottomHeight = 56.0; static double gameOverWidth = 96.0; static double gameOverHeight = 21.0; static double tubeWidth = 26.0; static double tubeHeight = 160.0; static double numberWidth = 12.0; static double numberHeight = 18.0; } class SpritesPostions { static double birdSprite1X = 3.0; static double birdSprite1Y = 491.0; static double birdSprite2X = 31.0; static double birdSprite2Y = 491.0; static double birdSprite3X = 59.0; static double birdSprite3Y = 491.0; static double bottomX = 292.0; static double bottomY = 0.0; static double gameOverX = 395.0; static double gameOverY = 59.0; static double tubeX = 84.0; static double tubeY = 323.0; static double zeroNumberX = 496.0; static double zeroNumberY = 60.0; static double firstNumberX = 136.0; static double firstNumberY = 455.0; static double secondNumberX = 292.0; static double secondNumberY = 160.0; static double thirdNumberX = 306.0; static double thirdNumberY = 160.0; static double fourthNumberX = 320.0; static double fourthNumberY = 160.0; static double fifthNumberX = 334.0; static double fifthNumberY = 160.0; static double sixthNumberX = 292.0; static double sixthNumberY = 184.0; static double seventhNumberX = 306.0; static double seventhNumberY = 184.0; static double eighthNumberX = 320.0; static double eighthNumberY = 184.0; static double ninethNumberX = 334.0; static double ninethNumberY = 184.0; } class ComponentDimensions { static double bottomHeight = 130; static double gameOverWidth = 200; static double gameOverHeight = 43.75; static double tubeWidth = 78; static double tubeHeight = 480; static double birdWidth = 51; static double birdHeight = 36; static double numberWidth = 36; static double numberHeight = 54; } class ComponentPositions { static double birdX = 80; static double birdY = 250; } class Speed { static double GroundSpeed = 120; static double GameSpeed = 1.0; }
0
mirrored_repositories/Flutter.Bird/lib
mirrored_repositories/Flutter.Bird/lib/game/game.dart
import 'dart:ui'; import 'package:flame/flame.dart'; import 'package:flame/game.dart'; import 'package:flutter_bird/game/bird.dart'; import 'package:flutter_bird/game/bottom.dart'; import 'package:flutter_bird/game/config.dart'; import 'package:flutter_bird/game/gameover.dart'; import 'package:flutter_bird/game/horizont.dart'; import 'package:flutter_bird/game/scorer.dart'; import 'package:flutter_bird/game/tube.dart'; import 'package:flutter_bird/main.dart'; enum GameStatus { playing, waiting, gameOver } class FlutterBirdGame extends BaseGame { Size screenSize; Horizon horizon; Bird bird; Bottom bottom; GameOver gameOver; Tube firstTopTube; Tube firstBottomTube; Tube secondTopTube; Tube secondBottomTube; Tube thirdTopTube; Tube thirdBottomTube; Image _spriteImage; Scorer _scorer; GameStatus status = GameStatus.waiting; double xTubeOffset = 220; double xTubeStart = Singleton.instance.screenSize.width * 1.5; FlutterBirdGame(Image spriteImage, Size screenSize) { _spriteImage = spriteImage; horizon = Horizon(spriteImage, screenSize); bird = Bird(spriteImage, screenSize); bottom = Bottom(spriteImage, screenSize); gameOver = GameOver(spriteImage, screenSize); _scorer = Scorer(spriteImage, screenSize); firstBottomTube = Tube(TubeType.bottom, spriteImage); firstTopTube = Tube(TubeType.top, spriteImage, firstBottomTube); secondBottomTube = Tube(TubeType.bottom, spriteImage); secondTopTube = Tube(TubeType.top, spriteImage, secondBottomTube); thirdBottomTube = Tube(TubeType.bottom, spriteImage); thirdTopTube = Tube(TubeType.top, spriteImage, thirdBottomTube); initPositions(spriteImage); this ..add(horizon) ..add(bird) ..add(firstTopTube) ..add(firstBottomTube) ..add(secondTopTube) ..add(secondBottomTube) ..add(thirdTopTube) ..add(thirdBottomTube) ..add(bottom) ..add(gameOver) ..add(_scorer); } void initPositions(Image spriteImage) { bird.setPosition(ComponentPositions.birdX, ComponentPositions.birdY); bottom.setPosition(0, Singleton.instance.screenSize.height - ComponentDimensions.bottomHeight); firstBottomTube.setPosition(xTubeStart, 400); firstTopTube.setPosition(xTubeStart, -250); secondBottomTube.setPosition(xTubeStart + xTubeOffset, 400); secondTopTube.setPosition(xTubeStart + xTubeOffset, -250); thirdBottomTube.setPosition(xTubeStart + xTubeOffset * 2, 400); thirdTopTube.setPosition(xTubeStart + xTubeOffset * 2, -250); gameOver.ground.y = Singleton.instance.screenSize.height; } @override void update(double t) { if (status != GameStatus.playing) return; bird.update(t * Speed.GameSpeed); bottom.update(t * Speed.GameSpeed); firstBottomTube.update(t * Speed.GameSpeed); firstTopTube.update(t * Speed.GameSpeed); secondBottomTube.update(t * Speed.GameSpeed); secondTopTube.update(t * Speed.GameSpeed); thirdBottomTube.update(t * Speed.GameSpeed); thirdTopTube.update(t * Speed.GameSpeed); var birdRect = bird.ground.toRect(); if (check2ItemsCollision(birdRect, bottom.rect)){ gameOverAction(); } if (check2ItemsCollision(birdRect, firstBottomTube.ground.toRect())){ gameOverAction(); } if (check2ItemsCollision(birdRect, firstTopTube.ground.toRect())){ gameOverAction(); } if (check2ItemsCollision(birdRect, secondBottomTube.ground.toRect())){ gameOverAction(); } if (check2ItemsCollision(birdRect, secondTopTube.ground.toRect())){ gameOverAction(); } if (check2ItemsCollision(birdRect, thirdBottomTube.ground.toRect())){ gameOverAction(); } if (check2ItemsCollision(birdRect, thirdTopTube.ground.toRect())){ gameOverAction(); } if (checkIfBirdCrossedTube(firstTopTube) || checkIfBirdCrossedTube(secondTopTube) || checkIfBirdCrossedTube(thirdTopTube)) { _scorer.increase(); } } void gameOverAction(){ if (status != GameStatus.gameOver) { Flame.audio.play('hit.wav'); Flame.audio.play('die.wav'); status = GameStatus.gameOver; gameOver.ground.y = (Singleton.instance.screenSize.height - gameOver.ground.height) / 2; } } bool checkIfBirdCrossedTube(Tube tube) { if (!tube.crossedBird) { var tubeRect = tube.ground.toRect(); var xCenterOfTube = tubeRect.left + tubeRect.width / 2; var xCenterOfBird = ComponentPositions.birdX + ComponentDimensions.birdWidth / 2; if (xCenterOfTube < xCenterOfBird && status == GameStatus.playing) { tube.crossedBird = true; return true; } } return false; } void onTap() { switch (status) { case GameStatus.waiting: status = GameStatus.playing; bird.jump(); bottom.move(); break; case GameStatus.gameOver: status = GameStatus.waiting; initPositions(_spriteImage); _scorer.reset(); break; case GameStatus.playing: bird.jump(); break; default: } } bool check2ItemsCollision(Rect item1, Rect item2){ var intersectedRect = item1.intersect(item2); return intersectedRect.width > 0 && intersectedRect.height > 0; } }
0
mirrored_repositories/Flutter.Bird/lib
mirrored_repositories/Flutter.Bird/lib/game/tube.dart
import 'dart:math'; import 'dart:ui'; import 'package:flame/components/component.dart'; import 'package:flame/components/composed_component.dart'; import 'package:flame/components/resizable.dart'; import 'package:flame/sprite.dart'; import 'package:flutter_bird/game/config.dart'; import 'package:flutter_bird/main.dart'; enum TubeType { top, bottom } class Tube extends PositionComponent with Resizable, ComposedComponent { Tube _bottomTube; TubeGround ground; TubeType _type; bool _hasBeenOnScreen = false; double _holeRange = 150; double get _topTubeOffset => Singleton.instance.screenSize.height * 0.15; double get _bottomTubeOffset => Singleton.instance.screenSize.height * 0.5; bool get isOnScreen => this.ground.x + ComponentDimensions.tubeWidth > 0 && this.ground.x < Singleton.instance.screenSize.width; bool crossedBird = false; Tube(TubeType type, Image spriteImage, [Tube bottomTube]) { _type = type; _bottomTube = bottomTube; var sprite = Sprite.fromImage( spriteImage, width: SpriteDimensions.tubeWidth, height: SpriteDimensions.tubeHeight, y: SpritesPostions.tubeY, x: SpritesPostions.tubeX, ); this.ground = TubeGround(sprite, _type); switch (_type) { case TubeType.top: this.ground.angle = 3.14159; // radians break; default: } this..add(ground); } @override Rect toRect() { var baseRect = super.toRect(); if (_type == TubeType.bottom) { return baseRect; } else { return Rect.fromLTWH( baseRect.left - ComponentDimensions.tubeWidth, baseRect.top - ComponentDimensions.tubeHeight, baseRect.width, baseRect.height ); } } void setPosition(double x, double y) { _hasBeenOnScreen = false; crossedBird = false; this.ground.x = x + (_type == TubeType.top ? ComponentDimensions.tubeWidth : 0); setY(); } void update(double t){ if (!_hasBeenOnScreen && isOnScreen) _hasBeenOnScreen = true; if (_hasBeenOnScreen && !isOnScreen) { print("Moved"); this.ground.x = Singleton.instance.screenSize.width * 1.5; setY(); crossedBird = false; _hasBeenOnScreen = false; } this.ground.x -= t * Speed.GroundSpeed; } void setY() { var ratio = double.parse(Random().nextDouble().toStringAsFixed(2)); var length = _bottomTubeOffset - _topTubeOffset; var newY = length * ratio + _topTubeOffset; this.ground.y = newY; if (_bottomTube != null) { _bottomTube.ground.y = newY + _holeRange; } } } class TubeGround extends SpriteComponent with Resizable { TubeType _type; TubeGround(Sprite sprite, TubeType type) : super.fromSprite( ComponentDimensions.tubeWidth, ComponentDimensions.tubeHeight, sprite) { _type = type; } @override Rect toRect() { var baseRect = super.toRect(); if (_type == TubeType.bottom) { return baseRect; } else { return Rect.fromLTWH( baseRect.left - ComponentDimensions.tubeWidth, baseRect.top - ComponentDimensions.tubeHeight, baseRect.width, baseRect.height ); } } }
0
mirrored_repositories/Flutter.Bird/lib
mirrored_repositories/Flutter.Bird/lib/game/scorer.dart
import 'dart:collection'; import 'dart:ui'; import 'package:flame/components/component.dart'; import 'package:flame/components/composed_component.dart'; import 'package:flame/components/resizable.dart'; import 'package:flame/flame.dart'; import 'package:flame/sprite.dart'; import 'config.dart'; class Scorer extends PositionComponent with ComposedComponent { int _score = 0; Size _screenSize; HashMap<String, Sprite> _digits; ScorerGround _oneDigitGround; ScorerGround _twoDigitGround; ScorerGround _threeDigitGround; Scorer(Image spriteImage, Size screenSize){ _screenSize = screenSize; _initSprites(spriteImage); _renderDefaultView(); } void increase() { _score++; _render(); Flame.audio.play('point.wav'); } void reset() { _score = 0; _render(); } void _render(){ // Adds leading zeroes to 3 digits var scoreStr = _score.toString().padLeft(3, '0'); _oneDigitGround.sprite = _digits[scoreStr[2]]; _twoDigitGround.sprite = _digits[scoreStr[1]]; _threeDigitGround.sprite = _digits[scoreStr[0]]; } void _initSprites(Image spriteImage){ _digits = HashMap.from({ "0": Sprite.fromImage( spriteImage, width: SpriteDimensions.numberWidth, height: SpriteDimensions.numberHeight, x: SpritesPostions.zeroNumberX, y: SpritesPostions.zeroNumberY, ), "1": Sprite.fromImage( spriteImage, width: SpriteDimensions.numberWidth, height: SpriteDimensions.numberHeight, x: SpritesPostions.firstNumberX, y: SpritesPostions.firstNumberY, ), "2": Sprite.fromImage( spriteImage, width: SpriteDimensions.numberWidth, height: SpriteDimensions.numberHeight, x: SpritesPostions.secondNumberX, y: SpritesPostions.secondNumberY, ), "3": Sprite.fromImage( spriteImage, width: SpriteDimensions.numberWidth, height: SpriteDimensions.numberHeight, x: SpritesPostions.thirdNumberX, y: SpritesPostions.thirdNumberY, ), "4": Sprite.fromImage( spriteImage, width: SpriteDimensions.numberWidth, height: SpriteDimensions.numberHeight, x: SpritesPostions.fourthNumberX, y: SpritesPostions.fourthNumberY, ), "5": Sprite.fromImage( spriteImage, width: SpriteDimensions.numberWidth, height: SpriteDimensions.numberHeight, x: SpritesPostions.fifthNumberX, y: SpritesPostions.fifthNumberY, ), "6": Sprite.fromImage( spriteImage, width: SpriteDimensions.numberWidth, height: SpriteDimensions.numberHeight, x: SpritesPostions.sixthNumberX, y: SpritesPostions.sixthNumberY, ), "7": Sprite.fromImage( spriteImage, width: SpriteDimensions.numberWidth, height: SpriteDimensions.numberHeight, x: SpritesPostions.seventhNumberX, y: SpritesPostions.seventhNumberY, ), "8": Sprite.fromImage( spriteImage, width: SpriteDimensions.numberWidth, height: SpriteDimensions.numberHeight, x: SpritesPostions.eighthNumberX, y: SpritesPostions.eighthNumberY, ), "9": Sprite.fromImage( spriteImage, width: SpriteDimensions.numberWidth, height: SpriteDimensions.numberHeight, x: SpritesPostions.ninethNumberX, y: SpritesPostions.ninethNumberY, ) }); } void _renderDefaultView() { double defaultY = 80; var twoGroundX = (_screenSize.width - ComponentDimensions.numberWidth) / 2; _twoDigitGround = ScorerGround(_digits["0"]); this._twoDigitGround.x = twoGroundX; this._twoDigitGround.y = defaultY; _oneDigitGround = ScorerGround(_digits["0"]); this._oneDigitGround.x = _twoDigitGround.toRect().right + 5; this._oneDigitGround.y = defaultY; _threeDigitGround = ScorerGround(_digits["0"]); this._threeDigitGround.x = twoGroundX - ComponentDimensions.numberWidth - 5; this._threeDigitGround.y = defaultY; this..add(_oneDigitGround)..add(_twoDigitGround)..add(_threeDigitGround); } } class ScorerGround extends SpriteComponent with Resizable { ScorerGround(Sprite sprite, [int multiplier = 1]) : super.fromSprite( ComponentDimensions.numberWidth * multiplier, ComponentDimensions.numberHeight, sprite); }
0
mirrored_repositories/Flutter.Bird/lib
mirrored_repositories/Flutter.Bird/lib/game/horizont.dart
import 'dart:ui'; import 'package:flame/components/component.dart'; import 'package:flame/components/resizable.dart'; import 'package:flame/components/composed_component.dart'; import 'package:flame/sprite.dart'; import 'package:flutter_bird/game/config.dart'; class Horizon extends PositionComponent with Resizable, ComposedComponent { HorizonGround ground; Horizon(Image spriteImage, Size screenSize) { Sprite sprite = Sprite.fromImage( spriteImage, width: SpriteDimensions.horizontWidth, height: SpriteDimensions.horizontHeight, y: 0.0, x: 0.0, ); this.ground = HorizonGround(sprite, screenSize); this..add(ground); } } class HorizonGround extends SpriteComponent with Resizable { HorizonGround(Sprite sprite, Size screenSize) : super.fromSprite( screenSize.width, screenSize.height, sprite); }
0
mirrored_repositories/Flutter.Bird
mirrored_repositories/Flutter.Bird/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_bird/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/flutter_todo
mirrored_repositories/flutter_todo/lib/home_page.dart
import 'dart:ui'; import 'package:flex_color_picker/flex_color_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'dart:convert'; import 'package:flutter_iconpicker/flutter_iconpicker.dart'; import 'package:shared_preferences/shared_preferences.dart'; typedef JSON = Map<String, dynamic>; List<Task> tasks = []; class HomePage extends StatefulWidget { HomePage({Key? key}) : super(key: key); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { // OverlayEntry _getEntry(context) { // late OverlayEntry entry; // entry = OverlayEntry( // opaque: false, // maintainState: true, // builder: (_) => TextEditor( // onTap: () { // entry.remove(); // }, // ), // ); // return entry; // } @override Widget build(BuildContext context) { ThemeData theme = Theme.of(context); // Color primaryColor = theme.primaryColor; return Scaffold( body: SafeArea( child: Center( child: Stack( children: [ CustomScrollView( slivers: [ SliverAppBar( title: Text('TODO List', style: TextStyle(color: Theme.of(context).colorScheme.secondary)), actions: [ // IconButton( // onPressed: () async { // // Overlay.of(context)!.insert(_getEntry(context)); // // Navigator.of(context).push( // // HeroDialogRoute( // // builder: (context) => Center( // // child: TextEditor( // // onTap: () {}, // // ), // // ), // // ), // // ); // // IconData? icon = await FlutterIconPicker.showIconPicker( // // context, // // iconPackMode: IconPack.cupertino, // // adaptiveDialog: true, // // iconColor: Theme.of(context).accentColor); // // debugPrint('Picked Icon: $icon'); // }, // icon: Icon(CupertinoIcons.add), // splashRadius: 20, // ), ], floating: true, ), SliverList( delegate: SliverChildBuilderDelegate( (context, index) { Task task = tasks[index]; return Container( margin: EdgeInsets.symmetric(horizontal: 20, vertical: 5), child: Material( color: Colors.transparent, borderRadius: BorderRadius.circular(20), child: InkWell( borderRadius: BorderRadius.circular(20), onTap: () { setState(() { tasks[index].isDone = !task.isDone; save(); }); }, child: Padding( padding: const EdgeInsets.symmetric( horizontal: 10, vertical: 5), child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Checkbox( value: task.isDone, onChanged: (value) { setState(() { tasks[index].isDone = !task.isDone; save(); }); }, visualDensity: theme.visualDensity, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5))), Text( task.task, style: theme.textTheme.subtitle1, ), Spacer(), Icon( task.icon, color: task.color, ), ], ), ), ), ), decoration: BoxDecoration( color: theme.primaryColor, borderRadius: BorderRadius.circular(20), ), ); }, childCount: tasks.length, ), ) ], ), Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Spacer(), GestureDetector( onTap: () async { Task? newTask = await Navigator.of(context) .push( HeroDialogRoute( builder: (context) => Center( child: TextEditor(), ), ), ) .then((value) => value); if (newTask != null) { setState(() { tasks.add(newTask); }); await save(); } else { return; } }, child: Hero( tag: 'textField', createRectTween: (begin, end) { return CustomRectTween(begin: begin!, end: end!); }, child: Material( color: Colors.transparent, child: Container( padding: const EdgeInsets.all(10), margin: const EdgeInsets.all(8), decoration: BoxDecoration( color: theme.primaryColor, borderRadius: BorderRadius.circular(20), ), child: Text( 'Write a new task', style: TextStyle( color: theme.textTheme.bodyText2!.color! .withOpacity(0.5), fontSize: 18, ), ), ), ), ), ), ], ), ), ], ), ), ), ); } } Future<void> save() async { SharedPreferences prefs = await SharedPreferences.getInstance(); String json = jsonEncode(tasks.map((e) => e.toJson()).toList()); await prefs.setString('tasks', json); } Future<void> read() async { SharedPreferences prefs = await SharedPreferences.getInstance(); if (prefs.getString('tasks') != null) { String json = prefs.getString('tasks')!; List<dynamic> data = jsonDecode(json); print(List.generate(data.length, (index) => Task.fromJson(data[index]))); tasks = List.generate(data.length, (index) => Task.fromJson(data[index])); } else { return; } } class Task { String task; bool isDone; Color color; IconData icon; Task({ required this.task, required this.isDone, required this.icon, required this.color, }); factory Task.fromJson(JSON json) { print(json['icon']['codePoint']); print(json['icon']['fontFamily']); print(json['color']); return Task( color: Color(int.parse('0x' + json['color'])), task: json['task'], isDone: json['isDone'], icon: IconData( json['icon']['codePoint'], fontFamily: json['icon']['fontFamily'], ), ); } JSON toJson() { return { 'color': color.hexAlpha, 'task': task, 'isDone': isDone, 'icon': { 'codePoint': icon.codePoint, 'fontFamily': icon.fontFamily, } }; } } class TextEditor extends StatefulWidget { TextEditor({Key? key}) : super(key: key); @override _TextEditorState createState() => _TextEditorState(); } class _TextEditorState extends State<TextEditor> { IconData selectedIcon = CupertinoIcons.book_solid; Color dialogPickerColor = Color(0xff894BFC); @override Widget build(BuildContext context) { return Hero( tag: 'textField', createRectTween: (begin, end) { return CustomRectTween(begin: begin!, end: end!); }, child: ClipRRect( borderRadius: BorderRadius.circular(16), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 5), // padding: EdgeInsets.symmetric(horizontal: (MediaQuery.of(context).size.width * 0.2), vertical: 5), child: Material( borderRadius: BorderRadius.circular(16), color: Theme.of(context).primaryColor, child: Container( padding: EdgeInsets.symmetric(vertical: 5), child: Row( children: [ Expanded( flex: 2, child: Container( margin: const EdgeInsets.all(8), decoration: BoxDecoration( color: Colors.transparent, borderRadius: BorderRadius.circular(8), ), child: TextField( autofocus: true, maxLines: 1, onSubmitted: (value) { print(value); Navigator.of(context).pop(Task( task: value, isDone: false, icon: selectedIcon, color: dialogPickerColor)); }, cursorColor: Colors.black, decoration: InputDecoration( contentPadding: EdgeInsets.all(8), hintText: 'Write a new task', border: InputBorder.none, ), ), ), ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ IconButton( padding: EdgeInsets.all(0), onPressed: () async { IconData? icon = await FlutterIconPicker.showIconPicker( context, // customIconPack: , iconPackModes: [IconPack.material], // iconPackMode: IconPack.material, adaptiveDialog: false, iconPickerShape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), iconColor: dialogPickerColor, ); debugPrint('Picked Icon: $icon'); setState(() { selectedIcon = icon ?? CupertinoIcons.book_solid; }); }, icon: Icon( selectedIcon, color: dialogPickerColor, ), splashRadius: 20, ), IconButton( padding: EdgeInsets.all(0), onPressed: () async { await colorPickerDialog(); }, icon: Icon(CupertinoIcons.circle_fill), splashRadius: 20, color: dialogPickerColor, ), ], ), ), ], ), ), ), ), ), ); } Future<bool> colorPickerDialog() async { return ColorPicker( // Use the dialogPickerColor as start color. color: dialogPickerColor, // Update the dialogPickerColor using the callback. onColorChanged: (Color color) => setState(() => dialogPickerColor = color), // width: 40, // height: 40, borderRadius: 16, showRecentColors: false, enableShadesSelection: false, heading: Text( 'Select color', style: Theme.of(context).textTheme.headline5, ), customColorSwatchesAndNames: <ColorSwatch<Object>, String>{ ColorTools.createPrimarySwatch(Color(0xff0163AE)): '', ColorTools.createPrimarySwatch(Color(0xff0163AE)): 'Dark Blue', ColorTools.createPrimarySwatch(Color(0xff038FFD)): 'Blue', ColorTools.createPrimarySwatch(Color(0xff00C0FF)): 'Light Blue', ColorTools.createPrimarySwatch(Color(0xff0AB9AF)): 'Teal', ColorTools.createPrimarySwatch(Color(0xff02B96D)): 'Green', ColorTools.createPrimarySwatch(Color(0xffDEBB10)): 'Yellow', ColorTools.createPrimarySwatch(Color(0xffFFF2AF)): 'Gold?', ColorTools.createPrimarySwatch(Color(0xffFF6B56)): 'Light Red', ColorTools.createPrimarySwatch(Color(0xffE80239)): 'Red', ColorTools.createPrimarySwatch(Color(0xffAC0F0D)): 'Dark Red', ColorTools.createPrimarySwatch(Color(0xffBF108D)): 'Dark Pink', ColorTools.createPrimarySwatch(Color(0xffF76EE8)): 'Pink', ColorTools.createPrimarySwatch(Color(0xff7A44FD)): 'Purple', ColorTools.createPrimarySwatch(Color(0xff4644FE)): 'Bluerple', ColorTools.createPrimarySwatch(Color(0xff9296A2)): 'Grey', ColorTools.createPrimarySwatch(Color(0xff7E7063)): 'Brown', }, materialNameTextStyle: Theme.of(context).textTheme.caption, colorNameTextStyle: Theme.of(context).textTheme.caption, colorCodeTextStyle: Theme.of(context).textTheme.caption, pickersEnabled: const <ColorPickerType, bool>{ ColorPickerType.both: false, ColorPickerType.primary: false, ColorPickerType.accent: false, ColorPickerType.bw: false, ColorPickerType.custom: true, ColorPickerType.wheel: false, }, ).showPickerDialog( context, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), constraints: const BoxConstraints(minHeight: 70, minWidth: 100, maxWidth: 320), ); } } /// {@template hero_dialog_route} /// Custom [PageRoute] that creates an overlay dialog (popup effect). /// /// Best used with a [Hero] animation. /// {@endtemplate} class HeroDialogRoute<T> extends PageRoute<T> { /// {@macro hero_dialog_route} HeroDialogRoute({ required WidgetBuilder builder, RouteSettings? settings, bool fullscreenDialog = false, }) : _builder = builder, super(settings: settings, fullscreenDialog: fullscreenDialog); final WidgetBuilder _builder; @override bool get opaque => false; @override bool get barrierDismissible => true; @override Duration get transitionDuration => const Duration(milliseconds: 300); @override bool get maintainState => true; @override Color get barrierColor => Colors.black54; @override Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { return child; } @override Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { return _builder(context); } @override String get barrierLabel => 'Popup dialog open'; } /// {@template custom_rect_tween} /// Linear RectTween with a [Curves.easeOut] curve. /// /// Less dramatic that the regular [RectTween] used in [Hero] animations. /// {@endtemplate} class CustomRectTween extends RectTween { /// {@macro custom_rect_tween} CustomRectTween({ required Rect begin, required Rect end, }) : super(begin: begin, end: end); @override Rect lerp(double t) { final elasticCurveValue = Curves.easeOut.transform(t); return Rect.fromLTRB( lerpDouble(begin!.left, end!.left, elasticCurveValue)!, lerpDouble(begin!.top, end!.top, elasticCurveValue)!, lerpDouble(begin!.right, end!.right, elasticCurveValue)!, lerpDouble(begin!.bottom, end!.bottom, elasticCurveValue)!, ); } }
0
mirrored_repositories/flutter_todo
mirrored_repositories/flutter_todo/lib/main.dart
import 'package:flutter/material.dart'; // import 'package:shared_preferences/shared_preferences.dart'; import 'home_page.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); // var prefs = await SharedPreferences.getInstance(); // prefs.clear(); await read(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'MyApp', themeMode: ThemeMode.system, theme: ThemeData( // brightness: Brightness.light, scaffoldBackgroundColor: Color(0xffE8EAED), primaryColor: Colors.white, appBarTheme: AppBarTheme(color: Color(0xffE8EAED)), colorScheme: ColorScheme.fromSwatch().copyWith( secondary: Color(0xff434346), brightness: Brightness.light, ), ), darkTheme: ThemeData( // brightness: Brightness.dark, primaryColor: Color(0xff393B43), checkboxTheme: CheckboxThemeData( fillColor: MaterialStateProperty.all( Color(0xff303137), ), ), scaffoldBackgroundColor: Color(0xff303137), appBarTheme: AppBarTheme(color: Color(0xff303137)), colorScheme: ColorScheme.fromSwatch().copyWith( secondary: Color(0xffE8EAED), brightness: Brightness.dark, ), ), home: HomePage(), ); } }
0
mirrored_repositories/flutter_todo
mirrored_repositories/flutter_todo/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_todo/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/savvy
mirrored_repositories/savvy/lib/main.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:instagram_flutter/providers/user_provider.dart'; import 'package:instagram_flutter/responsive/mobile_screen_layout.dart'; import 'package:instagram_flutter/responsive/responsive_layout.dart'; import 'package:instagram_flutter/responsive/web_screen_layout.dart'; import 'package:instagram_flutter/screens/login_screen.dart'; import 'package:instagram_flutter/screens/signup_screen.dart'; import 'package:instagram_flutter/utils/color.dart'; import 'package:provider/provider.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); if(kIsWeb){ await Firebase.initializeApp( options: const FirebaseOptions( apiKey: "<YOUR_FIREBASE_WEB_APIKEY>", projectId: "YOUR_FIREBASE_WEB_API_PROJECTID", storageBucket: "<YOUR_FIREBASE_WEB_API_STORAGEBUCKET>", messagingSenderId: "<YOUR_FIREBASE_WEB_API_MESSAGEINGSENDERID>", appId: "<YOUR_FIREBASE_WEB_API_APPID>" ), ); } else { await Firebase.initializeApp(); } runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider(create: (_) => userProvider(),), ], child: MaterialApp( debugShowCheckedModeBanner: false, title: 'Savvy', theme: ThemeData.dark().copyWith( scaffoldBackgroundColor: mobileBackgroundColor, ), home: StreamBuilder( stream: FirebaseAuth.instance.authStateChanges(), builder: (context, snapshot) { if(snapshot.connectionState == ConnectionState.active) { if(snapshot.hasData) { return const ResponsiveLauout( mobileScreenLayout: MobileScreenLayout(), webScreenLayout: WebScreenLayout(), ); } else if(snapshot.hasError) { return Center( child: Text('${snapshot.error}'), ); } } if(snapshot.connectionState == ConnectionState.waiting) { return const Center(child: CircularProgressIndicator( color: primaryColor, ), ); } return LoginScreen(); }, ), ), ); } }
0
mirrored_repositories/savvy/lib
mirrored_repositories/savvy/lib/responsive/responsive_layout.dart
import 'package:flutter/material.dart'; import 'package:instagram_flutter/providers/user_provider.dart'; import 'package:instagram_flutter/utils/global.dart'; import 'package:provider/provider.dart'; class ResponsiveLauout extends StatefulWidget { final Widget webScreenLayout; final Widget mobileScreenLayout; const ResponsiveLauout({Key? key, required this.webScreenLayout, required this.mobileScreenLayout}) : super(key: key); @override State<ResponsiveLauout> createState() => _ResponsiveLauoutState(); } class _ResponsiveLauoutState extends State<ResponsiveLauout> { @override void initState() { super.initState(); addData(); } addData() async { userProvider _userProvider = Provider.of(context, listen: false); await _userProvider.refreshUser(); } @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, constraints) { if(constraints.maxWidth > webScreenSize) { return widget.webScreenLayout; } return widget.mobileScreenLayout; }, ); } }
0
mirrored_repositories/savvy/lib
mirrored_repositories/savvy/lib/responsive/web_screen_layout.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:instagram_flutter/utils/color.dart'; import 'package:instagram_flutter/utils/global.dart'; class WebScreenLayout extends StatefulWidget { const WebScreenLayout({Key? key}) : super(key: key); @override State<WebScreenLayout> createState() => _WebScreenLayoutState(); } class _WebScreenLayoutState extends State<WebScreenLayout> { int _page = 0; late PageController pageController; // for tabs animation @override void initState() { super.initState(); pageController = PageController(); } @override void dispose() { super.dispose(); pageController.dispose(); } void onPageChanged(int page) { setState(() { _page = page; }); } void navigationTapped(int page) { //Animating Page pageController.jumpToPage(page); setState(() { _page = page; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: mobileBackgroundColor, centerTitle: false, title: SvgPicture.asset( 'assets/ic_instagram.svg', color: primaryColor, height: 32, ), actions: [ IconButton( icon: Icon( Icons.home, color: _page == 0 ? primaryColor : secondaryColor, ), onPressed: () => navigationTapped(0), ), IconButton( icon: Icon( Icons.search, color: _page == 1 ? primaryColor : secondaryColor, ), onPressed: () => navigationTapped(1), ), IconButton( icon: Icon( Icons.add_a_photo, color: _page == 2 ? primaryColor : secondaryColor, ), onPressed: () => navigationTapped(2), ), IconButton( icon: Icon( Icons.favorite, color: _page == 3 ? primaryColor : secondaryColor, ), onPressed: () => navigationTapped(3), ), IconButton( icon: Icon( Icons.person, color: _page == 4 ? primaryColor : secondaryColor, ), onPressed: () => navigationTapped(4), ), ], ), body: PageView( physics: const NeverScrollableScrollPhysics(), children: homeScreenItems, controller: pageController, onPageChanged: onPageChanged, ), ); } }
0
mirrored_repositories/savvy/lib
mirrored_repositories/savvy/lib/responsive/mobile_screen_layout.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:instagram_flutter/utils/color.dart'; import 'package:instagram_flutter/utils/global.dart'; class MobileScreenLayout extends StatefulWidget { const MobileScreenLayout({Key? key}) : super(key: key); @override State<MobileScreenLayout> createState() => _MobileScreenLayoutState(); } class _MobileScreenLayoutState extends State<MobileScreenLayout> { int _page = 0; late PageController pageController; @override void initState() { super.initState(); pageController = PageController(); } @override void dispose() { super.dispose(); pageController.dispose(); } void navigationTapped(int page) { pageController.jumpToPage(page); } void onPageChanged(int page) { setState(() { _page = page; }); } @override Widget build(BuildContext context) { return Scaffold( body: PageView( children: homeScreenItems, physics: const NeverScrollableScrollPhysics(), controller: pageController, onPageChanged: onPageChanged, ), bottomNavigationBar: CupertinoTabBar( backgroundColor: mobileBackgroundColor, items: [ BottomNavigationBarItem( icon: Icon( Icons.home, color: _page == 0 ? primaryColor : secondaryColor, ), label: '', backgroundColor: primaryColor), BottomNavigationBarItem( icon: Icon( Icons.search, color: _page == 1 ? primaryColor : secondaryColor, ), label: '', backgroundColor: primaryColor), BottomNavigationBarItem( icon: Icon( Icons.add_circle, color: _page == 2 ? primaryColor : secondaryColor, ), label: '', backgroundColor: primaryColor), BottomNavigationBarItem( icon: Icon( Icons.favorite, color: _page == 3 ? primaryColor : secondaryColor, ), label: '', backgroundColor: primaryColor), BottomNavigationBarItem( icon: Icon( Icons.person, color: _page == 4 ? primaryColor : secondaryColor, ), label: '', backgroundColor: primaryColor), ], onTap: navigationTapped, ), ); } }
0
mirrored_repositories/savvy/lib
mirrored_repositories/savvy/lib/resources/storage_methods.dart
import 'dart:typed_data'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:uuid/uuid.dart'; class StorageMethods { final FirebaseAuth _auth = FirebaseAuth.instance; final FirebaseStorage _storage = FirebaseStorage.instance; // adding image to firebase storage Future<String> uploadImageToStorage(String childName, Uint8List file, bool isPost) async { // creating location to our firebase storage Reference ref = _storage.ref().child(childName).child(_auth.currentUser!.uid); if(isPost) { String id = const Uuid().v1(); ref = ref.child(id); } // putting in uint8list format -> Upload task like a future but not future UploadTask uploadTask = ref.putData( file ); TaskSnapshot snapshot = await uploadTask; String downloadUrl = await snapshot.ref.getDownloadURL(); return downloadUrl; } }
0
mirrored_repositories/savvy/lib
mirrored_repositories/savvy/lib/resources/firestore_methods.dart
import 'dart:typed_data'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:instagram_flutter/models/post.dart'; import 'package:instagram_flutter/resources/storage_methods.dart'; import 'package:uuid/uuid.dart'; class FireStoreMethods { final FirebaseFirestore _firestore = FirebaseFirestore.instance; Future<String> uploadPost(String description, Uint8List file, String uid, String username, String profImage) async { // asking uid here because we dont want to make extra calls to firebase auth when we can just get from our state management String res = "Some error occurred"; try { String photoUrl = await StorageMethods().uploadImageToStorage('posts', file, true); String postId = const Uuid().v1(); // creates unique id based on time Post post = Post( description: description, uid: uid, username: username, likes: [], postId: postId, datePublished: DateTime.now(), postUrl: photoUrl, profileImage: profImage, ); _firestore.collection('posts').doc(postId).set(post.toJson()); res = "success"; } catch (err) { res = err.toString(); } return res; } Future<String> likePost(String postId, String uid, List likes) async { String res = "Some error occurred"; try { if (likes.contains(uid)) { // if the likes list contains the user uid, we need to remove it _firestore.collection('posts').doc(postId).update({ 'likes': FieldValue.arrayRemove([uid]) }); } else { // else we need to add uid to the likes array _firestore.collection('posts').doc(postId).update({ 'likes': FieldValue.arrayUnion([uid]) }); } res = 'success'; } catch (err) { res = err.toString(); } return res; } // Post comment Future<String> postComment(String postId, String text, String uid, String name, String profilePic) async { String res = "Some error occurred"; try { if (text.isNotEmpty) { // if the likes list contains the user uid, we need to remove it String commentId = const Uuid().v1(); _firestore .collection('posts') .doc(postId) .collection('comments') .doc(commentId) .set({ 'profilePic': profilePic, 'name': name, 'uid': uid, 'text': text, 'commentId': commentId, 'datePublished': DateTime.now(), }); res = 'success'; } else { res = "Please enter text"; } } catch (err) { res = err.toString(); } return res; } // Delete Post Future<String> deletePost(String postId) async { String res = "Some error occurred"; try { await _firestore.collection('posts').doc(postId).delete(); res = 'success'; } catch (err) { res = err.toString(); } return res; } Future<void> followUser( String uid, String followId ) async { try { DocumentSnapshot snap = await _firestore.collection('users').doc(uid).get(); List following = (snap.data()! as dynamic)['following']; if(following.contains(followId)) { await _firestore.collection('users').doc(followId).update({ 'followers': FieldValue.arrayRemove([uid]) }); await _firestore.collection('users').doc(uid).update({ 'following': FieldValue.arrayRemove([followId]) }); } else { await _firestore.collection('users').doc(followId).update({ 'followers': FieldValue.arrayUnion([uid]) }); await _firestore.collection('users').doc(uid).update({ 'following': FieldValue.arrayUnion([followId]) }); } } catch(e) { print(e.toString()); } } }
0
mirrored_repositories/savvy/lib
mirrored_repositories/savvy/lib/resources/auth_methods.dart
import 'dart:typed_data'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:instagram_flutter/models/user.dart' as model; import 'package:instagram_flutter/resources/storage_methods.dart'; class AuthMethods { final FirebaseFirestore _firestore = FirebaseFirestore.instance; final FirebaseAuth _auth = FirebaseAuth.instance; // get user details Future<model.User> getUserDetails() async { User currentUser = _auth.currentUser!; DocumentSnapshot documentSnapshot = await _firestore.collection('users').doc(currentUser.uid).get(); return model.User.fromSnap(documentSnapshot); } // Signing Up User Future<String> signUpUser({ required String email, required String password, required String username, required String bio, required Uint8List file, }) async { String res = "Some error Occurred"; try { if (email.isNotEmpty || password.isNotEmpty || username.isNotEmpty || bio.isNotEmpty || file != null) { // registering user in auth with email and password UserCredential cred = await _auth.createUserWithEmailAndPassword( email: email, password: password, ); String photoUrl = await StorageMethods().uploadImageToStorage('profilePics', file, false); model.User _user = model.User( username: username, uid: cred.user!.uid, photoUrl: photoUrl, email: email, bio: bio, followers: [], following: [], ); // adding user in our database await _firestore .collection("users") .doc(cred.user!.uid) .set(_user.toJson()); res = "success"; } else { res = "Please enter all the fields"; } } catch (err) { return err.toString(); } return res; } // logging in user Future<String> loginUser({ required String email, required String password, }) async { String res = "Some error Occurred"; try { if (email.isNotEmpty || password.isNotEmpty) { // logging in user with email and password await _auth.signInWithEmailAndPassword( email: email, password: password, ); res = "success"; } else { res = "Please enter all the fields"; } } catch (err) { return err.toString(); } return res; } Future<void> signOut() async { await _auth.signOut(); } }
0
mirrored_repositories/savvy/lib
mirrored_repositories/savvy/lib/models/user.dart
import 'package:cloud_firestore/cloud_firestore.dart'; class User { final String email; final String uid; final String photoUrl; final String username; final String bio; final List followers; final List following; const User({ required this.email, required this.bio, required this.followers, required this.following, required this.photoUrl, required this.uid, required this.username, }); Map<String, dynamic> toJson() => { "username": username, "uid": uid, "email": email, "photoUrl": photoUrl, "bio": bio, "followers": followers, "following": following, }; static User fromSnap(DocumentSnapshot snap) { var snapshot = snap.data() as Map<String, dynamic>; return User( username: snapshot['username'], uid: snapshot['uid'], email: snapshot['email'], photoUrl: snapshot['photoUrl'], bio: snapshot['bio'], followers: snapshot['followers'], following: snapshot['following'], ); } }
0
mirrored_repositories/savvy/lib
mirrored_repositories/savvy/lib/models/post.dart
import 'package:cloud_firestore/cloud_firestore.dart'; class Post { final String description; final String uid; final String username; final String postId; final datePublished; final String postUrl; final String profileImage; final likes; const Post({ required this.description, required this.uid, required this.username, required this.postId, required this.datePublished, required this.postUrl, required this.profileImage, required this.likes, }); Map<String, dynamic> toJson() => { "description": description, "uid": uid, "username": username, "postId": postId, "datePublished": datePublished, "profileImage": profileImage, "postUrl": postUrl, "likes": likes, }; static Post fromSnap(DocumentSnapshot snap) { var snapshot = snap.data() as Map<String, dynamic>; return Post( description: snapshot['description'], uid: snapshot['uid'], username: snapshot['username'], postId: snapshot['postId'], datePublished: snapshot['datePublished'], profileImage: snapshot['profileImage'], postUrl: snapshot['postUrl'], likes: snapshot['likes'], ); } }
0