repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/sort_it/lib
mirrored_repositories/sort_it/lib/controller/settings_controller.dart
import 'package:get/get.dart'; class SettingsController extends GetxController { RxBool darkMode = true.obs; RxBool playInBg = false.obs; void changeMode() { darkMode.value = !darkMode.value; } void changeBgMode() { playInBg.value = !playInBg.value; } }
0
mirrored_repositories/sort_it/lib
mirrored_repositories/sort_it/lib/controller/profile_controller.dart
import 'dart:convert'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:dio/dio.dart'; import 'package:get/get.dart'; import 'package:pretty_dio_logger/pretty_dio_logger.dart'; class ProfileController extends GetxController { //-----------VARIABLES----------// final FirebaseFirestore db = FirebaseFirestore.instance; @override void onInit() { getData(); super.onInit(); } void getData() async { Dio dio = Dio(); dio.interceptors.add(PrettyDioLogger( requestHeader: true, requestBody: true, responseBody: true, responseHeader: false, compact: false, )); try { // QueryDocumentSnapshot<Map<String, dynamic>> data = // (await db.collection('users').get()).docs.first; // print(jsonEncode(data.data())); } catch (e) { print(e); } } }
0
mirrored_repositories/sort_it/lib
mirrored_repositories/sort_it/lib/controller/test_controller.dart
import 'package:get/get.dart'; class TestController extends GetxController { RxString newvar = '+91'.obs; void updateVal(String newval) { newvar.value = newval; } }
0
mirrored_repositories/sort_it/lib
mirrored_repositories/sort_it/lib/controller/complete_controller.dart
import 'package:flutter/cupertino.dart'; import 'package:get/get.dart'; class CompleteProfileController extends GetxController { RxBool passwordState = false.obs; final TextEditingController nameController = TextEditingController(); final TextEditingController emailController = TextEditingController(); final TextEditingController passController = TextEditingController(); void goToPassword({required bool newval}) { passwordState.value = true; } }
0
mirrored_repositories/sort_it/lib
mirrored_repositories/sort_it/lib/controller/scan_controller.dart
import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:qr_code_scanner/qr_code_scanner.dart'; class ScanController extends GetxController { late Rx<Barcode?> result; late Rx<QRViewController?> controller; final GlobalKey qrKey = GlobalKey(debugLabel: 'QR'); RxBool campause = false.obs; RxBool showCodeState = false.obs; final TextEditingController codeController = TextEditingController(); // @override // void onInit() { // onQRViewCreated; // super.onInit(); // } void enterCode({required bool newval}) { showCodeState.value = newval; } void onQRViewCreated(QRViewController newval) { controller.value = newval; controller.value!.scannedDataStream.listen((scanData) { result.value = scanData; }); // print( // 'Barcode Type: ${describeEnum(result!.format)} Data: ${result!.code}'); } void onPermissionSet(BuildContext context, QRViewController ctrl, bool p) { log('${DateTime.now().toIso8601String()}_onPermissionSet $p'); if (!p) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('no Permission')), ); } } ///-------------Toggle Flash------------/// void toggleFlash({required QRViewController? controller}) async { await controller?.toggleFlash(); } ///--------------Toggle Camera----------/// void toggleCamera({required QRViewController? controller}) async { await controller?.flipCamera(); } ///--------------Pause Camera----------/// void pauseCamera({required QRViewController? controller}) async { await controller?.pauseCamera(); campause.value = true; } ///--------------Resume Camera----------/// void resumeCamera({required QRViewController? controller}) async { await controller?.resumeCamera(); campause.value = false; } }
0
mirrored_repositories/sort_it/lib
mirrored_repositories/sort_it/lib/controller/permission_controller.dart
import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:get/get.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:sort_it/src/screens/complete/complete_profile.dart'; import 'package:sort_it/src/screens/home/home.dart'; class PermissionController extends GetxController { Future<void> getPermission(BuildContext context) async { Map<Permission, PermissionStatus> statuses = await [ Permission.location, // Permission.phone, // Permission.sms, Permission.camera, ].request(); if (await Permission.location.request().isGranted) { print('location granted'); Fluttertoast.showToast(msg: "Permission Granted!"); ///Push Named and remove Until Home Screen // Navigator.pushNamedAndRemoveUntil( // context, Home.routeName, (route) => false); Navigator.of(context).pushNamed(CompleteProfile.routeName); } else { Fluttertoast.showToast(msg: "Permission Not Granted!"); } } }
0
mirrored_repositories/sort_it/lib
mirrored_repositories/sort_it/lib/controller/sign_up_controller.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:get/get.dart'; import 'package:sms_autofill/sms_autofill.dart'; import 'package:sort_it/enum/enum.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; class SignUpController extends GetxController { //-----------------VARIABLES----------------// final _auth = FirebaseAuth.instance; final userDb = FirebaseFirestore.instance; RxString verificationId = ''.obs; RxBool isLoading = false.obs; RxBool isLoadingForOtp = false.obs; RxString passError = ''.obs; RxString password = ''.obs; final phoneController = TextEditingController(); final otpController = TextEditingController(); RxBool isObscure = true.obs; MobileVerificationState currentState = MobileVerificationState.SHOW_MOBILE_FORM_STATE; // init() async { // SmsAutoFill().listenForCode; // } void setLoader({required bool newval}) { isLoadingForOtp.value = newval; } void changeObscure() { isObscure.value = !isObscure.value; } String? validatePassword(String value) { RegExp regex = RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$'); if (value.isEmpty) { return 'Please enter password'; } else { if (!regex.hasMatch(value)) { return 'Enter valid password'; } else { return null; } } } ///-----------------------SignIn with Phone and OTP Request------------------/// signInWithPhone(BuildContext context) async { await _auth.verifyPhoneNumber( phoneNumber: '+91' + phoneController.text, verificationCompleted: (verificationCompleted) async { print("-----verification completed--------"); UserCredential result = await _auth.signInWithCredential(verificationCompleted); User? user = result.user; if (user != null) { DocumentSnapshot userCheck = await userDb.collection("users").doc(user.uid).get(); if (userCheck.exists) { print("---------user exists------------"); ///navigate to access permissions page } else { String? token = await FirebaseMessaging.instance.getToken(); userDb.collection('users').doc(user.uid).set({ "id": user.uid, "name": user.displayName, "email": user.email, "tokens": FieldValue.arrayUnion([token]) }); ///Push to complete user profile } Fluttertoast.showToast(msg: 'Successfully signed in'); } else { Fluttertoast.showToast(msg: 'Error signing in'); } }, verificationFailed: (verificationFailed) { print("-----------Login Failed-------"); }, codeSent: (verificationID, resendingToken) { verificationId.value = verificationID; currentState = MobileVerificationState.SHOW_OTP_FORM_STATE; print("------code sent-----"); isLoadingForOtp.value = false; }, codeAutoRetrievalTimeout: (codeAutoRetrievalTimeout) { print("-----code retrieval--------"); }, ); } void signInWithPhoneAuthCredential( PhoneAuthCredential phoneAuthCredential, BuildContext context) async { try { final _authCredential = await _auth.signInWithCredential(phoneAuthCredential); User? user = _authCredential.user; if (user != null) { DocumentSnapshot userCheck = await userDb.collection("users").doc(user.uid).get(); if (userCheck.exists) { print("user existssssssssssssssssss"); // navigationService.navigateTo("/access-permission", // withreplacement: true); } else { String? token = await FirebaseMessaging.instance.getToken(); userDb.collection('users').doc(user.uid).set({ "id": user.uid, "name": user.displayName, "email": user.email, "tokens": FieldValue.arrayUnion([token]) }); Navigator.of(context).pushNamedAndRemoveUntil( '/complete-profile', (Route<dynamic> route) => false); } Fluttertoast.showToast(msg: 'Successfully signed in'); } else { Fluttertoast.showToast(msg: 'Error signing in'); } } on FirebaseAuthException catch (e) { print(e.message); } } ///----------------------------------Google SignIn--------------------------------/// // Future<User?> signInWithGoogle() async { // final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn(); // final GoogleSignInAuthentication googleSignInAuthentication = // await googleUser!.authentication; // final credential = GoogleAuthProvider.credential( // accessToken: googleSignInAuthentication.accessToken, // idToken: googleSignInAuthentication.idToken); // // //value has data of authenticated user // final UserCredential userCred = // await _auth.signInWithCredential(credential); // final User? user = userCred.user; // // if (user != null) { // DocumentSnapshot userCheck = // await userDb.collection("users").doc(user.uid).get(); // if (userCheck.exists) { // print("user existssssssssssssssssss"); // navigationService.navigateTo("/access-permission", // withreplacement: true); // } else { // String? token = await FirebaseMessaging.instance.getToken(); // userDb.collection('users').doc(user.uid).set({ // "id": user.uid, // "name": user.displayName, // "email": user.email, // "tokens": FieldValue.arrayUnion([token]) // }); // navigationService.navigateTo( // "/complete-profile", // withreplacement: true, // ); // } // Fluttertoast.showToast(msg:'Successfully Signed in'); // } else { // Fluttertoast.showToast(msg:'Error signing in'); // } // // return user; // } ///---------------------------------Facebook SignIn-----------------------------/// // Future signInWithFacebook() async { // final LoginResult loginResult = await FacebookAuth.instance.login(); // final OAuthCredential facebookAuthCredential = // FacebookAuthProvider.credential(loginResult.accessToken!.token); // // var user = await FirebaseAuth.instance // .signInWithCredential(facebookAuthCredential); // print(user); // } }
0
mirrored_repositories/sort_it/lib
mirrored_repositories/sort_it/lib/controller/sign_in_controller.dart
import 'dart:io'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:get/get.dart'; class SignInController extends GetxController { //------------------VARIABLES-------------// final FirebaseAuth _auth = FirebaseAuth.instance; var error = 'An error occured please check your credentials!'; String userEmail = ''; String userName = ''; String userPassword = ''; var isLogin = false; bool showPassword = false; final formKey = GlobalKey<FormState>(); File? userImgfile; void pickImage(File? image) { userImgfile = image; } changePasswordVisibility() { showPassword = !showPassword; } changeLoginType() { isLogin = !isLogin; } Future<bool> trySubmit(BuildContext context) async { bool _isValid = formKey.currentState!.validate(); FocusScope.of(context).unfocus(); if (userImgfile == null && !isLogin) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('Please select an image'), backgroundColor: Theme.of(context).errorColor, ), ); return false; } if (_isValid) { formKey.currentState!.save(); return submitAuthForm( userEmail.trim(), userPassword.trim(), userName.trim(), isLogin, context, ); } return false; } Future<bool> submitAuthForm( String email, String password, String username, bool isLogin, BuildContext ctx, ) async { UserCredential currentuser; try { if (isLogin) { currentuser = await _auth.signInWithEmailAndPassword( email: email, password: password); Fluttertoast.showToast(msg: 'Welcome back !'); return true; } else { currentuser = await _auth.createUserWithEmailAndPassword( email: email, password: password); // final ref = FirebaseStorage.instance // .ref() // .child('user_images') // .child(currentuser.user!.uid + '.jpg'); // // await ref.putFile(image!); //final url = await ref.getDownloadURL(); await FirebaseFirestore.instance .collection('users') .doc(currentuser.user!.uid) .set({ 'name': username, 'email': email, 'image_url': null, }); Fluttertoast.showToast(msg: 'Welcome $username!'); return true; } } catch (err) { error = err.toString(); ScaffoldMessenger.of(ctx).showSnackBar( SnackBar( content: Text(error), action: SnackBarAction( onPressed: () {}, label: 'undo', ), backgroundColor: Colors.black, ), ); return false; } } }
0
mirrored_repositories/sort_it/lib
mirrored_repositories/sort_it/lib/enum/enum.dart
enum MobileVerificationState { SHOW_MOBILE_FORM_STATE, SHOW_OTP_FORM_STATE, }
0
mirrored_repositories/sort_it
mirrored_repositories/sort_it/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:sort_it/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-liquid_swipe-package-example/flutter_liquid_swipe_package_example
mirrored_repositories/Flutter-liquid_swipe-package-example/flutter_liquid_swipe_package_example/lib/main.dart
import 'package:flutter/material.dart'; import 'package:liquid_swipe/liquid_swipe.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); ///////////////////////////////////// //@CodeWithFlexz on Instagram // //AmirBayat0 on Github //Programming with Flexz on Youtube ///////////////////////////////////// @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: LiquidSwipeScreen()); } } class LiquidSwipeScreen extends StatelessWidget { LiquidSwipeScreen({Key? key}) : super(key: key); final pages = [ Container( width: double.infinity, height: double.infinity, child: Image( image: AssetImage('assets/images/1.jpg'), fit: BoxFit.cover, ), ), Container( width: double.infinity, height: double.infinity, child: Image( image: AssetImage('assets/images/2.jpg'), fit: BoxFit.cover, ), ), Container( width: double.infinity, height: double.infinity, child: Image( image: AssetImage('assets/images/3.jpg'), fit: BoxFit.cover, ), ), Container( width: double.infinity, height: double.infinity, child: Image( image: AssetImage('assets/images/4.jpg'), fit: BoxFit.cover, ), ), Container( width: double.infinity, height: double.infinity, child: Image( image: AssetImage('assets/images/5.jpg'), fit: BoxFit.cover, ), ), ]; @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( extendBodyBehindAppBar: true, appBar: AppBar( title: Text("@C O D E W I T H F L E X Z"), elevation: 0, centerTitle: true, backgroundColor: Colors.transparent, ), body: LiquidSwipe( pages: pages, enableLoop: true, waveType: WaveType.liquidReveal, // CHANGING TYPE FROM HERE ), ), ); } }
0
mirrored_repositories/Complete-Flutter-Widgets-Tutorial
mirrored_repositories/Complete-Flutter-Widgets-Tutorial/lib/main.dart
import 'package:flutter/material.dart'; import '2-basic-widgets-appbar/BasicWidgets.dart'; import '3-materialapp-scaffold-demo/MaterialAppSacffold.dart'; import '4-appbar-fab-bottom-navigation-bar/AppBarFABDemo.dart'; import '4-appbar-fab-bottom-navigation-bar/BottomNavigationBar.dart'; import '5-container/ContainerDemo.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { static const String _title = 'Tech Talks With AK'; @override Widget build(BuildContext context) { return MaterialApp( title: _title, // home: BasicWidgets(), // home: MaterialAppScaffold(), // home: AppBarFABDemo(), // home: BottomNavigationDemo(), home: ContainerDemo(), ); } }
0
mirrored_repositories/Complete-Flutter-Widgets-Tutorial/lib
mirrored_repositories/Complete-Flutter-Widgets-Tutorial/lib/3-materialapp-scaffold-demo/MaterialAppSacffold.dart
import 'package:flutter/material.dart'; class MaterialAppScaffold extends StatelessWidget{ @override Widget build(BuildContext context) { return Scaffold(); } }
0
mirrored_repositories/Complete-Flutter-Widgets-Tutorial/lib
mirrored_repositories/Complete-Flutter-Widgets-Tutorial/lib/4-appbar-fab-bottom-navigation-bar/BottomNavigationBar.dart
import 'package:flutter/material.dart'; final SnackBar snackBar = const SnackBar( content: Text('Subscribe and get more on Flutter Programming')); class BottomNavigationDemo extends StatefulWidget { BottomNavigationDemo({Key key}) : super(key: key); @override _BottomNavigationDemoState createState() => _BottomNavigationDemoState(); } class _BottomNavigationDemoState extends State<BottomNavigationDemo> { int _selectedIndex = 0; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('This is AppBar'), actions: <Widget>[ Builder( builder: (BuildContext context) { return IconButton( icon: const Icon(Icons.add_alert), tooltip: 'Subscribe Snackbar', onPressed: () { Scaffold.of(context).showSnackBar(snackBar); }, ); }, ), ], ), body: const Center( child: Text( 'Tech Talks With AK', style: TextStyle(fontSize: 24), ), ), bottomNavigationBar: BottomNavigationBar( backgroundColor: Colors.yellowAccent, items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home' ), BottomNavigationBarItem( icon: Icon(Icons.business), label: 'Business' ), BottomNavigationBarItem( icon: Icon(Icons.school), label: 'School' ), BottomNavigationBarItem( icon: Icon(Icons.school), label: 'School' ), BottomNavigationBarItem( icon: Icon(Icons.school), label: 'School' ) ], currentIndex: _selectedIndex, onTap: _onItemTapped, unselectedItemColor: Colors.black, selectedItemColor: Colors.green, type: BottomNavigationBarType.shifting, ), ); } }
0
mirrored_repositories/Complete-Flutter-Widgets-Tutorial/lib
mirrored_repositories/Complete-Flutter-Widgets-Tutorial/lib/4-appbar-fab-bottom-navigation-bar/AppBarFABDemo.dart
import 'package:flutter/material.dart'; final SnackBar snackBar = const SnackBar( content: Text("Subscribe to get more on Flutter Programming")); class AppBarFABDemo extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Tech Talks"), actions: <Widget>[ Builder( builder: (BuildContext context) { return IconButton( icon: const Icon(Icons.add_alert), tooltip: "Show Snackbar", onPressed: () { Scaffold.of(context).showSnackBar(snackBar); }, ); }, ), ], ), body: const Center( child: Text("Welcome to Flutter Tutorial"), ), floatingActionButton: FloatingActionButton( child: Icon(Icons.add), backgroundColor: Colors.green, onPressed: (){ // On press }, ), floatingActionButtonLocation: FloatingActionButtonLocation.endDocked, ); } }
0
mirrored_repositories/Complete-Flutter-Widgets-Tutorial/lib
mirrored_repositories/Complete-Flutter-Widgets-Tutorial/lib/2-basic-widgets-appbar/BasicWidgets.dart
import 'package:flutter/material.dart'; class BasicWidgets extends StatelessWidget { @override Widget build(BuildContext context) { return Material( child: Column( children: <Widget>[ MyAppBar( title: Text("Tech Talks With AK", style: Theme.of(context).primaryTextTheme.headline6), ), Expanded( child: Center( child: Text( "Subscribe this channel to get more interesting technical videos"), )) ], ), ); } } class MyAppBar extends StatelessWidget { MyAppBar({this.title}); final Widget title; @override Widget build(BuildContext context) { return Container( height: 56.0, padding: const EdgeInsets.symmetric(horizontal: 8.0), decoration: BoxDecoration(color: Colors.blue[800]), child: Row( children: <Widget>[ IconButton( icon: Icon(Icons.arrow_back), onPressed: null, tooltip: "back", disabledColor: Colors.white, ), Expanded(child: title), IconButton( icon: Icon(Icons.cast), onPressed: null, tooltip: "back", disabledColor: Colors.white, ), IconButton( icon: Icon(Icons.search), onPressed: null, tooltip: "back", disabledColor: Colors.white, ), IconButton( icon: Icon(Icons.more_vert), onPressed: null, tooltip: "back", disabledColor: Colors.white, ), ], ), ); } }
0
mirrored_repositories/Complete-Flutter-Widgets-Tutorial/lib
mirrored_repositories/Complete-Flutter-Widgets-Tutorial/lib/5-container/ContainerDemo.dart
import 'package:flutter/material.dart'; final SnackBar snackBar = const SnackBar( content: Text("Subscribe to get more on Flutter Programming")); class ContainerDemo extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Tech Talks With AK"), actions: <Widget>[ Builder( builder: (BuildContext context) { return IconButton( icon: const Icon(Icons.add_alert), tooltip: "Show Snackbar", onPressed: () { Scaffold.of(context).showSnackBar(snackBar); }, ); }, ), ], ), body: Center( child: Container( // color: Colors.green, padding: EdgeInsets.all(8.0), // constraints: BoxConstraints.expand(), // constraints: BoxConstraints(minWidth: 100, maxWidth: 200), alignment: Alignment.center, // alignment: Alignment.centerLeft, // transform: Matrix4.rotationZ(0.5), height: 200, width: 250, decoration: BoxDecoration( // color: Colors.blue, border: Border.all(color: Colors.black, width: 2.0, style: BorderStyle.solid), // borderRadius: BorderRadius.all(Radius.circular(20.0)), boxShadow: [ BoxShadow( color: Colors.red, blurRadius: 4.0, spreadRadius: 2.0, ) ], gradient: LinearGradient( begin: Alignment.centerLeft, end: Alignment.centerRight, colors: [ Colors.red, Colors.blue, ]), shape: BoxShape.circle ), child: Text( "Flutter Tutorial", style: TextStyle(fontSize: 20, color: Colors.white), )), )); } }
0
mirrored_repositories/IntelliCam
mirrored_repositories/IntelliCam/lib/main.dart
import 'package:flutter/material.dart'; import 'package:intellicam/views/camera_view.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'IntelliCam', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const CameraView(), ); } }
0
mirrored_repositories/IntelliCam/lib
mirrored_repositories/IntelliCam/lib/views/camera_view.dart
import 'dart:io'; import 'dart:typed_data'; import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:intellicam/controller/scan_controller.dart'; import '../widgets/bndbox.dart'; import 'dart:math' as math; import 'package:image/image.dart' as img; class CameraView extends StatelessWidget { const CameraView({super.key}); @override Widget build(BuildContext context) { Size screen = MediaQuery.sizeOf(context); // var tmp = screen; var screenH = math.max(screen.height, screen.width); var screenW = math.min(screen.height, screen.width); Future<Uint8List> cropImage( String imagePath, int previewH, int previewW, double x, double y, double w, double h, ) async { double scaleW, scaleH, x1, y1, w1, h1; if (screenH / screenW > previewH / previewW) { scaleW = screenH / previewH * previewW; scaleH = screenH; var difW = (scaleW - screenW) / scaleW; x1 = (x - difW / 2) * scaleW; w1 = w * scaleW; if (x < difW / 2) w1 -= (difW / 2 - x) * scaleW; y1 = y * scaleH; h1 = h * scaleH; } else { scaleH = screenW / previewW * previewH; scaleW = screenW; var difH = (scaleH - screenH) / scaleH; x1 = x * scaleW; w1 = w * scaleW; y1 = (y - difH / 2) * scaleH; h1 = h * scaleH; if (y < difH / 2) h1 -= (difH / 2 - y) * scaleH; } // Read the image from file File imageFile = File(imagePath); List<int> imageBytes = await imageFile.readAsBytes(); // Decode the image img.Image originalImage = img.decodeImage(Uint8List.fromList(imageBytes))!; // Crop the image based on coordinates and size img.Image croppedImage = img.copyCrop( originalImage, x: x1.toInt() + 165 /* math.max(0, x1).toInt() */, y: y1.toInt() + 150 /* math.max(0, y1).toInt() */, width: (w1*1.6).toInt(), height: (h1*2.0).toInt(), ); // Encode the cropped image back to bytes List<int> croppedBytes = img.encodePng(croppedImage); return Uint8List.fromList(croppedBytes); } return Scaffold( body: GetBuilder<ScanController>( init: ScanController(), builder: (controller) { var objectList = controller.results; var imageH = controller.imageHeight; var imageW = controller.imageWidth; return controller.isCameraInitialized.value ? Stack( children: [ OverflowBox( maxHeight: screenH, maxWidth: screenW, child: CameraPreview( controller.cameraController, ), ), BndBox( results: objectList, previewH: math.max(imageH, imageW), previewW: math.min(imageH, imageW), screenH: screen.height, screenW: screen.width, ), Positioned( bottom: 2, right: 2, child: FloatingActionButton( onPressed: controller.playPause, child: Icon(controller.isPlaying.value ? Icons.pause : Icons.play_arrow), ), ), Positioned( bottom: 2, left: 2, child: FloatingActionButton( onPressed: () async { var path = await controller.takePicture(); showDialog( context: context, builder: (context) { var w = objectList[0]["rect"]["w"]; var h = objectList[0]["rect"]["h"]; var x = objectList[0]["rect"]["x"]; var y = objectList[0]["rect"]["y"]; // print("width is ${w.toString()}"); // print("height is ${h.toString()}"); return Column( children: [ Center( child: FutureBuilder<Uint8List>( future: cropImage( path, math.max(imageH, imageW), math.min(imageH, imageW), x, y, w, h, ), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) { return Image.memory(snapshot.data!); } else { return const CircularProgressIndicator(); } }, ), ), ], ); }, ); }, child: const Icon(Icons.camera), ), ), ], ) : const Center(child: Text("Loading Preview...")); }, ), ); } }
0
mirrored_repositories/IntelliCam/lib
mirrored_repositories/IntelliCam/lib/widgets/bndbox.dart
// ignore_for_file: no_leading_underscores_for_local_identifiers import 'package:flutter/material.dart'; import 'dart:math' as math; class BndBox extends StatelessWidget { const BndBox({ super.key, required this.results, required this.previewH, required this.previewW, required this.screenH, required this.screenW, }); final List<dynamic> results; final int previewH; final int previewW; final double screenH; final double screenW; @override Widget build(BuildContext context) { List<Widget> renderBoxes() { return results.map((re) { var _x = re["rect"]["x"]; var _w = re["rect"]["w"]; var _y = re["rect"]["y"]; var _h = re["rect"]["h"]; double scaleW, scaleH, x, y, w, h; if (screenH / screenW > previewH / previewW) { scaleW = screenH / previewH * previewW; scaleH = screenH; var difW = (scaleW - screenW) / scaleW; x = (_x - difW / 2) * scaleW; w = _w * scaleW; if (_x < difW / 2) w -= (difW / 2 - _x) * scaleW; y = _y * scaleH; h = _h * scaleH; } else { scaleH = screenW / previewW * previewH; scaleW = screenW; var difH = (scaleH - screenH) / scaleH; x = _x * scaleW; w = _w * scaleW; y = (_y - difH / 2) * scaleH; h = _h * scaleH; if (_y < difH / 2) h -= (difH / 2 - _y) * scaleH; } return Positioned( left: math.max(0, x), top: math.max(0, y), width: w, height: h, child: Container( padding: const EdgeInsets.only(top: 5.0, left: 5.0), decoration: BoxDecoration( border: Border.all( color: const Color.fromRGBO(37, 213, 253, 1.0), width: 3.0, ), ), child: Text( "${re["detectedClass"]} ${(re["confidenceInClass"] * 100).toStringAsFixed(0)}%", style: const TextStyle( color: Color.fromRGBO(37, 213, 253, 1.0), fontSize: 14.0, fontWeight: FontWeight.bold, ), ), ), ); }).toList(); } return Stack( children: renderBoxes(), ); } }
0
mirrored_repositories/IntelliCam/lib
mirrored_repositories/IntelliCam/lib/controller/scan_controller.dart
// ignore_for_file: avoid_print import 'package:flutter/widgets.dart'; import 'package:get/get.dart'; import 'package:camera/camera.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:tflite_v2/tflite_v2.dart'; // import 'package:path/path.dart' as path; class ScanController extends GetxController { @override void onInit() { super.onInit(); initCamera(); initTfLite(); } @override void dispose() { super.dispose(); cameraController.dispose(); } late CameraController cameraController; late List<CameraDescription> cameras; var imageHeight = 0, imageWidth = 0; Size previewSize = const Size(0, 0); var isCameraInitialized = false.obs; var cameraCount = 0; var isPlaying = true.obs; List<dynamic> results = []; initCamera() async { if (await Permission.camera.request().isGranted) { cameras = await availableCameras(); cameraController = CameraController( cameras[0], //Rear Camera ResolutionPreset.high, ); await cameraController.initialize().then((value) { //for every 10th frame cameraController.startImageStream((image) { cameraCount++; if (cameraCount % 10 == 0) { cameraCount = 0; imageHeight = image.height; imageWidth = image.width; previewSize = cameraController.value.previewSize!; objectDetector(image); } update(); }); update(); }); isCameraInitialized(true); isPlaying(true); update(); } else { print("Permission denied!"); } } initTfLite() async { await Tflite.loadModel( model: 'assets/ssd_mobilenet.tflite', labels: 'assets/ssd_mobilenet.txt', isAsset: true, numThreads: 1, useGpuDelegate: false, ); } playPause() { if (cameraController.value.isInitialized) { if (isPlaying.value) { cameraController.pausePreview(); isPlaying(false); } else { cameraController.resumePreview(); isPlaying(true); } update(); } } takePicture() async { if (cameraController.value.isInitialized) { var image = await cameraController.takePicture(); await cameraController.pausePreview(); isPlaying(false); update(); print("Image path is ${image.path}"); return image.path; } } objectDetector(CameraImage image) async { var detector = await Tflite.detectObjectOnFrame( bytesList: image.planes.map((e) => e.bytes).toList(), asynch: true, model: "SSDMobileNet", imageHeight: image.height, imageWidth: image.width, imageMean: 127.5, imageStd: 127.5, rotation: 90, threshold: 0.4, numResultsPerClass: 1, ); if (detector != null && detector.isNotEmpty) { results = detector; print("Result is $results"); update(); } } }
0
mirrored_repositories/Smiley-Rating-Dialog
mirrored_repositories/Smiley-Rating-Dialog/lib/smiley_painter.dart
import 'package:flutter/material.dart'; import 'dart:math' as Math; class SmileyPainter extends CustomPainter { final int rating; SmileyPainter({this.rating}); @override void paint(Canvas canvas, Size size) { final radius = Math.min(size.width, size.height) / 2; final center = Offset(size.width / 2, size.height / 2); switch (rating) { case 1: drawAngryFace(canvas, radius, center); break; case 2: drawSadFace(canvas, radius, center); break; case 3: drawNeutralFace(canvas, radius, center); break; case 4: drawSmileyFace(canvas, radius, center, size); break; case 5: drawWideSmileyFace(canvas, radius, center, size); break; break; default: drawSmileyFace(canvas, radius, center, size); } } @override bool shouldRepaint(CustomPainter oldDelegate) => false; void drawSmileyFace(Canvas canvas, double radius, Offset center, Size size) { // Draw the body final paint = Paint()..color = Colors.lightGreen; canvas.drawCircle(center, radius, paint); // Draw the mouth final smilePaint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 5; var startPoint =Offset(25.0, size.height / 2 + 10.0); var firstControlPoint =Offset(size.width / 4, size.height / 2 + 35.0); var secondControlPoint =Offset(3 * size.width / 4, size.height /2 + 35.0); var endPoint =Offset(size.width - 25.0, size.height / 2 + 10.0); var path =Path(); path.moveTo(startPoint.dx, startPoint.dy); path.cubicTo(firstControlPoint.dx, firstControlPoint.dy, secondControlPoint.dx, secondControlPoint.dy, endPoint.dx, endPoint.dy); canvas.drawPath(path, smilePaint); // Draw the eyes canvas.drawCircle( Offset(center.dx - radius / 2 , center.dy - radius / 2 + 10.0), 8, Paint()); canvas.drawCircle( Offset(center.dx + radius / 2 , center.dy - radius / 2 + 10.0), 8, Paint()); } void drawSadFace(Canvas canvas, double radius, Offset center) { // Draw the body final paint = Paint()..color = Colors.orange; canvas.drawCircle(center, radius, paint); // Draw the mouth final smilePaint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 5; canvas.drawArc( Rect.fromCircle(center: center + Offset(0.0, 30.0), radius: radius / 2), 0, -Math.pi, false, smilePaint); // Draw the eyes canvas.drawCircle( Offset(center.dx - radius / 2 , center.dy - radius / 2 + 10.0), 8, Paint()); canvas.drawCircle( Offset(center.dx + radius / 2 , center.dy - radius / 2 + 10.0), 8, Paint()); } void drawAngryFace(Canvas canvas, double radius, Offset center) { // Draw the body final paint = Paint()..color = Colors.red; canvas.drawCircle(center, radius, paint); // Draw the mouth final smilePaint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 5; canvas.drawArc( Rect.fromCircle(center: center + Offset(0.0, 30.0), radius: radius / 2), 0, -Math.pi, false, smilePaint); canvas.drawLine(Offset(center.dx - radius + 20 , center.dy - radius / 1.5 +5), Offset(center.dx - radius / 3.5 , center.dy - radius / 3), smilePaint); canvas.drawLine(Offset(center.dx + radius / 2 + 10, center.dy - radius / 2 - 5), Offset(center.dx + radius / 3, center.dy - radius / 3), smilePaint); // Draw the eyes canvas.drawCircle( Offset(center.dx - radius / 2 , center.dy - radius / 2 + 10.0), 8, Paint()); canvas.drawCircle( Offset(center.dx + radius / 2 , center.dy - radius / 2 + 10.0), 8, Paint()); } void drawNeutralFace(Canvas canvas, double radius, Offset center) { // Draw the body final paint = Paint()..color = Colors.yellow; canvas.drawCircle(center, radius, paint); // Draw the mouth final smilePaint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 5; canvas.drawLine(Offset(center.dx - radius / 2, center.dy + radius /4 ), Offset(center.dx + radius / 2, center.dy + radius / 4), smilePaint); // Draw the eyes canvas.drawCircle( Offset(center.dx - radius / 2 , center.dy - radius / 2 + 10.0), 8, Paint()); canvas.drawCircle( Offset(center.dx + radius / 2 , center.dy - radius / 2 + 10.0), 8, Paint()); } void drawWideSmileyFace(Canvas canvas, double radius, Offset center, Size size) { // Draw the body final paint = Paint()..color = Colors.green; canvas.drawCircle(center, radius, paint); // Draw the mouth final smilePaint = Paint() ..style = PaintingStyle.fill ..strokeWidth = 5; canvas.drawArc(Rect.fromCircle(center: center + Offset(0.0, 10.0), radius: radius / 2), 0, Math.pi, false, smilePaint); // Draw the eyes canvas.drawCircle( Offset(center.dx - radius / 2 , center.dy - radius / 2 + 10.0), 8, Paint()); canvas.drawCircle( Offset(center.dx + radius / 2 , center.dy - radius / 2 + 10.0), 8, Paint()); } }
0
mirrored_repositories/Smiley-Rating-Dialog
mirrored_repositories/Smiley-Rating-Dialog/lib/smiley_rating_dialog.dart
library smiley_rating_dialog; import 'package:flutter/material.dart'; import 'package:smiley_rating_dialog/smiley_painter.dart'; class SmileyRatingDialog extends StatefulWidget { // Color of star buttons final Color starColor; // Called when positive button is clicked final ValueSetter<int> onSubmitPressed; // Called when negative button is clicked final VoidCallback onCancelPressed; // Text of Positive Button final String positiveButtonText; // Text of Positive Button final String negativeButtonText; // Color of Positive Button final Color positiveButtonColor; // Color of Positive Button final Color negativeButtonColor; // Title of Dialog final Widget title; // Whether the corners of the buttons should be rounded or not final bool isRoundedButtons; SmileyRatingDialog( {this.starColor = Colors.yellow, this.title, @required this.onSubmitPressed, @required this.onCancelPressed, @required this.positiveButtonText, @required this.negativeButtonText, this.isRoundedButtons = true, this.positiveButtonColor = Colors.amber, this.negativeButtonColor = Colors.amber}); @override _SmileyRatingDialogState createState() => _SmileyRatingDialogState(); } class _SmileyRatingDialogState extends State<SmileyRatingDialog> { int _rating = 0; List<Widget> _starWidgets() { List<Widget> buttons = []; for (int rateValue = 1; rateValue <= 5; rateValue++) { final starRatingButton = IconButton( icon: Icon(_rating >= rateValue ? Icons.star : Icons.star_border, color: widget.starColor, size: 35), onPressed: () { setState(() { _rating = rateValue; }); }); buttons.add(starRatingButton); } return buttons; } @override Widget build(BuildContext context) { return AlertDialog( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)), title: widget.title, contentPadding: EdgeInsets.all(20.0), content: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Container( width: 100.0, height: 100.0, child: CustomPaint( painter: SmileyPainter(rating: _rating), ), ), Row(children: _starWidgets()), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ FlatButton( shape: BeveledRectangleBorder( borderRadius: BorderRadius.circular( widget.isRoundedButtons ? 4.0 : 0.0)), color: widget.positiveButtonColor, onPressed: () { widget.onSubmitPressed(_rating); }, child: Text(widget.positiveButtonText), ), FlatButton( shape: BeveledRectangleBorder( borderRadius: BorderRadius.circular( widget.isRoundedButtons ? 4.0 : 0.0)), color: widget.negativeButtonColor, onPressed: () { widget.onCancelPressed(); }, child: Text(widget.negativeButtonText), ), ], ) ], ), ); } }
0
mirrored_repositories/Smiley-Rating-Dialog
mirrored_repositories/Smiley-Rating-Dialog/test/smiley_rating_dialog_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:smiley_rating_dialog/smiley_rating_dialog.dart'; void main() { test('adds one to input values', () { final calculator = Calculator(); expect(calculator.addOne(2), 3); expect(calculator.addOne(-7), -6); expect(calculator.addOne(0), 1); expect(() => calculator.addOne(null), throwsNoSuchMethodError); }); }
0
mirrored_repositories/Smiley-Rating-Dialog/example
mirrored_repositories/Smiley-Rating-Dialog/example/lib/main.dart
import 'package:flutter/material.dart'; import 'package:smiley_rating_dialog/smiley_rating_dialog.dart'; void main() => runApp(MaterialApp( debugShowCheckedModeBanner: false, home: HomeScreen(), )); class HomeScreen extends StatefulWidget { @override _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { @override Widget build(BuildContext context) { return Center( child: RaisedButton( onPressed: () { showDialog( barrierDismissible: true, context: context, builder: (context) => SmileyRatingDialog( title: Text('Smiley Dialog'), starColor: Colors.red, isRoundedButtons: true, positiveButtonText: 'Ok', negativeButtonText: 'Cancel', positiveButtonColor: Colors.amber, negativeButtonColor: Colors.amber, onCancelPressed: () => Navigator.pop(context), onSubmitPressed: (rating) {}, )); }, child: Text('Show Dialog'), ), ); } }
0
mirrored_repositories/Basic-Banking-APP
mirrored_repositories/Basic-Banking-APP/lib/allcustomers.dart
import 'package:basicbankingapp/alltransactions.dart'; import 'package:flutter/material.dart'; import 'customerprofile.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; class Allcustomers extends StatefulWidget { @override _AllcustomersState createState() => _AllcustomersState(); } class _AllcustomersState extends State<Allcustomers> { TextStyle _textStyle(double x) { return TextStyle( fontSize: x, fontWeight: FontWeight.w600, color: Colors.white); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color.fromRGBO(32, 132, 113, 1), centerTitle: true, title: Text( 'All Customers', style: (TextStyle(fontSize: 30, fontWeight: FontWeight.w500)), ), actions: [ IconButton( padding: EdgeInsets.only(right: 20), icon: Icon( Icons.fast_forward_outlined, size: 30, ), onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return AllTransactions(); })); }) ], ), backgroundColor: Colors.white, body: WillPopScope( onWillPop: () { return Navigator.popAndPushNamed(context, '/home'); }, child: StreamBuilder<QuerySnapshot>( stream: FirebaseFirestore.instance .collection("customers") .snapshots(), builder: (context, snapshot) { return !snapshot.hasData ? Center(child: CircularProgressIndicator()) : ListView.builder( itemCount: snapshot.data.docs.length, itemBuilder: (context, index) { DocumentSnapshot data = snapshot.data.docs[index]; return GestureDetector( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return CustomerProfile( name: data['name'], email: data['email'], customerid: data['customerid'], currentbalance: data['currentbalance'], tid: data.id, accountno: data['account'], ); })); }, child: Container( margin: EdgeInsets.all(30), padding: EdgeInsets.all(10), decoration: BoxDecoration( color: Color.fromRGBO(32, 132, 113, 1), boxShadow: [ BoxShadow( color: Colors.black38, // soften the shadow spreadRadius: 5.0, //extend the shadow offset: Offset( 8.0, // Move to right 10 horizontally 9.0, // Move to bottom 10 Vertically ), ) ], ), child: ListTile( leading: Icon(Icons.view_list, color: Colors.white), title: Text( data['name'], maxLines: 1, style: _textStyle(25), ), subtitle: Text( data['email'], style: _textStyle(15), ), trailing: Text( "₹ " + data['currentbalance'].toString(), style: _textStyle(20)), ), ), ); }); }), )); } }
0
mirrored_repositories/Basic-Banking-APP
mirrored_repositories/Basic-Banking-APP/lib/choosecustomer.dart
import 'package:basicbankingapp/transfermoney.dart'; import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'models/customermodel.dart'; class ChooseCustomer extends StatefulWidget { final String tname; final String temail; final int tcurrentbalance; final int tcustomerid; final tid; ChooseCustomer( {this.tname, this.tcustomerid, this.temail, this.tcurrentbalance,this.tid}); @override _ChooseCustomerState createState() => _ChooseCustomerState(); } class _ChooseCustomerState extends State<ChooseCustomer> { TextStyle _textStyle(double x) { return TextStyle( fontSize: x, fontWeight: FontWeight.w600, color: Colors.white); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color.fromRGBO(32, 132, 113, 1), centerTitle: true, title: Text( 'Choose Customers', style: (TextStyle(fontSize: 30, fontWeight: FontWeight.w500)), ), ), backgroundColor: Colors.white, body: StreamBuilder<QuerySnapshot>( stream: FirebaseFirestore.instance.collection("customers").snapshots(), builder: (context, snapshot) { return !snapshot.hasData ? Center(child: CircularProgressIndicator()) : ListView.builder( itemCount: snapshot.data.docs.length, itemBuilder: (context, index) { DocumentSnapshot data = snapshot.data.docs[index]; return GestureDetector( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return Transfermoney( widget.tname, widget.tcustomerid, widget.tcurrentbalance, widget.tid, data['name'], data['customerid'], data['currentbalance'], data.id); })); }, child: Container( margin: EdgeInsets.all(30), padding: EdgeInsets.all(10), decoration: BoxDecoration( color: Color.fromRGBO(32, 132, 113, 1), boxShadow: [ BoxShadow( color: Colors.black38, // soften the shadow spreadRadius: 5.0, //extend the shadow offset: Offset( 8.0, // Move to right 10 horizontally 9.0, // Move to bottom 10 Vertically ), ) ], ), child: ListTile( leading: Icon(Icons.view_list, color: Colors.white), title: Text( data['name'], maxLines: 1, style: _textStyle(25), ), subtitle: Text( data['email'], style: _textStyle(15), ), trailing: Text( "₹ " + data['currentbalance'].toString(), style: _textStyle(20)), ), ), ); }); })); } }
0
mirrored_repositories/Basic-Banking-APP
mirrored_repositories/Basic-Banking-APP/lib/myhomepage.dart
import 'package:flutter/material.dart'; import 'allcustomers.dart'; class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color.fromRGBO(32, 132, 113, 1), body: SingleChildScrollView( child: Center( child: Column( children: [ SizedBox( height: 100, ), Container( height: 250, width: 250, padding: EdgeInsets.all(10), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(122.5)), child: CircleAvatar( backgroundColor: Colors.white, onBackgroundImageError: (exception, stackTrace) => Text( 'BBA', style: TextStyle( fontSize: 15, color: Color.fromRGBO(32, 132, 113, 1)), ), backgroundImage: AssetImage( "assets/images/HomeScreen.jpg", ), ), ), SizedBox(height: 50), Text( " Basic Banking", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 50, foreground: Paint() ..style = PaintingStyle.stroke ..strokeWidth = 2 ..color = Colors.white, ), ), Text( 'App', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 50, foreground: Paint() ..style = PaintingStyle.stroke ..strokeWidth = 2 ..color = Colors.white, ), ), SizedBox( height: 20, ), Card( elevation: 10, color: Colors.white, child: IconButton( icon: Icon(Icons.arrow_forward), iconSize: 50, color: Color.fromRGBO(32, 132, 113, 1), onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return Allcustomers(); })); }), ) ], ), ), ), ); } }
0
mirrored_repositories/Basic-Banking-APP
mirrored_repositories/Basic-Banking-APP/lib/alltransactions.dart
import 'package:flutter/material.dart'; import 'customerprofile.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; class AllTransactions extends StatefulWidget { @override _AllTransactionsState createState() => _AllTransactionsState(); } class _AllTransactionsState extends State<AllTransactions> { TextStyle _passorfail(String status){ if (status=='Success'){ return TextStyle( fontSize:22, fontWeight: FontWeight.w600, color: Colors.green); } else{ return TextStyle( fontSize:20, fontWeight: FontWeight.w600, color: Colors.red); } } TextStyle _textStyle(double x) { return TextStyle( fontSize: x, fontWeight: FontWeight.w600, color: Colors.white); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color.fromRGBO(32, 132, 113, 1), centerTitle: true, title: Text( 'All Transactions', style: (TextStyle(fontSize: 30, fontWeight: FontWeight.w500)), ), ), backgroundColor: Colors.white, body: StreamBuilder<QuerySnapshot>( stream: FirebaseFirestore.instance .collection("transactions") .snapshots(), builder: (context, snapshot) { return !snapshot.hasData ? Center( child: CircularProgressIndicator()) : ListView.builder( itemCount: snapshot.data.docs.length, itemBuilder: (context, index) { DocumentSnapshot data = snapshot.data.docs[index]; return Container( margin: EdgeInsets.all(5), padding: EdgeInsets.all(3), decoration: BoxDecoration( color: Color.fromRGBO(32, 132, 113, 1), boxShadow: [ BoxShadow( color: Colors.black38, // soften the shadow spreadRadius: 5.0, //extend the shadow offset: Offset( 8.0, // Move to right 10 horizontally 9.0, // Move to bottom 10 Vertically ), ) ], ), child: ListTile( title: Text( data['tname'] + " >> " + data['rname'], style: _textStyle(24), ), subtitle: Text( data['Date'], style: _textStyle(18), ), trailing: Column( children: [ Text( " ₹ "+data['Amount'], style: _textStyle(22), ), Text( data['Status'], style: _passorfail( data['Status']), ) ], ), ), ); }); })); } }
0
mirrored_repositories/Basic-Banking-APP
mirrored_repositories/Basic-Banking-APP/lib/transfermoney.dart
import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:intl/intl.dart'; class Transfermoney extends StatefulWidget { String tname; int tcustomerid; int tcurrentbalance; String rname; int rcustomerid; int rcurrentbalance; var tid; var rid; Transfermoney(this.tname, this.tcustomerid, this.tcurrentbalance, this.tid, this.rname, this.rcustomerid, this.rcurrentbalance, this.rid); @override _TransfermoneyState createState() => _TransfermoneyState(); } class _TransfermoneyState extends State<Transfermoney> { showAlertDialog(BuildContext context, String content) { // set up the button Widget okButton = FlatButton( child: Text("OK"), onPressed: () { amountcontroller.text = ''; Navigator.of(context).pop(); }, ); // set up the AlertDialog AlertDialog alert = AlertDialog( title: Text("Alert"), content: Text(content), actions: [ okButton, ], ); // show the dialog showDialog( context: context, builder: (BuildContext context) { return alert; }, ); } TextStyle _textStyle(double x) { return TextStyle( fontSize: x, fontWeight: FontWeight.w600, color: Colors.white); } TextEditingController amountcontroller = new TextEditingController(); var trans = 0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color.fromRGBO(32, 132, 113, 1), title: Text('Transfer Money', style: (TextStyle(fontSize: 30, fontWeight: FontWeight.w500))), ), backgroundColor: Colors.white, body: SingleChildScrollView( child: Column( children: [ Container( margin: EdgeInsets.all(30), padding: EdgeInsets.all(10), decoration: BoxDecoration( color: Color.fromRGBO(32, 132, 113, 1), boxShadow: [ BoxShadow( color: Colors.black38, // soften the shadow spreadRadius: 5.0, //extend the shadow offset: Offset( 8.0, // Move to right 10 horizontally 9.0, // Move to bottom 10 Vertically ), ) ], ), child: ListTile( title: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Expanded( flex: 1, child: Text( '${widget.tname}', maxLines: 1, style: _textStyle(23), ), ), Expanded( flex: 1, child: Icon( Icons.double_arrow, color: Colors.white, ), ), Expanded( flex: 1, child: Text( '${widget.rname}', maxLines: 2, style: _textStyle(22), ), ), ], ), ), ), SizedBox( height: 20, ), Text( 'Current Balance : ${widget.tcurrentbalance}', style: TextStyle( color: Color.fromRGBO(32, 132, 113, 1), fontSize: 24), ), SizedBox( height: 10, ), Text( 'Enter amount:', style: TextStyle( color: Color.fromRGBO(32, 132, 113, 1), fontSize: 35, fontWeight: FontWeight.w800), ), Container( margin: EdgeInsets.all(30), child: TextField( keyboardType: TextInputType.number, controller: amountcontroller, decoration: InputDecoration( labelText: 'Amount', border: OutlineInputBorder( borderRadius: BorderRadius.circular(2), )), onSubmitted: (value) { Widget yesButton = FlatButton( color: Colors.blue, child: Text( "Yes", style: TextStyle(fontSize: 15), ), onPressed: () { trans++; FirebaseFirestore.instance.collection("transactions"). doc().set( { "tname": widget.tname, "rname": widget.rname, "Date": DateFormat().format(DateTime.now()), "Amount": amountcontroller.text.toString(), "Status": "Success"}); FirebaseFirestore.instance .collection("customers") .doc(widget.rid) .update({ "currentbalance": widget.rcurrentbalance + int.parse(amountcontroller.text) }); FirebaseFirestore.instance .collection("customers") .doc(widget.tid) .update({ "currentbalance": widget.tcurrentbalance - int.parse(amountcontroller.text) }); Navigator.popAndPushNamed(context, '/all'); AlertDialog al = AlertDialog( title: Text("Alert"), content: Text('Transaction Succesfull.')); showDialog( context: context, builder: (BuildContext context) { return al; }, ); }, ); Widget noButton = FlatButton( color: Colors.blue, child: Text( "No", style: TextStyle(fontSize: 15), ), onPressed: () { trans++; FirebaseFirestore.instance.collection("transactions"). doc().set( { "tname": widget.tname, "rname": widget.rname, "Date": DateFormat().format(DateTime.now()), "Amount": amountcontroller.text.toString(), "Status": "Failed"}); AlertDialog al = AlertDialog( title: Text("Alert"), content: Text('Transaction Cancelled.')); showDialog( context: context, builder: (BuildContext context) { return al; }, ); Navigator.popAndPushNamed(context, '/all'); }, ); AlertDialog alert = AlertDialog( title: Text("Alert"), content: Text('Are you sure?'), actions: [yesButton, noButton], ); // show the dialog showDialog( context: context, builder: (BuildContext context) { return alert; }, ); }, onChanged: (value) { if (int.parse(value) > widget.tcurrentbalance) { return showAlertDialog(context, "Insufficient Balance.\n You have ${widget.tcurrentbalance}"); } }, ), ) ], ), ), ); } }
0
mirrored_repositories/Basic-Banking-APP
mirrored_repositories/Basic-Banking-APP/lib/customerprofile.dart
import 'package:basicbankingapp/choosecustomer.dart'; import 'package:flutter/material.dart'; class CustomerProfile extends StatelessWidget { final String name; final String email; final int currentbalance; final int customerid; final tid; final accountno; CustomerProfile( {this.name, this.customerid, this.email, this.currentbalance, this.tid,this.accountno}); TextStyle texttheme() { return TextStyle( fontSize: 20, fontWeight: FontWeight.w700, color: Color.fromRGBO(32, 132, 113, 1)); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color.fromRGBO(32, 132, 113, 1), title: Text( name, style: TextStyle(fontSize: 25), ), ), backgroundColor: Color.fromRGBO(32, 132, 113, 1), body: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ SizedBox( height: 10, ), Container( height: 200, width: 200, padding: EdgeInsets.all(10), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(100)), child: CircleAvatar( backgroundColor: Colors.white, onBackgroundImageError: (exception, stackTrace) => Text( 'CP', style: TextStyle( fontSize: 15, color: Color.fromRGBO(32, 132, 113, 1)), ), backgroundImage: AssetImage( "assets/images/profile.jpg", ), ), ), SizedBox( height: 10, ), SizedBox( height: 300, width: 400, child: Card( margin: EdgeInsets.all(30), elevation: 5, color: Colors.white, child: Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("Name : $name", style: texttheme()), Text("Customer ID : ${customerid.toString()}", style: texttheme()), Text("Account Number : $accountno", style: texttheme()), Text("Email : $email", style: texttheme()), Text("Current Balance : ₹ $currentbalance", style: texttheme()), ], ), ), ), ), Container( height: 70, width: 200, padding: EdgeInsets.all(10), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(35)), child: GestureDetector( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return ChooseCustomer( tname: name, tcurrentbalance: currentbalance, tcustomerid: customerid, temail: email, tid: tid, ); })); }, child: Container( decoration: BoxDecoration( color: Color.fromRGBO(32, 132, 113, 1), borderRadius: BorderRadius.circular(30)), child: Center( child: Text( 'Transfer', style: TextStyle( color: Colors.white, fontSize: 35, fontWeight: FontWeight.w600), ), ), ), )), SizedBox( height: 10, ) ], ), ), ); } }
0
mirrored_repositories/Basic-Banking-APP
mirrored_repositories/Basic-Banking-APP/lib/main.dart
import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'allcustomers.dart'; import 'dart:async'; import 'myhomepage.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Basic Banking App', theme: ThemeData( primaryColor: Color.fromRGBO(32, 132, 113, 1), ), initialRoute: '/', routes: { '/': (BuildContext context) => MyHomePage(), '/all': (BuildContext context) => Allcustomers(), 'home':(BuildContext context) => HomeScreen(), }, ); } } class MyHomePage extends StatefulWidget { @override SplashScreenState createState() => SplashScreenState(); } class SplashScreenState extends State<MyHomePage> { @override void initState() { super.initState(); Timer( Duration(seconds: 5), () => Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => HomeScreen()))); } @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( backgroundColor: Color.fromRGBO(32, 132, 113, 1), body: Center( child: SizedBox( height: 300, width: 300, child: CircleAvatar( backgroundImage: AssetImage( "assets/images/HomeScreen.jpg", ), ), ), ), )); } }
0
mirrored_repositories/Basic-Banking-APP/lib
mirrored_repositories/Basic-Banking-APP/lib/models/customermodel.dart
class Customermodel { String name; String email; int currentbalance; int customerid; Customermodel({this.name,this.customerid,this.email,this.currentbalance}); }
0
mirrored_repositories/GDSC-Flutter-Flourish-D2
mirrored_repositories/GDSC-Flutter-Flourish-D2/lib/model.dart
//Automatic Generated Model Class import 'dart:convert'; List<SamplePosts> samplePostsFromJson(String str) => List<SamplePosts>.from( json.decode(str).map((x) => SamplePosts.fromJson(x))); String samplePostsToJson(List<SamplePosts> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson()))); class SamplePosts { int userId; int id; String title; String body; SamplePosts({ required this.userId, required this.id, required this.title, required this.body, }); factory SamplePosts.fromJson(Map<String, dynamic> json) => SamplePosts( userId: json["userId"], id: json["id"], title: json["title"], body: json["body"], ); Map<String, dynamic> toJson() => { "userId": userId, "id": id, "title": title, "body": body, }; }
0
mirrored_repositories/GDSC-Flutter-Flourish-D2
mirrored_repositories/GDSC-Flutter-Flourish-D2/lib/main.dart
import 'package:flutter/material.dart'; import './home.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Learning API', debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( leading: const Icon(Icons.code), centerTitle: true, title: const Text( 'Flutter Flourish Day 2', style: TextStyle(fontWeight: FontWeight.w300, fontSize: 25), ), ), body: const HomePage(), )); } } /* Steps I have performed to use API -->Most imp added http package dependencies to yaml. 1. API - took the fake data from 'https://jsonplaceholder.typicode.com/posts' 2. Tested the API is giving response properly or not from 'https://web.postman.co/' 3. Autogenerated the code for model class from 'https://app.quicktype.io/'. Just copied the body from the postman that was tested and paste. 4.Created a List to getData using async & await. */
0
mirrored_repositories/GDSC-Flutter-Flourish-D2
mirrored_repositories/GDSC-Flutter-Flourish-D2/lib/home.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import './model.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { //List to store the data from the API. List<SamplePosts> samplePosts = []; @override Widget build(BuildContext context) { //Future builder helps to fetch data till the data gets from the server. return FutureBuilder( future: getData(), builder: (context, snapshot) { if (snapshot.hasData) { return ListView.builder( itemCount: samplePosts.length, itemBuilder: (context, index) { return Container( decoration: BoxDecoration( color: Colors.greenAccent, borderRadius: BorderRadius.circular(10)), height: 130, margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 10), padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'User id: ${samplePosts[index].userId}', style: const TextStyle(fontSize: 18), ), Text( 'ID: ${samplePosts[index].id}', style: const TextStyle(fontSize: 18), ), Text( 'Title: ${samplePosts[index].title}', maxLines: 1, style: const TextStyle(fontSize: 18), ), Text( 'Body: ${samplePosts[index].body}', maxLines: 1, style: const TextStyle(fontSize: 18), ), ], ), ); }, ); } else { return const Center(child: CircularProgressIndicator()); } }, ); } //This function helps to fetch data from the server. Future<List<SamplePosts>> getData() async { final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts')); var data = jsonDecode(response.body.toString()); if (response.statusCode == 200) { for (Map<String, dynamic> index in data) { samplePosts.add(SamplePosts.fromJson(index)); } return samplePosts; } else { return samplePosts; } } }
0
mirrored_repositories/GDSC-Flutter-Flourish-D2
mirrored_repositories/GDSC-Flutter-Flourish-D2/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:api_day/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/First-Flutter-App/First_App
mirrored_repositories/First-Flutter-App/First_App/lib/main.dart
import 'package:flutter/material.dart'; import 'ui/home.dart'; void main() { runApp(myapp()); }
0
mirrored_repositories/First-Flutter-App/First_App/lib
mirrored_repositories/First-Flutter-App/First_App/lib/ui/home.dart
import 'package:flutter/material.dart'; myapp() { //text to be printed in my main body var mytext = Text( "Beyblade Burst", textDirection: TextDirection.ltr, textAlign: TextAlign.center, ); //functions to events, when the iconbutton/button is pressed mypress() { print("Clicked Mail......."); } mypress2() { print("Clicked Alarm......."); } //Icons - elements which act as thumbnails, but don't have any functionalities of button var myemailicon = Icon( Icons.email, color: Colors.yellow, ); var myalarmicon = Icon( Icons.access_alarm, color: Colors.black, ); var mycallicon = Icon( Icons.call, color: Colors.blue, ); //IconButton - icons, which can act as buttons, perform events when they are pressed or some other action is done var myemailbutton = IconButton( icon: myemailicon, onPressed: mypress, ); var myalarmbutton = IconButton( icon: myalarmicon, onPressed: mypress2, ); //AppBar - the top bar which appears in the android apps //can have text, images, icons, iconbuttons, etc. var myappbar = AppBar( title: mytext, backgroundColor: Colors.red, //leading: Text('Divam'), leading: mycallicon, actions: <Widget>[myemailbutton, myalarmbutton], ); //url var url = 'https://vignette.wikia.nocookie.net/beyblade/images/1/18/Beyblade_Burst_Superking_Rage_Longinus_Destroy%27_3A_avatar_25.png/revision/latest/top-crop/width/220/height/220?cb=20200619223546'; //Image - used to get an image and put it in the app //can adjust size, borders, orientation etc. var myimage = Image.network( url, width: double.infinity, height: double.infinity, ); //main app //Scaffold - a pre-designed framework in flutter var myhome = Scaffold( appBar: myappbar, //body: Center(child: Text('Helix Dragonoid MK3')), body: myimage, backgroundColor: Colors.grey.shade400, ); //MaterialApp - the pre-defined class for flutter apps //It is likely the main or core component of flutter. //We can access all the other components and widgets provided by Flutter SDK. //Text widget, Dropdownbutton widget, AppBar widget, Scaffold widget, ListView widget, StatelessWidget, StatefulWidget, //IconButton widget, TextField widget, Padding widget, ThemeData widget, etc. are the widgets that can be accessed using MaterialApp class. var design = MaterialApp( home: myhome, debugShowCheckedModeBanner: false, ); return design; }
0
mirrored_repositories/First-Flutter-App/First_App
mirrored_repositories/First-Flutter-App/First_App/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:First_App/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Wordle-Flutter
mirrored_repositories/Wordle-Flutter/lib/main.dart
import 'package:flutter/material.dart'; import 'package:wordle/app/app.dart'; void main() { runApp(const App()); }
0
mirrored_repositories/Wordle-Flutter/lib
mirrored_repositories/Wordle-Flutter/lib/app/app.dart
import 'package:flutter/material.dart'; import 'package:wordle/feature/wordle/views/wordle.screen.dart'; class App extends StatelessWidget { const App({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Wordle App', debugShowCheckedModeBanner: false, theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: Colors.black), home: const WordleScreen(), ); } }
0
mirrored_repositories/Wordle-Flutter/lib
mirrored_repositories/Wordle-Flutter/lib/app/app.colors.dart
import 'package:flutter/cupertino.dart'; const Color correctColor = Color(0xFF538D4E); const Color inWordColor = Color(0xFFb49F3A); const Color notInWordColor = Color(0xFF3A3A3C);
0
mirrored_repositories/Wordle-Flutter/lib/feature/wordle
mirrored_repositories/Wordle-Flutter/lib/feature/wordle/views/wordle.screen.dart
import 'dart:math'; import 'package:flip_card/flip_card.dart'; import 'package:flutter/material.dart'; import 'package:wordle/app/app.colors.dart'; import 'package:wordle/feature/wordle/data/word_list.dart'; import 'package:wordle/feature/wordle/models/letter.model.dart'; import 'package:wordle/feature/wordle/models/word.model.dart'; import 'package:wordle/feature/wordle/widgets/board.dart'; import 'package:wordle/feature/wordle/widgets/keyboard.dart'; enum GameStatus { playing, submitting, lost, won } class WordleScreen extends StatefulWidget { const WordleScreen({Key? key}) : super(key: key); @override State<WordleScreen> createState() => _WordleScreenState(); } class _WordleScreenState extends State<WordleScreen> { GameStatus _gameStatus = GameStatus.playing; final List<Word> _board = List.generate( 6, (_) => Word( letters: List.generate( 5, (_) => Letter.empty(), ), ), ); final List<List<GlobalKey<FlipCardState>>> _flipCardKeys = List.generate( 6, (_) => List.generate( 5, (_) => GlobalKey<FlipCardState>(), ), ); int _currWordIndex = 0; Word? get _currentWord => _currWordIndex < _board.length ? _board[_currWordIndex] : null; Word _solution = Word.fromString( fiveLetterWords[Random().nextInt(fiveLetterWords.length)].toUpperCase(), ); final Set<Letter> _keyboardLetter = {}; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: Colors.transparent, elevation: 0, title: const Text( "WORDLE", style: TextStyle( fontSize: 36, fontWeight: FontWeight.bold, letterSpacing: 4, ), ), ), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Board(board: _board, flipCardKeys: _flipCardKeys), const SizedBox( height: 80, ), Keyboard( onKeyTapped: onKeyTapped, onDeleteTapped: onDeleteTapped, letters: _keyboardLetter, onEnterTapped: onEnterTapped, ) ], ), ); } void onKeyTapped(String val) { if (_gameStatus == GameStatus.playing) { setState( () => _currentWord?.addLetter(val), ); } } void onDeleteTapped() { if (_gameStatus == GameStatus.playing) { setState(() => _currentWord?.removeLetter()); } } Future<void> onEnterTapped() async { if (_gameStatus == GameStatus.playing && _currentWord != null && !_currentWord!.letters.contains( Letter.empty(), )) { _gameStatus = GameStatus.submitting; for (var i = 0; i < _currentWord!.letters.length; i++) { final currWordLetter = _currentWord!.letters[i]; final currSolLetter = _solution.letters[i]; setState( () { if (currWordLetter == currSolLetter) { _currentWord!.letters[i] = currWordLetter.copyWith(status: LetterStatus.correct); } else if (_solution.letters.contains(currWordLetter)) { _currentWord!.letters[i] = currWordLetter.copyWith(status: LetterStatus.inWord); } else { _currentWord!.letters[i] = currWordLetter.copyWith(status: LetterStatus.notInWord); } }, ); final letter = _keyboardLetter.firstWhere( (e) => e.val == currWordLetter.val, orElse: () => Letter.empty(), ); if (letter.status != LetterStatus.correct) { _keyboardLetter.remove((e) => e.val == currWordLetter.val); _keyboardLetter.add(_currentWord!.letters[i]); } await Future.delayed( const Duration(milliseconds: 150), () => _flipCardKeys[_currWordIndex][i].currentState?.toggleCard(), ); } _checkIfWinOrLoss(); } } void _checkIfWinOrLoss() { if (_currentWord!.wordString == _solution.wordString) { _gameStatus = GameStatus.won; ScaffoldMessenger.of(context).showSnackBar( SnackBar( dismissDirection: DismissDirection.none, duration: const Duration(days: 1), backgroundColor: correctColor, content: const Text( 'You Won!', style: TextStyle( color: Colors.white, ), ), action: SnackBarAction( onPressed: _restart, textColor: Colors.white, label: 'New Game', ), ), ); } else if (_currWordIndex + 1 >= _board.length) { _gameStatus = GameStatus.lost; ScaffoldMessenger.of(context).showSnackBar( SnackBar( dismissDirection: DismissDirection.none, duration: const Duration(days: 1), backgroundColor: Colors.red, content: Text( 'You Lost! Solution ${_solution.wordString}', style: const TextStyle( color: Colors.white, ), ), action: SnackBarAction( onPressed: _restart, textColor: Colors.white, label: 'New Game', ), ), ); } else { _gameStatus = GameStatus.playing; } _currWordIndex += 1; } void _restart() { setState(() { _gameStatus = GameStatus.playing; _currWordIndex = 0; _board ..clear() ..addAll(List.generate( 6, (_) => Word( letters: List.generate( 5, (_) => Letter.empty(), ), ), )); _solution = Word.fromString( fiveLetterWords[Random().nextInt(fiveLetterWords.length)].toUpperCase(), ); _flipCardKeys ..clear() ..addAll( List.generate( 6, (_) => List.generate( 5, (_) => GlobalKey<FlipCardState>(), ), ), ); _keyboardLetter.clear(); }); } }
0
mirrored_repositories/Wordle-Flutter/lib/feature/wordle
mirrored_repositories/Wordle-Flutter/lib/feature/wordle/widgets/board.dart
import 'package:flip_card/flip_card.dart'; import 'package:flutter/material.dart'; import 'package:wordle/feature/wordle/models/letter.model.dart'; import 'package:wordle/feature/wordle/models/word.model.dart'; import 'package:wordle/feature/wordle/widgets/board.tile.dart'; class Board extends StatelessWidget { const Board({Key? key, required this.board, required this.flipCardKeys}) : super(key: key); final List<Word> board; final List<List<GlobalKey<FlipCardState>>> flipCardKeys; @override Widget build(BuildContext context) { return Column( children: board .asMap() .map( (i, word) => MapEntry( i, Row( mainAxisAlignment: MainAxisAlignment.center, children: word.letters .asMap() .map( (j, letter) => MapEntry( j, FlipCard( key: flipCardKeys[i][j], flipOnTouch: false, direction: FlipDirection.VERTICAL, front: BoardTile( letter: Letter( val: letter.val, status: LetterStatus.intial, ), ), back: BoardTile(letter: letter), ), ), ) .values .toList(), ), ), ) .values .toList(), ); } }
0
mirrored_repositories/Wordle-Flutter/lib/feature/wordle
mirrored_repositories/Wordle-Flutter/lib/feature/wordle/widgets/keyboard.dart
import 'package:flutter/material.dart'; import 'package:wordle/feature/wordle/models/letter.model.dart'; const _qwerty = [ ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'], ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'], ['ENTER', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', 'DEL'], ]; class Keyboard extends StatelessWidget { const Keyboard({ Key? key, required this.onKeyTapped, required this.onDeleteTapped, required this.onEnterTapped, required this.letters, }) : super(key: key); final void Function(String) onKeyTapped; final VoidCallback onDeleteTapped; final VoidCallback onEnterTapped; final Set<Letter> letters; @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: _qwerty .map((keyRow) => Row( mainAxisAlignment: MainAxisAlignment.center, children: keyRow.map( (letter) { if (letter == 'DEL') { return _KeyboardButton.delete(onTap: onDeleteTapped); } else if (letter == 'ENTER') { return _KeyboardButton.enter(onTap: onEnterTapped); } final letterKey = letters.firstWhere( (e) => e.val == letter, orElse: () => Letter.empty(), ); return _KeyboardButton( onTap: () => onKeyTapped(letter), letter: letter, backgroundColor: letterKey != Letter.empty() ? letterKey.backgroundColor : Colors.grey, ); }, ).toList(), )) .toList(), ); } } class _KeyboardButton extends StatelessWidget { const _KeyboardButton({ Key? key, // ignore: unused_element this.height = 48, this.width = 30, required this.onTap, required this.backgroundColor, required this.letter, }) : super(key: key); factory _KeyboardButton.delete({ required VoidCallback onTap, }) => _KeyboardButton( width: 56, onTap: onTap, backgroundColor: Colors.grey, letter: 'DEL', ); factory _KeyboardButton.enter({ required VoidCallback onTap, }) => _KeyboardButton( width: 56, onTap: onTap, backgroundColor: Colors.grey, letter: 'ENTER', ); final double height; final double width; final VoidCallback onTap; final Color backgroundColor; final String letter; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 3.0, horizontal: 2.0), child: Material( color: backgroundColor, borderRadius: BorderRadius.circular(4), child: InkWell( onTap: onTap, child: Container( height: height, width: width, alignment: Alignment.center, child: Text( letter, style: const TextStyle( fontSize: 12, fontWeight: FontWeight.w600, ), ), ), ), ), ); } }
0
mirrored_repositories/Wordle-Flutter/lib/feature/wordle
mirrored_repositories/Wordle-Flutter/lib/feature/wordle/widgets/board.tile.dart
import 'package:flutter/material.dart'; import 'package:wordle/feature/wordle/models/letter.model.dart'; class BoardTile extends StatelessWidget { const BoardTile({Key? key, required this.letter}) : super(key: key); final Letter letter; @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.all(4), height: 48, width: 48, alignment: Alignment.center, decoration: BoxDecoration( color: letter.backgroundColor, border: Border.all(color: letter.borderColor), borderRadius: BorderRadius.circular(4), ), child: Text( letter.val, style: const TextStyle( fontSize: 32, fontWeight: FontWeight.bold, ), ), ); } }
0
mirrored_repositories/Wordle-Flutter/lib/feature/wordle
mirrored_repositories/Wordle-Flutter/lib/feature/wordle/models/letter.model.dart
import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import 'package:wordle/app/app.colors.dart'; enum LetterStatus { intial, notInWord, inWord, correct } class Letter extends Equatable { const Letter({ required this.val, this.status = LetterStatus.intial, }); factory Letter.empty() => const Letter(val: ''); final String val; final LetterStatus status; Color get backgroundColor { switch (status) { case LetterStatus.intial: return Colors.transparent; case LetterStatus.notInWord: return notInWordColor; case LetterStatus.inWord: return inWordColor; case LetterStatus.correct: return correctColor; } } Color get borderColor { switch (status) { case LetterStatus.intial: return Colors.grey; default: return Colors.transparent; } } Letter copyWith({ String? val, LetterStatus? status, }) { return Letter( val: val ?? this.val, status: status ?? this.status, ); } @override List<Object?> get props => [val, status]; }
0
mirrored_repositories/Wordle-Flutter/lib/feature/wordle
mirrored_repositories/Wordle-Flutter/lib/feature/wordle/models/word.model.dart
import 'package:equatable/equatable.dart'; import 'package:wordle/feature/wordle/models/letter.model.dart'; class Word extends Equatable { const Word({ required this.letters, }); final List<Letter> letters; factory Word.fromString(String word) => Word(letters: word.split('').map((e) => Letter(val: e)).toList()); String get wordString => letters.map((e) => e.val).join(); void addLetter(String val) { final currentIndex = letters.indexWhere((e) => e.val.isEmpty); if (currentIndex != -1) { letters[currentIndex] = Letter(val: val); } } void removeLetter() { final recentLetterIndex = letters.lastIndexWhere((e) => e.val.isNotEmpty); if (recentLetterIndex != -1) { letters[recentLetterIndex] = Letter.empty(); } } @override List<Object?> get props => [letters]; }
0
mirrored_repositories/Wordle-Flutter/lib/feature/wordle
mirrored_repositories/Wordle-Flutter/lib/feature/wordle/data/word_list.dart
const List<String> fiveLetterWords = [ "Abuse", "Adult", "Agent", "Anger", "Apple", "Award", "Basis", "Beach", "Birth", "Block", "Blood", "Board", "Brain", "Bread", "Break", "Brown", "Buyer", "Cause", "Chain", "Chair", "Chest", "Chief", "Child", "China", "Claim", "Class", "Clock", "Coach", "Coast", "Court", "Cover", "Cream", "Crime", "Cross", "Crowd", "Crown", "Cycle", "Dance", "Death", "Depth", "Doubt", "Draft", "Drama", "Dream", "Dress", "Earth", "Enemy", "Entry", "Error", "Event", "Owner", "Panel", "Paper", "Party" ];
0
mirrored_repositories/Wordle-Flutter
mirrored_repositories/Wordle-Flutter/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:wordle/app/app.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const App()); // 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/river
mirrored_repositories/river/lib/main.dart
import 'package:adaptive_theme/adaptive_theme.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:river/routes/router.dart'; import 'package:river/routes/router.gr.dart'; const Color cWhite = Color(0xFFFAFEFE); const Color cDark = Color(0xff2B2B2C); void main() async { WidgetsFlutterBinding.ensureInitialized(); final savedThemeMode = await AdaptiveTheme.getThemeMode(); runApp(RiverApp(savedThemeMode: savedThemeMode)); } /// My [MaterialApp] + [AdaptiveThem] class RiverApp extends StatelessWidget { final AdaptiveThemeMode? savedThemeMode; RiverApp({Key? key, this.savedThemeMode}) : super(key: key); final _appRouter = AppRouter(authGuard: AuthGuard(true)); @override Widget build(BuildContext context) { return ProviderScope( child: AdaptiveTheme( light: ThemeData( fontFamily: GoogleFonts.montserrat().fontFamily, appBarTheme: AppBarTheme( actionsIconTheme: const IconThemeData(color: cDark), elevation: .2, titleTextStyle: GoogleFonts.mogra( color: cDark, fontSize: 26, ), backgroundColor: cWhite, ), scaffoldBackgroundColor: cWhite, brightness: Brightness.light, primarySwatch: Colors.red, colorScheme: const ColorScheme.light().copyWith(secondary: Colors.amber), ), dark: ThemeData( brightness: Brightness.dark, primarySwatch: Colors.red, colorScheme: const ColorScheme.dark().copyWith(secondary: Colors.amber), ), initial: AdaptiveThemeMode.system, builder: (theme, darkTheme) => MaterialApp.router( debugShowCheckedModeBanner: false, title: 'Adaptive Theme Demo', theme: theme, darkTheme: darkTheme, routerDelegate: _appRouter.delegate(), routeInformationParser: _appRouter.defaultRouteParser(), ), ), ); } }
0
mirrored_repositories/river/lib
mirrored_repositories/river/lib/constants/constant.dart
import 'package:flutter/material.dart'; class KColors { KColors._(); static const Color background = Color(0xffF6F6F8); static const Color text = Color(0xff252525); static const Color card = Color(0xff0E1B2B); static const Color header = Color(0xff363853); } class KGradiant { KGradiant._(); static const LinearGradient purple = LinearGradient( colors: [ Color(0xFF6C91F5), Color(0xFF3C91F9), ], begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: [0.0, 1.0], tileMode: TileMode.clamp); static const LinearGradient blue = LinearGradient( colors: [ Color(0xFF0F85F3), Color(0xFF0165C6), ], begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: [0.0, 1.0], tileMode: TileMode.clamp); static const LinearGradient red = LinearGradient( colors: [ Color(0xFFFB1A28), Color(0xFFCC2630), ], begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: [0.0, 1], tileMode: TileMode.clamp); static const LinearGradient cyanButton = LinearGradient( colors: [ Color(0xFF6DF1ED), Color(0xFFA8E5E5), ], begin: Alignment.topLeft, end: Alignment.bottomRight, stops: [0.0, 1], tileMode: TileMode.clamp); static const LinearGradient pink = LinearGradient( colors: [ Color(0xFFF4737B), Color(0xFFFE9577), ], begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: [0.0, 1.0], tileMode: TileMode.clamp); } class KShadow { KShadow._(); static BoxShadow normal = BoxShadow( color: Colors.grey.withOpacity(0.3), spreadRadius: 2, blurRadius: 5, offset: const Offset(0, 3), // changes position of shadow ); static BoxShadow lightblue = BoxShadow( color: Colors.lightBlue.withOpacity(0.4), spreadRadius: 0, blurRadius: 5, offset: const Offset(3, 3), // changes position of shadow ); static BoxShadow red = BoxShadow( color: Colors.red.withOpacity(0.4), spreadRadius: 0, blurRadius: 5, offset: const Offset(3, 3), // changes position of shadow ); static BoxShadow yellow = BoxShadow( color: Colors.yellowAccent.withOpacity(0.4), spreadRadius: 0, blurRadius: 5, offset: const Offset(3, 3), // changes position of shadow ); static BoxShadow orange = BoxShadow( color: Colors.orangeAccent.withOpacity(0.4), spreadRadius: 0, blurRadius: 5, offset: const Offset(3, 3), // changes position of shadow ); }
0
mirrored_repositories/river/lib
mirrored_repositories/river/lib/gen/assets.gen.dart
/// GENERATED CODE - DO NOT MODIFY BY HAND /// ***************************************************** /// FlutterGen /// ***************************************************** // ignore_for_file: directives_ordering,unnecessary_import import 'package:flutter/widgets.dart'; class $AssetsImagesGen { const $AssetsImagesGen(); /// File path: assets/images/accountRecovery.png AssetGenImage get accountRecovery => const AssetGenImage('assets/images/accountRecovery.png'); /// File path: assets/images/getStartIntro.png AssetGenImage get getStartIntro => const AssetGenImage('assets/images/getStartIntro.png'); /// File path: assets/images/loginWithMobileNumber.png AssetGenImage get loginWithMobileNumber => const AssetGenImage('assets/images/loginWithMobileNumber.png'); /// File path: assets/images/uploadFile.png AssetGenImage get uploadFile => const AssetGenImage('assets/images/uploadFile.png'); } class Assets { Assets._(); static const $AssetsImagesGen images = $AssetsImagesGen(); } class AssetGenImage extends AssetImage { const AssetGenImage(String assetName) : super(assetName); Image image({ Key? key, ImageFrameBuilder? frameBuilder, ImageLoadingBuilder? loadingBuilder, ImageErrorWidgetBuilder? errorBuilder, String? semanticLabel, bool excludeFromSemantics = false, double? width, double? height, Color? color, BlendMode? colorBlendMode, BoxFit? fit, AlignmentGeometry alignment = Alignment.center, ImageRepeat repeat = ImageRepeat.noRepeat, Rect? centerSlice, bool matchTextDirection = false, bool gaplessPlayback = false, bool isAntiAlias = false, FilterQuality filterQuality = FilterQuality.low, }) { return Image( key: key, image: this, frameBuilder: frameBuilder, loadingBuilder: loadingBuilder, errorBuilder: errorBuilder, semanticLabel: semanticLabel, excludeFromSemantics: excludeFromSemantics, width: width, height: height, color: color, colorBlendMode: colorBlendMode, fit: fit, alignment: alignment, repeat: repeat, centerSlice: centerSlice, matchTextDirection: matchTextDirection, gaplessPlayback: gaplessPlayback, isAntiAlias: isAntiAlias, filterQuality: filterQuality, ); } String get path => assetName; }
0
mirrored_repositories/river/lib
mirrored_repositories/river/lib/routes/router.dart
import 'package:appwrite/appwrite.dart'; import 'package:appwrite/models.dart'; import 'package:auto_route/auto_route.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:river/appwrite/appwrite_client.dart'; import 'package:river/routes/router.gr.dart'; import 'package:river/screens/auth/login_with_email.dart'; import 'package:river/screens/auth/register.dart'; import 'package:river/screens/chat_screen.dart'; import 'package:river/screens/get_started_screen.dart'; import 'package:river/screens/home_bottom_nav_screen.dart'; import 'package:river/screens/image_picker_screen.dart'; import 'package:river/screens/market_screen.dart'; import 'package:river/screens/profile_screen.dart'; import 'package:river/screens/settings_screen.dart'; import 'package:river/screens/wallet_screen.dart'; @MaterialAutoRouter( replaceInRouteName: 'Screen,Route', routes: <AutoRoute>[ // AutoRoute(path: "/", page: GetStartedScreen), AutoRoute(path: "/login", page: LoginWithEmailAndPassScreen), AutoRoute(path: "/register", page: RegisterScreen), AutoRoute(path: "/Pick_image", page: ImagePickerScreen), AutoRoute(path: "/", page: HomeBottomNavigationScreen, children: [ AutoRoute( name: 'ChatRouter', path: 'chat', page: EmptyRouterPage, children: [ AutoRoute(path: '', page: ChatScreen), RedirectRoute(path: '*', redirectTo: ''), ], ), AutoRoute( name: 'MarketRouter', path: 'market', page: EmptyRouterPage, children: [ AutoRoute(path: '', page: MarketScreen), RedirectRoute(path: '*', redirectTo: ''), ], ), AutoRoute( name: 'WalletRouter', path: 'wallet', page: EmptyRouterPage, children: [ AutoRoute(path: '', page: WalletScreen), RedirectRoute(path: '*', redirectTo: ''), ], ), AutoRoute( name: 'ProfileRouter', path: 'profile', page: EmptyRouterPage, children: [ AutoRoute(path: '', page: ProfileScreen), RedirectRoute(path: '*', redirectTo: ''), ], ), ], guards: [ AuthGuard ]), AutoRoute( page: SettingsScreen, children: [ // AutoRoute(path: '', page: WalletScreen), RedirectRoute(path: '*', redirectTo: ''), ], ), ], ) class $AppRouter {} class AuthGuard extends AutoRouteGuard { bool account; AuthGuard(this.account); @override void onNavigation(NavigationResolver resolver, StackRouter router) { // the navigation is paused until resolver.next() is called with either // true to resume/continue navigation or false to abort navigation if (account ) { // if user is authenticated we continue resolver.next(true); } else { // we redirect the user to our login page router.push(RegisterRoute()).then((value) => resolver.next(true)); } } }
0
mirrored_repositories/river/lib
mirrored_repositories/river/lib/appwrite/appwrite_client.dart
import 'package:appwrite/appwrite.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; final _appWriteClient = Provider<Client>((ref) { Client client = Client(); client // .setEndpoint('http://192.168.1.24:1010/v1') // Your Appwrite Endpoint .setEndpoint('http://192.168.1.7:1010/v1') // Your Appwrite Endpoint .setProject('625d05a4d92c8bd0d5f4') // Your project ID .setSelfSigned( status: true, ); // For self signed certificates, only use for development return client; }); final accountProvider = Provider<Account>((ref) { Client client = ref.watch(_appWriteClient); Account account = Account(client); return account; }); final databaseProvider = Provider<Database>((ref) { Client client = ref.watch(_appWriteClient); Database _db = Database(client); return _db; });
0
mirrored_repositories/river/lib/utils
mirrored_repositories/river/lib/utils/database/person.dart
import 'package:objectbox/objectbox.dart'; @Entity() class Person { int id; String firstName; String lastName; Person({this.id = 0, required this.firstName, required this.lastName}); }
0
mirrored_repositories/river/lib
mirrored_repositories/river/lib/screens/home_bottom_nav_screen.dart
import 'package:adaptive_theme/adaptive_theme.dart'; import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:line_icons/line_icon.dart'; import 'package:river/routes/router.gr.dart'; class HomeBottomNavigationScreen extends HookWidget { const HomeBottomNavigationScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final _navCurrentIndex = useState(0); return AutoTabsScaffold( routes: const [ ProfileRouter(), ChatRouter(), WalletRouter(), MarketRouter(), ], bottomNavigationBuilder: (_, tabsRouter) { return BottomNavigationBar( onTap: (int index) { tabsRouter.setActiveIndex(index); _navCurrentIndex.value = index; }, currentIndex: _navCurrentIndex.value, selectedItemColor: Colors.blue[700], unselectedItemColor: Colors.grey[400], items: [ BottomNavigationBarItem( icon: LineIcon.user(), label: 'Profile', ), BottomNavigationBarItem( icon: LineIcon.wallet(), label: 'Wallet', ), BottomNavigationBarItem( icon: LineIcon.rocketChat(), label: 'Chat', ), BottomNavigationBarItem( icon: LineIcon.store(), label: 'Market', ), ]); }, appBarBuilder: (_, tabsRouter) { return AppBar( centerTitle: true, title: const Text('River'), actions: [ IconButton( onPressed: () async { var currentThem = await AdaptiveTheme.getThemeMode(); currentThem == AdaptiveThemeMode.light ? AdaptiveTheme.of(context).setDark() : AdaptiveTheme.of(context).setLight(); }, icon: LineIcon.sun()) ], ); }, ); } }
0
mirrored_repositories/river/lib
mirrored_repositories/river/lib/screens/image_picker_screen.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:image_picker/image_picker.dart'; import 'package:image_editor/image_editor.dart' as editor; class ImagePickerScreen extends HookConsumerWidget { ImagePickerScreen({Key? key}) : super(key: key); final ImagePicker _picker = ImagePicker(); final editorOption = editor.ImageEditorOption() ..addOption(editor.ClipOption(x: 0, y: 0, width: 450, height: 450)); @override Widget build(BuildContext context, WidgetRef ref) { // editorOption.outputFormat(editor.OutputFormat.jpeg(88)); final image = useState(''); final compressed = useState(''); final compressedSize = useState(0); final size = useState(0); return Scaffold( appBar: AppBar(), body: Center( child: ListView( children: [ GestureDetector( onTap: () async { print('call btn'); XFile? file = await _picker.pickImage(source: ImageSource.gallery); image.value = file?.path ?? ''; print(file?.mimeType ?? ''); print(await file?.length()); size.value = await file?.length() ?? 0; }, child: Container( padding: const EdgeInsets.all(10), color: Colors.lightBlue, child: const Text( 'Pick image', textAlign: TextAlign.center, ))), Image.file(File(image.value)), Text('${(size.value/1080).floor()} kb'), ElevatedButton( onPressed: () async { // editorOption.outputFormat = editor.OutputFormat.jpeg(60); var edited = await editor.ImageEditor.editFileImageAndGetFile( file: File(image.value), imageEditorOption: editorOption); compressed.value = edited?.path ?? ''; compressedSize.value = await edited?.length() ?? 0; }, child: Text('ویرایش')), Image.file(File(compressed.value)), Text('${(compressedSize.value / 1080).floor()} kb'), ], ), ), ); } }
0
mirrored_repositories/river/lib
mirrored_repositories/river/lib/screens/profile_screen.dart
import 'package:appwrite/appwrite.dart'; import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:river/appwrite/appwrite_client.dart'; import 'package:river/routes/router.gr.dart'; class ProfileScreen extends HookConsumerWidget { const ProfileScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { // Account account = ref.watch(accountProvider); // Database database = ref.watch(databaseProvider); return Scaffold( body: SafeArea( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 18), child: ListView( children: [ const SizedBox( height: 30, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Padding( padding: EdgeInsets.only(right: 18), child: CircleAvatar( maxRadius: 40, backgroundImage: NetworkImage( 'https://d2qp0siotla746.cloudfront.net/img/use-cases/profile-picture/template_3.jpg'), ), ), Column( children: const [ Text('128', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, )), Text('Post') ], ), Column( children: const [ Text('128', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, )), Text('Followers') ], ), const SizedBox() ], ), const SizedBox(height: 30), const Text( 'This is the title', style: TextStyle( fontWeight: FontWeight.bold, ), ), const SizedBox( height: 8, ), const Text( 'This is the total biography an ddetails aboute this person. ...............'), const SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ ElevatedButton( onPressed: () { AutoRouter.of(context).navigate(ImagePickerRoute()); }, child: Text('new Post')), ElevatedButton(onPressed: null, child: Text('new Post')), ElevatedButton(onPressed: null, child: Text('new Post')) ], ), const SizedBox( height: 10, ), const Divider( height: 1, ), StaggeredGrid.count( crossAxisCount: 6, mainAxisSpacing: 4, crossAxisSpacing: 4, children: [ StaggeredGridTile.count( crossAxisCellCount: 2, mainAxisCellCount: 2, child: Container( color: Colors.blue, child: const Center( child: Text('text'), ), ), ), StaggeredGridTile.count( crossAxisCellCount: 2, mainAxisCellCount: 2, child: Container( color: Colors.blue, child: const Center( child: Text('text'), ), ), ), StaggeredGridTile.count( crossAxisCellCount: 2, mainAxisCellCount: 2, child: Container( color: Colors.blue, child: const Center( child: Text('text'), ), ), ), StaggeredGridTile.count( crossAxisCellCount: 2, mainAxisCellCount: 2, child: Container( color: Colors.blue, child: Center( child: Text('text'), ), ), ), ], ) ], ))), ); } }
0
mirrored_repositories/river/lib
mirrored_repositories/river/lib/screens/wallet_screen.dart
import 'package:flutter/material.dart'; class WalletScreen extends StatelessWidget { const WalletScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.brown, body: Center(child: Text('Wallet screen') ), ); } }
0
mirrored_repositories/river/lib
mirrored_repositories/river/lib/screens/get_started_screen.dart
import 'package:auto_route/auto_route.dart'; import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:river/constants/constant.dart'; import 'package:river/gen/assets.gen.dart'; import 'package:river/main.dart'; import 'package:river/routes/router.gr.dart'; class GetStartedScreen extends StatelessWidget { const GetStartedScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: cWhite, appBar: AppBar( backgroundColor: cWhite, elevation: 0, ), body: CustomScrollView( slivers: [ SliverFillRemaining( hasScrollBody: false, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Image.asset(Assets.images.getStartIntro.path), Padding( padding: const EdgeInsets.symmetric(horizontal: 50), child: Column( children: [ const SizedBox( height: 80, child: AutoSizeText( 'Pay, Manage,\nGrow...', style: TextStyle( fontSize: 40, fontWeight: FontWeight.bold, color: cDark), minFontSize: 24, maxLines: 2, textAlign: TextAlign.center, overflow: TextOverflow.ellipsis, )), const SizedBox( height: 20, ), SizedBox( height: 35, child: AutoSizeText( 'A social Media For your Brand, manage All of your payment related needs', style: TextStyle( fontSize: 14, color: Colors.grey[700]!), minFontSize: 12, maxLines: 2, textAlign: TextAlign.center, overflow: TextOverflow.ellipsis, ), ), ], ), ), Padding( padding: const EdgeInsets.symmetric( horizontal: 50, vertical: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ GradientButton( onTap: () { AutoRouter.of(context).push( RegisterRoute()); }, gradient: KGradiant.blue, padding: const EdgeInsets.symmetric(vertical: 25), child: const Text( 'Get Started', textAlign: TextAlign.center, style: TextStyle(color: cWhite, fontSize: 16), ), ), const SizedBox( height: 20, ), Wrap( runAlignment: WrapAlignment.center, crossAxisAlignment: WrapCrossAlignment.center, alignment: WrapAlignment.center, children: [ Text('Already have an account? '), TextButton(onPressed: () { AutoRouter.of(context) .push(const LoginWithEmailAndPassRoute()); }, child: Text('Signin')) ], ) ], ), ) ], )) ], ), ); } } class GradientButton extends StatelessWidget { const GradientButton( {Key? key, required this.child, required this.onTap, this.gradient, this.boxShadow, this.padding, this.color, this.borderRadius}) : super(key: key); final Widget child; final void Function()? onTap; final Gradient? gradient; final List<BoxShadow>? boxShadow; final EdgeInsetsGeometry? padding; final BorderRadius? borderRadius; /// As Default The color is set to [transparent]. /// set color if you don't want to use gradient. final Color? color; @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( color: Colors.red, boxShadow: boxShadow, gradient: gradient, borderRadius: borderRadius ?? BorderRadius.circular(14.0), ), child: Material( color: color ?? Colors.transparent, // elevation: 4, shape: RoundedRectangleBorder( borderRadius: borderRadius ?? BorderRadius.circular(14.0), ), child: InkWell( borderRadius: borderRadius ?? BorderRadius.circular(14.0), splashColor: Colors.black.withOpacity(.2), overlayColor: MaterialStateProperty.resolveWith( (states) => Colors.black.withOpacity(.2)), onTap: onTap, child: Container( padding: padding ?? const EdgeInsets.symmetric(horizontal: 20, vertical: 12), child: child), ), ), ); } }
0
mirrored_repositories/river/lib
mirrored_repositories/river/lib/screens/chat_screen.dart
import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:river/routes/router.gr.dart'; import 'package:river/screens/auth/register.dart'; // class ChatScreen extends StatelessWidget { // const ChatScreen({Key? key}) : super(key: key); // @override // Widget build(BuildContext context) { // return Scaffold( // backgroundColor: Colors.green, // body: Center(child: Text('Chat screen')) // ); // } // } class ChatScreen extends StatelessWidget { const ChatScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.green, body: RegisterScreen() ); } }
0
mirrored_repositories/river/lib
mirrored_repositories/river/lib/screens/testfunctions.dart
import 'package:appwrite/appwrite.dart'; import 'package:appwrite/models.dart'; import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:river/appwrite/appwrite_client.dart'; import 'package:river/main.dart'; import 'package:river/routes/router.gr.dart'; class TestFunctionScreen extends HookConsumerWidget { const TestFunctionScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { Account account = ref.watch(accountProvider); Database database = ref.watch(databaseProvider); AppWriteServices _services = AppWriteServices(account: account, db: database); final data = useState([]); return Scaffold( backgroundColor: cWhite, body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text('hellow world'), ElevatedButton( onPressed: () async { try { await account.create( userId: 'unique()', email: 'me@appwrite.io', password: 'password', name: 'My Name'); } catch (e) { throw e; } }, child: const Text('create User')), ElevatedButton( onPressed: () { account .createSession( email: 'me@appwrite.io', password: 'password', ) .then((response) => print(response)) .catchError((error) => print(error.response)); }, child: Text('login')), ElevatedButton( onPressed: () { database .listDocuments( collectionId: 'alaki001', ) .then((value) => print(value.documents)) .catchError((error) => print(error.response)); }, child: Text('Get document List')), ElevatedButton( onPressed: () { database .createDocument( collectionId: 'alaki001', documentId: 'unique()', data: {'1000': 200, 'text': "she lived in paradice"}, ) .then((value) => print(value)) .catchError((error) => print(error.response)); }, child: Text('Get User')), ElevatedButton( onPressed: () { account.get().then((User response) { print(response.$id); }).catchError((error) { print(error.response); }); }, child: Text('create Document')), ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith( (states) => Colors.red)), onPressed: () { _services.updateDocument(); }, child: Text('custom Function')) ]), ), ); } } class AppWriteServices { Account account; Database db; AppWriteServices({ required this.account, required this.db, }); /// get the userData getAccount() { account .get() .then((User user) => print(user.email)) .catchError((e) => print(e)); } createDocument() { db .createDocument( collectionId: '625d0cba1cc5ff839bf7', documentId: 'unique()', data: { 'hi': 'end of the world', 'data': ['ali', 'mamad'] }, ) .then((value) => print(value)) .catchError((e) => print(e)); } listDocument() { db .listDocuments( collectionId: '625d0cba1cc5ff839bf7', ) .then((value) => print(value.documents)) .catchError((e) => print(e)); } updateDocument() { db .updateDocument( collectionId: '625d0cba1cc5ff839bf7', documentId: '627139dc3ff0ed133738', data: {'bad': 'fucked up shit'}, ) .then((value) => print(value)) .catchError((e) => print(e)); } }
0
mirrored_repositories/river/lib
mirrored_repositories/river/lib/screens/settings_screen.dart
import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:river/routes/router.gr.dart'; class SettingsScreen extends StatelessWidget { const SettingsScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: ElevatedButton( onPressed: () { // context.router.push(BookChildRoute()); }, child: Center(child: Text('Setting')), ), ); } }
0
mirrored_repositories/river/lib
mirrored_repositories/river/lib/screens/market_screen.dart
import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:river/routes/router.gr.dart'; class MarketScreen extends StatelessWidget { const MarketScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.yellow, body: Center(child: Text('Market screen')) ); } }
0
mirrored_repositories/river/lib/screens
mirrored_repositories/river/lib/screens/auth/register.dart
import 'package:appwrite/appwrite.dart'; import 'package:appwrite/models.dart'; import 'package:auto_route/auto_route.dart'; import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:line_icons/line_icon.dart'; import 'package:river/appwrite/appwrite_client.dart'; import 'package:river/constants/constant.dart'; import 'package:river/gen/assets.gen.dart'; import 'package:river/main.dart'; import 'package:river/routes/router.gr.dart'; import 'package:river/screens/get_started_screen.dart'; import 'package:river/screens/profile_screen.dart'; class RegisterScreen extends HookConsumerWidget { RegisterScreen({Key? key}) : super(key: key); Map<String, String> _object = {'email': '', 'password': '', 'username': ''}; final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context, WidgetRef ref) { Account account = ref.watch(accountProvider); return Scaffold( backgroundColor: cWhite, appBar: AppBar( toolbarTextStyle: TextStyle(color: Colors.black), iconTheme: IconThemeData(color: Colors.black), backgroundColor: cWhite, elevation: 0, ), body: CustomScrollView( slivers: [ SliverFillRemaining( hasScrollBody: false, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( children: const [ Text( 'Welcome', style: TextStyle( fontSize: 40, fontWeight: FontWeight.bold), ), Text('please complete the following requirment'), ], ), Padding( padding: const EdgeInsets.symmetric(horizontal: 50), child: Form( key: _formKey, child: Column( children: [ TextFormField( onSaved: (value) { _object.update('email', (_) => value ?? ''); }, decoration: InputDecoration( icon: LineIcon.envelope(), hintText: 'example@gmail.com'), ), const SizedBox( height: 10, ), TextFormField( onSaved: (value) { _object.update('password', (_) => value ?? ''); }, obscureText: true, decoration: InputDecoration( icon: LineIcon.lock(), hintText: 'password'), ), const SizedBox( height: 10, ), TextFormField( onSaved: (value) { _object.update('username', (_) => value ?? ''); }, decoration: InputDecoration( icon: LineIcon.user(), hintText: 'Username'), ), ], ), ), ), Padding( padding: const EdgeInsets.symmetric( horizontal: 50, vertical: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ElevatedButton(onPressed: (){ account.get().then((User response) { print( response.email); }).catchError((error) { print(error.response); }); }, child: Text('getUser')), GradientButton( onTap: () async { _formKey.currentState?.save(); print(_object); await account .create( userId: 'unique()', email: _object['email']!, password: _object['password']!, name: _object['username']!) .then((response) => print(response)) .catchError((error) => print(error.response)); account .createSession( email: _object['email']!, password: _object['password']!, ) .then((response) { print(response); AutoRouter.of(context) .push(HomeBottomNavigationRoute()); }).catchError((error) => print(error.response)); // AutoRouter.of(context).push(const RegisterRoute()); }, gradient: KGradiant.blue, padding: const EdgeInsets.symmetric(vertical: 25), child: const Text( 'Register', textAlign: TextAlign.center, style: TextStyle(color: cWhite, fontSize: 16), ), ), const SizedBox( height: 20, ), Wrap( runAlignment: WrapAlignment.center, crossAxisAlignment: WrapCrossAlignment.center, alignment: WrapAlignment.center, children: [ const Text('Already have an account? '), TextButton( onPressed: () { AutoRouter.of(context) .push(const LoginWithEmailAndPassRoute()); }, child: const Text('Signin')) ], ) ], ), ) ], )) ], ), ); } }
0
mirrored_repositories/river/lib/screens
mirrored_repositories/river/lib/screens/auth/login_with_email.dart
import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; class LoginWithEmailAndPassScreen extends HookConsumerWidget { const LoginWithEmailAndPassScreen ({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { return Scaffold( appBar: AppBar(), body: Center( child: Column( children: [ Form( child: Column( children: [ TextFormField( decoration: InputDecoration(label: Text('E-mail')), ) ], )) ], )), ); } }
0
mirrored_repositories/river
mirrored_repositories/river/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:river/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. // await tester.pumpWidget( RiverApp()); // 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/GATT_the_bugger
mirrored_repositories/GATT_the_bugger/lib/assigned_numbers.dart
import 'dart:convert'; import 'package:flutter/services.dart' show rootBundle; import 'package:flutter_blue/flutter_blue.dart'; Map<int,String> AsgnVendor = {}; Map<String,String> AsgnService = {}; Map<String,String> AsgnCharacteristic = {}; final RegExp pattern = RegExp( r'^0000([0-9a-f]{4})-0000-1000-8000-00805f9b34fb$', caseSensitive: false); Future<void> assigned_numbers_load() async { final vendors = await rootBundle.loadString( 'bluetooth-numbers-database/v1/company_ids.json'); for(final rec in jsonDecode(vendors)) { AsgnVendor[rec['code']] = rec['name']; } final services = await rootBundle.loadString( 'bluetooth-numbers-database/v1/service_uuids.json'); for(final rec in jsonDecode(services)) { AsgnService[rec['uuid']] = rec['name']; } final characteristics = await rootBundle.loadString( 'bluetooth-numbers-database/v1/characteristic_uuids.json'); for(final rec in jsonDecode(characteristics)) { AsgnCharacteristic[rec['uuid']] = rec['name']; } } String vendor_lookup(int id) { if(AsgnVendor.containsKey(id)) return AsgnVendor[id]!; return ''; } String service_lookup(Guid uuid) { RegExpMatch? match = pattern.firstMatch(uuid.toString()); String key = match != null ? match.group(1)! : uuid.toString(); key = key.toUpperCase(); if(AsgnService.containsKey(key)) { return AsgnService[key]!; } return ''; } String characteristic_lookup(Guid uuid) { RegExpMatch? match = pattern.firstMatch(uuid.toString()); String key = match != null ? match.group(1)! : uuid.toString(); key = key.toUpperCase(); if(AsgnCharacteristic.containsKey(key)) { return AsgnCharacteristic[key]!; } return ''; }
0
mirrored_repositories/GATT_the_bugger
mirrored_repositories/GATT_the_bugger/lib/globals.dart
import 'package:flutter_blue/flutter_blue.dart'; late BluetoothDevice device; late List<BluetoothService> services; late BluetoothCharacteristic characteristic; String device_name() { return device.name.isNotEmpty ? device.name : device.id.toString(); }
0
mirrored_repositories/GATT_the_bugger
mirrored_repositories/GATT_the_bugger/lib/widgets.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; enum DataType { hex, string } ThemeData app_theme() { return ThemeData( brightness: Brightness.light, primarySwatch: Colors.indigo, scaffoldBackgroundColor: Colors.grey[200], cardTheme: CardTheme(color: Colors.white), textButtonTheme: TextButtonThemeData(style: TextButton.styleFrom( textStyle: TextStyle(fontSize: 16), primary: Colors.indigo[800], padding: EdgeInsets.only(right: 16), )), elevatedButtonTheme: ElevatedButtonThemeData(style: ElevatedButton.styleFrom( textStyle: TextStyle(fontSize: 15), primary: Colors.indigo[400], minimumSize: Size(100, 40), )), ); } Widget infobar(BuildContext context, String left, [String? right, Brightness brightness=Brightness.light]) { late TextStyle style; late Color background; switch(brightness) { case Brightness.light: style = TextStyle(color: Theme.of(context).textTheme.caption!.color); background = Theme.of(context).cardTheme.color!; break; case Brightness.dark: style = TextStyle(color: Colors.grey[100]); background = Colors.indigo[600]!; break; } return Container( child: Row( children: [ Text(left, style: style), right != null ? Text(right, style: style) : SizedBox(), ], mainAxisAlignment: MainAxisAlignment.spaceBetween, ), color: background, padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16), ); } Widget loader(String title, String subtitle) { return Center(child: Card( child: Padding( child: ListTile( leading: CircularProgressIndicator(), title: Text(title), subtitle: Text(subtitle), ), padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16), ), margin: EdgeInsets.only(bottom: 80), shape: RoundedRectangleBorder(), )); } class HexFormatter extends TextInputFormatter { final RegExp filter = RegExp(r"[^0-9a-fA-F]+"); final RegExp hexpair = RegExp(r"([0-9a-fA-F]{2})"); DataType data_type; HexFormatter(this.data_type); formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { if(this.data_type == DataType.hex) { String newText = newValue.text.replaceAll(filter, ''); newText = newText.replaceAllMapped(hexpair, (Match m) => m[1]! + ' '); newText = newText.trimRight(); int offset = newValue.selection.baseOffset; if(oldValue.text.length < newValue.text.length) { if(oldValue.text.length == newText.length) offset--; else if(offset % 3 == 0) offset++; } else if(oldValue.text.length > newValue.text.length) { if(offset % 3 == 0) offset--; } return TextEditingValue( text: newText, selection: TextSelection.collapsed(offset: offset), ); } return newValue; } }
0
mirrored_repositories/GATT_the_bugger
mirrored_repositories/GATT_the_bugger/lib/main.dart
import 'dart:async'; import 'dart:io'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_blue/flutter_blue.dart'; import 'package:location/location.dart'; import 'package:wave/config.dart'; import 'package:wave/wave.dart'; import 'device.dart'; import 'globals.dart'; import 'characteristic.dart'; import 'assigned_numbers.dart'; import 'widgets.dart'; enum ConnStage { connecting, discovering } class ResultTime { ScanResult result; DateTime time; ResultTime(this.result, this.time); } void main() => runApp(App()); class App extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'GATT the bugger', home: Main(), routes: { '/device': (BuildContext context) => Device(), '/characteristic': (BuildContext context) => Characteristic(), }, theme: app_theme(), ); } } class Main extends StatefulWidget { @override _MainState createState() => _MainState(); } class _MainState extends State<Main> with WidgetsBindingObserver { static const platform = const MethodChannel('pl.blach.gatt_the_bugger/native'); List<ResultTime> _results = []; ConnStage? _conn_stage; StreamSubscription<ScanResult>? _scan_sub; Timer? _cleanup_timer; @override void didChangeAppLifecycleState(AppLifecycleState state) { if(ModalRoute.of(context)!.isCurrent) { switch(state) { case AppLifecycleState.paused: _stop_scan(); break; case AppLifecycleState.resumed: _start_scan(); break; case AppLifecycleState.inactive: case AppLifecycleState.detached: } } } @override void initState() { WidgetsBinding.instance!.addObserver(this); init_async(); super.initState(); } Future<void> init_async() async { await assigned_numbers_load(); _start_scan(); } @override void dispose() { WidgetsBinding.instance!.removeObserver(this); _stop_scan(); super.dispose(); } Future<void> _start_scan() async { if(Platform.isAndroid) { if(! await FlutterBlue.instance.isOn) { await platform.invokeMethod('btenable'); while(! await FlutterBlue.instance.isOn); } AndroidDeviceInfo androidInfo = await DeviceInfoPlugin().androidInfo; if(androidInfo.version.sdkInt! >= 23) { Location location = Location(); while(await location.hasPermission() != PermissionStatus.granted) { await location.requestPermission(); } if(! await location.serviceEnabled()) { await location.requestService(); } } _cleanup_timer = Timer.periodic(Duration(seconds: 2), _cleanup); } _scan_sub = FlutterBlue.instance.scan(allowDuplicates: true).listen((ScanResult result) { final ResultTime result_time = ResultTime(result, DateTime.now()); int index = _results.indexWhere((ResultTime _result_time) => _result_time.result.device.id == result_time.result.device.id); setState(() { if(index < 0) _results.add(result_time); else _results[index] = result_time; }); }); } void _cleanup(Timer timer) { DateTime limit = DateTime.now().subtract(Duration(seconds: 5)); for(int i = _results.length - 1; i >= 0; i--) { if(_results[i].time.isBefore(limit)) setState(() => _results.removeAt(i)); } } Future<void> _stop_scan() async { _scan_sub?.cancel(); _cleanup_timer?.cancel(); await FlutterBlue.instance.stopScan(); setState(() => _results.clear()); } Future<void> _restart_scan() async { if(Platform.isAndroid) { setState(() => _results.clear()); } else { await _stop_scan(); _start_scan(); } } Future<void> _goto_device(int index) async { late StreamSubscription<BluetoothDeviceState> _conn_sub; device = _results[index].result.device; _stop_scan(); setState(() => _conn_stage = ConnStage.connecting); await device.connect(autoConnect: false); _conn_sub = device.state.listen((BluetoothDeviceState state) { if(state == BluetoothDeviceState.disconnected) { Navigator.popUntil(context, ModalRoute.withName('/')); } }); setState(() => _conn_stage = ConnStage.discovering); services = await device.discoverServices(); await device.requestMtu(251); Future.delayed(Duration(milliseconds: 500), () => Navigator.pushNamed(context, '/device').whenComplete(() async { _conn_sub.cancel(); await device.disconnect(); setState(() => _conn_stage = null); _start_scan(); }) ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GATT the bugger'), actions: [IconButton( icon: Icon(Icons.refresh), onPressed: _conn_stage == null ? _restart_scan : null, )], ), body: _build_body(), ); } Widget _build_body() { switch(_conn_stage) { case ConnStage.connecting: return loader('Connecting ...', 'Wait while connecting'); case ConnStage.discovering: return loader('Connecting ...', 'Wait while discovering services'); case null: return _results.isEmpty ? _build_intro() : _build_list(); } } Widget _build_intro() { final screen = MediaQuery.of(context).size; return Column( children: [ Stack( children: [ Container( child: Material( child: WaveWidget( config: CustomConfig( colors: [Colors.white30, Colors.white70], durations: [5000, 7500], heightPercentages: [0.40, 0.40], ), size: Size(double.infinity, double.infinity), ), clipBehavior: Clip.antiAlias, color: Colors.grey[200], elevation: 3, shape: CircleBorder(), ), width: screen.width * .80, height: screen.width * .80, ), Opacity( child: Padding( child: Icon( Icons.bluetooth_searching, color: Colors.indigo, size: screen.width / 2, ), padding: EdgeInsets.only(left: screen.width / 14), ), opacity: .90, ), ], alignment: AlignmentDirectional.center, ), Text( 'No BLE devices found', textAlign: TextAlign.center, style: TextStyle(color: Theme.of(context).primaryColor, fontSize: 18, fontWeight: FontWeight.w500), ), Padding( child: Text( 'Wait while looking for BLE devices.\nThis should take a few seconds.', textAlign: TextAlign.center, style: TextStyle(height: 1.4), ), padding: EdgeInsets.only(bottom: screen.height * .02), ), ], mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.stretch, ); } Widget _build_list() { return RefreshIndicator( child: ListView.separated( itemCount: _results.length + 1, itemBuilder: _build_list_item, separatorBuilder: (BuildContext context, int index) => Divider(height: 0), ), onRefresh: _restart_scan, ); } Widget _build_list_item(BuildContext context, int index) { if(index == 0) return infobar(context, 'BLE devices', null, Brightness.dark); final ScanResult result = _results[index - 1].result; String vendor = ''; if(result.advertisementData.manufacturerData.isNotEmpty) { result.advertisementData.manufacturerData.forEach((int id, _) { vendor = vendor_lookup(id); if(vendor.isNotEmpty) vendor = '\n' + vendor; }); } return Card( child: ListTile( leading: Column( children: [Text('${result.rssi.toString()} dB')], mainAxisAlignment: MainAxisAlignment.center, ), title: result.device.name.isNotEmpty ? Text(result.device.name) : Text('Unnamed', style: TextStyle(color: Theme.of(context).textTheme.caption!.color)), subtitle: Text(result.device.id.toString() + vendor, style: TextStyle(height: 1.35)), trailing: result.advertisementData.connectable ? Column( children: [Icon(Icons.chevron_right)], mainAxisAlignment: MainAxisAlignment.center, ) : SizedBox(), isThreeLine: vendor.isNotEmpty, onTap: result.advertisementData.connectable ? () => _goto_device(index-1) : null, ), margin: EdgeInsets.all(0), shape: RoundedRectangleBorder(), ); } }
0
mirrored_repositories/GATT_the_bugger
mirrored_repositories/GATT_the_bugger/lib/characteristic.dart
import 'dart:async'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_blue/flutter_blue.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'assigned_numbers.dart'; import 'globals.dart'; import 'widgets.dart'; class Characteristic extends StatefulWidget { @override _CharacteristicState createState() => _CharacteristicState(); } class _CharacteristicState extends State<Characteristic> { DataType _data_type = DataType.hex; StreamSubscription<List<int>>? _notify_sub; TextEditingController _write_ctrl = TextEditingController(); TextEditingController _read_ctrl = TextEditingController(); TextEditingController _notify_ctrl = TextEditingController(); @override Future<void> didChangeDependencies() async { SharedPreferences prefs = await SharedPreferences.getInstance(); setState(() => _data_type = DataType.values[prefs.getInt('data_type') ?? 0]); super.didChangeDependencies(); } @override void dispose() { _notify_sub?.cancel(); if(characteristic.properties.notify || characteristic.properties.indicate) { characteristic.setNotifyValue(false); } super.dispose(); } Future<void> _on_data_type(DataType? value) async { setState(() => _data_type = value!); SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setInt('data_type', value!.index); } Future<void> _on_write() async { List<int> value = []; if(_data_type == DataType.hex) { for(int i=0; i<_write_ctrl.text.length; i+=3) { value.add(int.parse(_write_ctrl.text[i] + _write_ctrl.text[i+1], radix: 16)); } } else { value = Uint8List.fromList(_write_ctrl.text.codeUnits); } if(value.isNotEmpty) { characteristic.write(value, withoutResponse: characteristic.properties.writeWithoutResponse); } } String _value_to_text(List<int> value) { String text = ''; if(_data_type == DataType.hex) { for(int hex in value) { text += hex.toRadixString(16).padLeft(2, '0').padRight(3); } } else { text = String.fromCharCodes(value); } return text; } Future<void> _on_read() async { List<int> value = await characteristic.read(); setState(() => _read_ctrl.text = _value_to_text(value)); } Future<void> _on_notify() async { if(_notify_sub == null) { _notify_sub = characteristic.value.listen((List<int> value) { setState(() => _notify_ctrl.text = _value_to_text(value)); }); characteristic.setNotifyValue(true); setState(() => null); } else { _notify_sub?.cancel(); characteristic.setNotifyValue(false); setState(() => _notify_sub = null); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(device_name())), body: _build_body(), ); } Widget _build_body() { final CharacteristicProperties props = characteristic.properties; String sname = service_lookup(characteristic.serviceUuid); if(sname.isNotEmpty) sname = '\n' + sname; String cname = characteristic_lookup(characteristic.uuid); if(cname.isNotEmpty) cname = '\n' + cname; return Column(children: [ _build_switches(), (props.write || props.writeWithoutResponse) ? _build_write() : SizedBox(), props.read ? _build_read() : SizedBox(), (props.notify || props.indicate) ? _build_notify() : SizedBox(), Expanded(child: SizedBox()), Divider(height: 0), Card( child: Column(children: [ infobar(context, 'Service:', characteristic.serviceUuid.toString() + sname), Divider(height: 0), infobar(context, 'Characteristic:', characteristic.uuid.toString() + cname), ]), margin: EdgeInsets.all(0), ), ]); } Widget _build_switches() { return Card( child: Row( children: [ _build_switch('Hex', DataType.hex), _build_switch('String', DataType.string), ], mainAxisAlignment: MainAxisAlignment.spaceEvenly, ), color: Colors.transparent, elevation: 0, margin: EdgeInsets.only(top: 24, bottom: 12, left: 8, right: 8), ); } Widget _build_switch(String label, DataType value) { return TextButton( child: Row(children: [ Radio( value: value, groupValue: _data_type, onChanged: _on_data_type, ), Text(label), ]), style: TextButton.styleFrom( primary: value != _data_type ? Colors.grey[800] : null, ), onPressed: () => _on_data_type(value), ); } Widget _build_button(List<Widget> children) { return Card( child: Padding( child: Row(children: children), padding: EdgeInsets.symmetric(vertical: 16, horizontal: 12), ), margin: EdgeInsets.symmetric(vertical: 12, horizontal: 8), ); } Widget _build_write() { return _build_button([ Expanded(child: TextField( controller: _write_ctrl, style: TextStyle(fontFamily: 'monospace'), inputFormatters: [HexFormatter(_data_type)], )), SizedBox(width: 12), ElevatedButton( child: Text('Write'), onPressed: _on_write, ), ]); } Widget _build_read() { return _build_button([ ElevatedButton( child: Text('Read'), onPressed: _on_read, ), SizedBox(width: 12), Expanded(child: TextField( controller: _read_ctrl, readOnly: true, style: TextStyle(fontFamily: 'monospace'), )), ]); } Widget _build_notify() { return _build_button([ ElevatedButton( child: Text('Subscribe'), style: ElevatedButton.styleFrom( primary: _notify_sub != null ? Colors.indigoAccent[400] : null, ), onPressed: _on_notify, ), SizedBox(width: 12), Expanded(child: TextField( controller: _notify_ctrl, readOnly: true, style: TextStyle(fontFamily: 'monospace'), )), ]); } }
0
mirrored_repositories/GATT_the_bugger
mirrored_repositories/GATT_the_bugger/lib/device.dart
import 'package:flutter/material.dart'; import 'package:flutter_blue/flutter_blue.dart'; import 'assigned_numbers.dart'; import 'globals.dart'; import 'widgets.dart'; class Device extends StatefulWidget { @override _DeviceState createState() => _DeviceState(); } class _DeviceState extends State<Device> { void _goto_characteristic(BluetoothCharacteristic c) { characteristic = c; Navigator.pushNamed(context, '/characteristic'); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(device_name())), body: _build_list(), ); } Widget _build_list() { return ListView.separated( itemCount: services.length + 1, itemBuilder: _build_list_item, separatorBuilder: (BuildContext context, int index) => Divider(height: 0), ); } Widget _build_list_item(BuildContext context, int index) { if(index == 0) return infobar(context, 'Services & characteristics', null, Brightness.dark); final BluetoothService s = services[index-1]; final String sname = service_lookup(s.uuid); List<ListTile> tiles = [ ListTile( title: Text(s.uuid.toString()), subtitle: sname.isNotEmpty ? Text(sname) : null, ) ]; for(BluetoothCharacteristic c in s.characteristics) { String cname = characteristic_lookup(c.uuid); if(cname.isNotEmpty) cname += '\n'; List<String> props = []; if(c.properties.write) props.add('write'); if(c.properties.writeWithoutResponse) props.add('write without response'); if(c.properties.read) props.add('read'); if(c.properties.notify) props.add('notify'); if(c.properties.indicate) props.add('indicate'); tiles.add(ListTile( title: Text(c.uuid.toString(), style: TextStyle(fontSize: 15)), subtitle: Text(cname + props.join(', '), style: TextStyle(height: 1.4)), trailing: Icon(Icons.chevron_right), isThreeLine: cname.isNotEmpty, onTap: () => _goto_characteristic(c), )); } return Card( child: Column(children: tiles), margin: EdgeInsets.only(bottom: index < services.length ? 16 : 0), shape: RoundedRectangleBorder(), ); } }
0
mirrored_repositories/stories-app
mirrored_repositories/stories-app/lib/assets.dart
abstract class Assets { static String emptyJson = 'assets/lottie/empty.json'; static String loadingJson = 'assets/lottie/loading.json'; static String writeJson = 'assets/lottie/write.json'; }
0
mirrored_repositories/stories-app
mirrored_repositories/stories-app/lib/main.dart
import 'package:encrypt_shared_preferences/provider.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/material.dart'; import 'package:jokes_app/common/resource/colors.dart'; import 'package:jokes_app/common/resource/fonts.dart'; import 'package:jokes_app/common/utils/printer.dart'; import 'package:jokes_app/di/app_di.dart'; import 'package:jokes_app/ui/main/main_screen.dart'; import 'package:modified_localization/easy_localization.dart'; import 'package:overlay_support/overlay_support.dart'; import 'common/language/language.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized('121234930934-023'); await EncryptedSharedPreferences.initialize('121234930934-023'); await setUpDependencies(); await Firebase.initializeApp(); FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); late final FirebaseMessaging messaging; messaging = FirebaseMessaging.instance; FirebaseMessaging.onMessage.listen( (RemoteMessage message) { printMessage(message.toString()); showSimpleNotification( Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Text( message.notification?.title ?? "", style: primaryTextStyle(color: AppColors.white), ), Text( message.notification?.body ?? "", style: primaryTextStyle(color: AppColors.white), ), ], ), background: AppColors.darkGreen); }, ); runApp( EasyLocalization( supportedLocales: Language.supportedLanguages, path: Language.languagePath, saveLocale: true, startLocale: Language.defaultLanguage, child: const MainScreen(), ), ); } Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async { printMessage("Handling a background message: ${message.messageId}"); }
0
mirrored_repositories/stories-app/lib/data
mirrored_repositories/stories-app/lib/data/database/app_database.dart
import 'dart:io'; import 'package:drift/drift.dart'; import 'package:drift/native.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; import '../../domain/models/cache/story_cache.dart'; part 'app_database.g.dart'; @DriftDatabase(tables: [ StoryCacheTable, ]) class AppDatabase extends _$AppDatabase { AppDatabase() : super(_openConnection()); @override int get schemaVersion => 1; } LazyDatabase _openConnection() { return LazyDatabase( () async { final path = await getApplicationDocumentsDirectory(); final file = File(p.join(path.path, 'db.sqlite')); return NativeDatabase.createInBackground(file, logStatements: true); }, ); }
0
mirrored_repositories/stories-app/lib/data
mirrored_repositories/stories-app/lib/data/database/app_database.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'app_database.dart'; // ignore_for_file: type=lint class $StoryCacheTableTable extends StoryCacheTable with TableInfo<$StoryCacheTableTable, StoryCache> { @override final GeneratedDatabase attachedDatabase; final String? _alias; $StoryCacheTableTable(this.attachedDatabase, [this._alias]); static const VerificationMeta _idMeta = const VerificationMeta('id'); @override late final GeneratedColumn<int> id = GeneratedColumn<int>( 'id', aliasedName, false, type: DriftSqlType.int, requiredDuringInsert: false); static const VerificationMeta _bodyMeta = const VerificationMeta('body'); @override late final GeneratedColumn<String> body = GeneratedColumn<String>( 'body', aliasedName, false, type: DriftSqlType.string, requiredDuringInsert: true); static const VerificationMeta _timeCreateMeta = const VerificationMeta('timeCreate'); @override late final GeneratedColumn<DateTime> timeCreate = GeneratedColumn<DateTime>( 'time_create', aliasedName, false, type: DriftSqlType.dateTime, requiredDuringInsert: true); static const VerificationMeta _categoryIdMeta = const VerificationMeta('categoryId'); @override late final GeneratedColumn<int> categoryId = GeneratedColumn<int>( 'category_id', aliasedName, false, type: DriftSqlType.int, requiredDuringInsert: true); static const VerificationMeta _authorIdMeta = const VerificationMeta('authorId'); @override late final GeneratedColumn<int> authorId = GeneratedColumn<int>( 'author_id', aliasedName, false, type: DriftSqlType.int, requiredDuringInsert: true); static const VerificationMeta _authorNameMeta = const VerificationMeta('authorName'); @override late final GeneratedColumn<String> authorName = GeneratedColumn<String>( 'author_name', aliasedName, false, type: DriftSqlType.string, requiredDuringInsert: true); static const VerificationMeta _titleMeta = const VerificationMeta('title'); @override late final GeneratedColumn<String> title = GeneratedColumn<String>( 'title', aliasedName, false, type: DriftSqlType.string, requiredDuringInsert: true); static const VerificationMeta _viewCountMeta = const VerificationMeta('viewCount'); @override late final GeneratedColumn<int> viewCount = GeneratedColumn<int>( 'view_count', aliasedName, false, type: DriftSqlType.int, requiredDuringInsert: true); static const VerificationMeta _isPremiumMeta = const VerificationMeta('isPremium'); @override late final GeneratedColumn<bool> isPremium = GeneratedColumn<bool>('is_premium', aliasedName, false, type: DriftSqlType.bool, requiredDuringInsert: true, defaultConstraints: GeneratedColumn.constraintsDependsOnDialect({ SqlDialect.sqlite: 'CHECK ("is_premium" IN (0, 1))', SqlDialect.mysql: '', SqlDialect.postgres: '', })); static const VerificationMeta _isFrozenMeta = const VerificationMeta('isFrozen'); @override late final GeneratedColumn<bool> isFrozen = GeneratedColumn<bool>('is_frozen', aliasedName, false, type: DriftSqlType.bool, requiredDuringInsert: true, defaultConstraints: GeneratedColumn.constraintsDependsOnDialect({ SqlDialect.sqlite: 'CHECK ("is_frozen" IN (0, 1))', SqlDialect.mysql: '', SqlDialect.postgres: '', })); static const VerificationMeta _isOwnerMeta = const VerificationMeta('isOwner'); @override late final GeneratedColumn<bool> isOwner = GeneratedColumn<bool>('is_owner', aliasedName, false, type: DriftSqlType.bool, requiredDuringInsert: true, defaultConstraints: GeneratedColumn.constraintsDependsOnDialect({ SqlDialect.sqlite: 'CHECK ("is_owner" IN (0, 1))', SqlDialect.mysql: '', SqlDialect.postgres: '', })); static const VerificationMeta _isPublishedMeta = const VerificationMeta('isPublished'); @override late final GeneratedColumn<bool> isPublished = GeneratedColumn<bool>('is_published', aliasedName, false, type: DriftSqlType.bool, requiredDuringInsert: true, defaultConstraints: GeneratedColumn.constraintsDependsOnDialect({ SqlDialect.sqlite: 'CHECK ("is_published" IN (0, 1))', SqlDialect.mysql: '', SqlDialect.postgres: '', })); @override List<GeneratedColumn> get $columns => [ id, body, timeCreate, categoryId, authorId, authorName, title, viewCount, isPremium, isFrozen, isOwner, isPublished ]; @override String get aliasedName => _alias ?? 'story_cache_table'; @override String get actualTableName => 'story_cache_table'; @override VerificationContext validateIntegrity(Insertable<StoryCache> instance, {bool isInserting = false}) { final context = VerificationContext(); final data = instance.toColumns(true); if (data.containsKey('id')) { context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); } if (data.containsKey('body')) { context.handle( _bodyMeta, body.isAcceptableOrUnknown(data['body']!, _bodyMeta)); } else if (isInserting) { context.missing(_bodyMeta); } if (data.containsKey('time_create')) { context.handle( _timeCreateMeta, timeCreate.isAcceptableOrUnknown( data['time_create']!, _timeCreateMeta)); } else if (isInserting) { context.missing(_timeCreateMeta); } if (data.containsKey('category_id')) { context.handle( _categoryIdMeta, categoryId.isAcceptableOrUnknown( data['category_id']!, _categoryIdMeta)); } else if (isInserting) { context.missing(_categoryIdMeta); } if (data.containsKey('author_id')) { context.handle(_authorIdMeta, authorId.isAcceptableOrUnknown(data['author_id']!, _authorIdMeta)); } else if (isInserting) { context.missing(_authorIdMeta); } if (data.containsKey('author_name')) { context.handle( _authorNameMeta, authorName.isAcceptableOrUnknown( data['author_name']!, _authorNameMeta)); } else if (isInserting) { context.missing(_authorNameMeta); } if (data.containsKey('title')) { context.handle( _titleMeta, title.isAcceptableOrUnknown(data['title']!, _titleMeta)); } else if (isInserting) { context.missing(_titleMeta); } if (data.containsKey('view_count')) { context.handle(_viewCountMeta, viewCount.isAcceptableOrUnknown(data['view_count']!, _viewCountMeta)); } else if (isInserting) { context.missing(_viewCountMeta); } if (data.containsKey('is_premium')) { context.handle(_isPremiumMeta, isPremium.isAcceptableOrUnknown(data['is_premium']!, _isPremiumMeta)); } else if (isInserting) { context.missing(_isPremiumMeta); } if (data.containsKey('is_frozen')) { context.handle(_isFrozenMeta, isFrozen.isAcceptableOrUnknown(data['is_frozen']!, _isFrozenMeta)); } else if (isInserting) { context.missing(_isFrozenMeta); } if (data.containsKey('is_owner')) { context.handle(_isOwnerMeta, isOwner.isAcceptableOrUnknown(data['is_owner']!, _isOwnerMeta)); } else if (isInserting) { context.missing(_isOwnerMeta); } if (data.containsKey('is_published')) { context.handle( _isPublishedMeta, isPublished.isAcceptableOrUnknown( data['is_published']!, _isPublishedMeta)); } else if (isInserting) { context.missing(_isPublishedMeta); } return context; } @override Set<GeneratedColumn> get $primaryKey => {id}; @override StoryCache map(Map<String, dynamic> data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; return StoryCache( id: attachedDatabase.typeMapping .read(DriftSqlType.int, data['${effectivePrefix}id'])!, body: attachedDatabase.typeMapping .read(DriftSqlType.string, data['${effectivePrefix}body'])!, timeCreate: attachedDatabase.typeMapping .read(DriftSqlType.dateTime, data['${effectivePrefix}time_create'])!, categoryId: attachedDatabase.typeMapping .read(DriftSqlType.int, data['${effectivePrefix}category_id'])!, authorId: attachedDatabase.typeMapping .read(DriftSqlType.int, data['${effectivePrefix}author_id'])!, authorName: attachedDatabase.typeMapping .read(DriftSqlType.string, data['${effectivePrefix}author_name'])!, title: attachedDatabase.typeMapping .read(DriftSqlType.string, data['${effectivePrefix}title'])!, viewCount: attachedDatabase.typeMapping .read(DriftSqlType.int, data['${effectivePrefix}view_count'])!, isPremium: attachedDatabase.typeMapping .read(DriftSqlType.bool, data['${effectivePrefix}is_premium'])!, isFrozen: attachedDatabase.typeMapping .read(DriftSqlType.bool, data['${effectivePrefix}is_frozen'])!, isOwner: attachedDatabase.typeMapping .read(DriftSqlType.bool, data['${effectivePrefix}is_owner'])!, isPublished: attachedDatabase.typeMapping .read(DriftSqlType.bool, data['${effectivePrefix}is_published'])!, ); } @override $StoryCacheTableTable createAlias(String alias) { return $StoryCacheTableTable(attachedDatabase, alias); } } class StoryCache extends DataClass implements Insertable<StoryCache> { final int id; final String body; final DateTime timeCreate; final int categoryId; final int authorId; final String authorName; final String title; final int viewCount; final bool isPremium; final bool isFrozen; final bool isOwner; final bool isPublished; const StoryCache( {required this.id, required this.body, required this.timeCreate, required this.categoryId, required this.authorId, required this.authorName, required this.title, required this.viewCount, required this.isPremium, required this.isFrozen, required this.isOwner, required this.isPublished}); @override Map<String, Expression> toColumns(bool nullToAbsent) { final map = <String, Expression>{}; map['id'] = Variable<int>(id); map['body'] = Variable<String>(body); map['time_create'] = Variable<DateTime>(timeCreate); map['category_id'] = Variable<int>(categoryId); map['author_id'] = Variable<int>(authorId); map['author_name'] = Variable<String>(authorName); map['title'] = Variable<String>(title); map['view_count'] = Variable<int>(viewCount); map['is_premium'] = Variable<bool>(isPremium); map['is_frozen'] = Variable<bool>(isFrozen); map['is_owner'] = Variable<bool>(isOwner); map['is_published'] = Variable<bool>(isPublished); return map; } StoryCacheTableCompanion toCompanion(bool nullToAbsent) { return StoryCacheTableCompanion( id: Value(id), body: Value(body), timeCreate: Value(timeCreate), categoryId: Value(categoryId), authorId: Value(authorId), authorName: Value(authorName), title: Value(title), viewCount: Value(viewCount), isPremium: Value(isPremium), isFrozen: Value(isFrozen), isOwner: Value(isOwner), isPublished: Value(isPublished), ); } factory StoryCache.fromJson(Map<String, dynamic> json, {ValueSerializer? serializer}) { serializer ??= driftRuntimeOptions.defaultSerializer; return StoryCache( id: serializer.fromJson<int>(json['id']), body: serializer.fromJson<String>(json['body']), timeCreate: serializer.fromJson<DateTime>(json['timeCreate']), categoryId: serializer.fromJson<int>(json['categoryId']), authorId: serializer.fromJson<int>(json['authorId']), authorName: serializer.fromJson<String>(json['authorName']), title: serializer.fromJson<String>(json['title']), viewCount: serializer.fromJson<int>(json['viewCount']), isPremium: serializer.fromJson<bool>(json['isPremium']), isFrozen: serializer.fromJson<bool>(json['isFrozen']), isOwner: serializer.fromJson<bool>(json['isOwner']), isPublished: serializer.fromJson<bool>(json['isPublished']), ); } @override Map<String, dynamic> toJson({ValueSerializer? serializer}) { serializer ??= driftRuntimeOptions.defaultSerializer; return <String, dynamic>{ 'id': serializer.toJson<int>(id), 'body': serializer.toJson<String>(body), 'timeCreate': serializer.toJson<DateTime>(timeCreate), 'categoryId': serializer.toJson<int>(categoryId), 'authorId': serializer.toJson<int>(authorId), 'authorName': serializer.toJson<String>(authorName), 'title': serializer.toJson<String>(title), 'viewCount': serializer.toJson<int>(viewCount), 'isPremium': serializer.toJson<bool>(isPremium), 'isFrozen': serializer.toJson<bool>(isFrozen), 'isOwner': serializer.toJson<bool>(isOwner), 'isPublished': serializer.toJson<bool>(isPublished), }; } StoryCache copyWith( {int? id, String? body, DateTime? timeCreate, int? categoryId, int? authorId, String? authorName, String? title, int? viewCount, bool? isPremium, bool? isFrozen, bool? isOwner, bool? isPublished}) => StoryCache( id: id ?? this.id, body: body ?? this.body, timeCreate: timeCreate ?? this.timeCreate, categoryId: categoryId ?? this.categoryId, authorId: authorId ?? this.authorId, authorName: authorName ?? this.authorName, title: title ?? this.title, viewCount: viewCount ?? this.viewCount, isPremium: isPremium ?? this.isPremium, isFrozen: isFrozen ?? this.isFrozen, isOwner: isOwner ?? this.isOwner, isPublished: isPublished ?? this.isPublished, ); @override String toString() { return (StringBuffer('StoryCache(') ..write('id: $id, ') ..write('body: $body, ') ..write('timeCreate: $timeCreate, ') ..write('categoryId: $categoryId, ') ..write('authorId: $authorId, ') ..write('authorName: $authorName, ') ..write('title: $title, ') ..write('viewCount: $viewCount, ') ..write('isPremium: $isPremium, ') ..write('isFrozen: $isFrozen, ') ..write('isOwner: $isOwner, ') ..write('isPublished: $isPublished') ..write(')')) .toString(); } @override int get hashCode => Object.hash(id, body, timeCreate, categoryId, authorId, authorName, title, viewCount, isPremium, isFrozen, isOwner, isPublished); @override bool operator ==(Object other) => identical(this, other) || (other is StoryCache && other.id == this.id && other.body == this.body && other.timeCreate == this.timeCreate && other.categoryId == this.categoryId && other.authorId == this.authorId && other.authorName == this.authorName && other.title == this.title && other.viewCount == this.viewCount && other.isPremium == this.isPremium && other.isFrozen == this.isFrozen && other.isOwner == this.isOwner && other.isPublished == this.isPublished); } class StoryCacheTableCompanion extends UpdateCompanion<StoryCache> { final Value<int> id; final Value<String> body; final Value<DateTime> timeCreate; final Value<int> categoryId; final Value<int> authorId; final Value<String> authorName; final Value<String> title; final Value<int> viewCount; final Value<bool> isPremium; final Value<bool> isFrozen; final Value<bool> isOwner; final Value<bool> isPublished; const StoryCacheTableCompanion({ this.id = const Value.absent(), this.body = const Value.absent(), this.timeCreate = const Value.absent(), this.categoryId = const Value.absent(), this.authorId = const Value.absent(), this.authorName = const Value.absent(), this.title = const Value.absent(), this.viewCount = const Value.absent(), this.isPremium = const Value.absent(), this.isFrozen = const Value.absent(), this.isOwner = const Value.absent(), this.isPublished = const Value.absent(), }); StoryCacheTableCompanion.insert({ this.id = const Value.absent(), required String body, required DateTime timeCreate, required int categoryId, required int authorId, required String authorName, required String title, required int viewCount, required bool isPremium, required bool isFrozen, required bool isOwner, required bool isPublished, }) : body = Value(body), timeCreate = Value(timeCreate), categoryId = Value(categoryId), authorId = Value(authorId), authorName = Value(authorName), title = Value(title), viewCount = Value(viewCount), isPremium = Value(isPremium), isFrozen = Value(isFrozen), isOwner = Value(isOwner), isPublished = Value(isPublished); static Insertable<StoryCache> custom({ Expression<int>? id, Expression<String>? body, Expression<DateTime>? timeCreate, Expression<int>? categoryId, Expression<int>? authorId, Expression<String>? authorName, Expression<String>? title, Expression<int>? viewCount, Expression<bool>? isPremium, Expression<bool>? isFrozen, Expression<bool>? isOwner, Expression<bool>? isPublished, }) { return RawValuesInsertable({ if (id != null) 'id': id, if (body != null) 'body': body, if (timeCreate != null) 'time_create': timeCreate, if (categoryId != null) 'category_id': categoryId, if (authorId != null) 'author_id': authorId, if (authorName != null) 'author_name': authorName, if (title != null) 'title': title, if (viewCount != null) 'view_count': viewCount, if (isPremium != null) 'is_premium': isPremium, if (isFrozen != null) 'is_frozen': isFrozen, if (isOwner != null) 'is_owner': isOwner, if (isPublished != null) 'is_published': isPublished, }); } StoryCacheTableCompanion copyWith( {Value<int>? id, Value<String>? body, Value<DateTime>? timeCreate, Value<int>? categoryId, Value<int>? authorId, Value<String>? authorName, Value<String>? title, Value<int>? viewCount, Value<bool>? isPremium, Value<bool>? isFrozen, Value<bool>? isOwner, Value<bool>? isPublished}) { return StoryCacheTableCompanion( id: id ?? this.id, body: body ?? this.body, timeCreate: timeCreate ?? this.timeCreate, categoryId: categoryId ?? this.categoryId, authorId: authorId ?? this.authorId, authorName: authorName ?? this.authorName, title: title ?? this.title, viewCount: viewCount ?? this.viewCount, isPremium: isPremium ?? this.isPremium, isFrozen: isFrozen ?? this.isFrozen, isOwner: isOwner ?? this.isOwner, isPublished: isPublished ?? this.isPublished, ); } @override Map<String, Expression> toColumns(bool nullToAbsent) { final map = <String, Expression>{}; if (id.present) { map['id'] = Variable<int>(id.value); } if (body.present) { map['body'] = Variable<String>(body.value); } if (timeCreate.present) { map['time_create'] = Variable<DateTime>(timeCreate.value); } if (categoryId.present) { map['category_id'] = Variable<int>(categoryId.value); } if (authorId.present) { map['author_id'] = Variable<int>(authorId.value); } if (authorName.present) { map['author_name'] = Variable<String>(authorName.value); } if (title.present) { map['title'] = Variable<String>(title.value); } if (viewCount.present) { map['view_count'] = Variable<int>(viewCount.value); } if (isPremium.present) { map['is_premium'] = Variable<bool>(isPremium.value); } if (isFrozen.present) { map['is_frozen'] = Variable<bool>(isFrozen.value); } if (isOwner.present) { map['is_owner'] = Variable<bool>(isOwner.value); } if (isPublished.present) { map['is_published'] = Variable<bool>(isPublished.value); } return map; } @override String toString() { return (StringBuffer('StoryCacheTableCompanion(') ..write('id: $id, ') ..write('body: $body, ') ..write('timeCreate: $timeCreate, ') ..write('categoryId: $categoryId, ') ..write('authorId: $authorId, ') ..write('authorName: $authorName, ') ..write('title: $title, ') ..write('viewCount: $viewCount, ') ..write('isPremium: $isPremium, ') ..write('isFrozen: $isFrozen, ') ..write('isOwner: $isOwner, ') ..write('isPublished: $isPublished') ..write(')')) .toString(); } } abstract class _$AppDatabase extends GeneratedDatabase { _$AppDatabase(QueryExecutor e) : super(e); late final $StoryCacheTableTable storyCacheTable = $StoryCacheTableTable(this); @override Iterable<TableInfo<Table, Object?>> get allTables => allSchemaEntities.whereType<TableInfo<Table, Object?>>(); @override List<DatabaseSchemaEntity> get allSchemaEntities => [storyCacheTable]; }
0
mirrored_repositories/stories-app/lib/data/data_sources
mirrored_repositories/stories-app/lib/data/data_sources/network/main_network_data_source_impl.dart
import 'package:jokes_app/data/api/api_client.dart'; import '../../../domain/data_sources/network/main_network_data_source.dart'; class MainNetworkDataSourceImpl extends MainNetworkDataSource { final DioClient _client; @override Future<bool> refreshFCMToken(String token) async { final result = await _client.post( "api/v1/user/notification/refreshToken", data: { "token": token, }, ); return result.isSuccessful; } MainNetworkDataSourceImpl({ required DioClient client, }) : _client = client; }
0
mirrored_repositories/stories-app/lib/data/data_sources
mirrored_repositories/stories-app/lib/data/data_sources/network/publish_network_data_source_impl.dart
import 'dart:convert'; import 'package:jokes_app/data/api/api_client.dart'; import 'package:jokes_app/domain/data_sources/network/publish_network_data_source.dart'; import 'package:jokes_app/domain/models/network/category_response.dart'; import '../../../common/utils/printer.dart'; import '../../../domain/models/common/base_response.dart'; class PublishNetworkDataSourceImpl extends PublishNetworkDataSource { final DioClient _client; @override Future<bool> publishStory(String body, String title, int categoryId) async { final response = await _client.post( "api/v1/stories/", data: { "body": body, "title": title, "categoryId": categoryId, }, ); return response.isSuccessful; } PublishNetworkDataSourceImpl({ required DioClient client, }) : _client = client; @override Future<List<CategoryResponse>?> getCategories() async { try { final response = await _client.get("api/v1/categories"); final decoded = BaseListResponse.fromJson(jsonDecode(response.data)); final list = decoded.data.map((e) => CategoryResponse.fromJson(e)); return list.toList(); } catch (e) { printMessage(e.toString()); return null; } } }
0
mirrored_repositories/stories-app/lib/data/data_sources
mirrored_repositories/stories-app/lib/data/data_sources/network/global_network_data_source_impl.dart
import 'dart:convert'; import 'package:jokes_app/data/api/api_client.dart'; import 'package:jokes_app/domain/data_sources/network/global_network_data_source.dart'; import 'package:jokes_app/domain/models/common/base_response.dart'; import 'package:jokes_app/domain/models/network/profile_response.dart'; class GlobalNetworkDataSourceImpl extends GlobalNetworkDataSource { final DioClient _client; @override Future<List<UserResponse>> getTopUsers() async { final response = await _client.get("api/v1/users/topusers"); final decoded = BaseListResponse.fromJson(jsonDecode(response.data)); final list = decoded.data.map((e) => UserResponse.fromJson(e)); return list.toList(); } GlobalNetworkDataSourceImpl({ required DioClient client, }) : _client = client; }
0
mirrored_repositories/stories-app/lib/data/data_sources
mirrored_repositories/stories-app/lib/data/data_sources/network/story_quotes_network_data_source_impl.dart
import 'dart:convert'; import 'package:jokes_app/data/api/api_client.dart'; import 'package:jokes_app/domain/data_sources/network/story_quotes_network_data_source.dart'; import 'package:jokes_app/domain/models/common/base_response.dart'; import 'package:jokes_app/domain/models/network/story_quote_response.dart'; class StoryQuotesNetworkDataSourceImpl extends StoryQuotesNetworkDataSource { final DioClient _client; @override Future<bool> createQuote(int storyId, String body) async { final response = await _client.post( "api/v1/story/quotes", queryParameters: { "storyId": storyId, "body": body, }, ); return response.isSuccessful; } @override Future<List<StoryQuoteResponse>> getQuotes(int storyId) async { final response = await _client.get( "api/v1/story/quotes", queryParameters: { "storyId": storyId, }, ); final decoded = BaseListResponse.fromJson(jsonDecode(response.data)); final list = decoded.data.map((e) => StoryQuoteResponse.fromJson(e)); return list.toList(); } StoryQuotesNetworkDataSourceImpl({ required DioClient client, }) : _client = client; }
0
mirrored_repositories/stories-app/lib/data/data_sources
mirrored_repositories/stories-app/lib/data/data_sources/network/auth_network_data_source_impl.dart
import 'dart:convert'; import 'package:jokes_app/data/api/api_client.dart'; import 'package:jokes_app/domain/data_sources/network/auth_network_data_source.dart'; import 'package:jokes_app/domain/models/network/auth_response.dart'; class AuthNetworkDataSourceImpl extends AuthNetworkDataSource { final DioClient _client; @override Future<AuthResponse> login( String username, String password, String fcmToken) async { final response = await _client.post( "api/token/", data: { "username": username, "password": password, "fcmToken": fcmToken, }, ); final decoded = AuthResponse.fromJson(jsonDecode(response.data)); return decoded; } @override Future<AuthResponse> register( String username, String password, String fcmToken) async { final response = await _client.post( "api/register/", data: { "username": username, "password": password, "fcmToken": fcmToken, }, ); final decoded = AuthResponse.fromJson(jsonDecode(response.data)); return decoded; } AuthNetworkDataSourceImpl({ required DioClient client, }) : _client = client; }
0
mirrored_repositories/stories-app/lib/data/data_sources
mirrored_repositories/stories-app/lib/data/data_sources/network/stories_network_data_source_impl.dart
import 'dart:convert'; import 'package:jokes_app/common/utils/printer.dart'; import 'package:jokes_app/domain/data_sources/network/stories_network_data_source.dart'; import 'package:jokes_app/domain/models/common/base_response.dart'; import 'package:jokes_app/domain/models/network/category_response.dart'; import 'package:jokes_app/domain/models/network/story_response.dart'; import '../../api/api_client.dart'; class StoriesNetworkDataSourceImpl extends StoriesNetworkDataSource { final DioClient _client; @override Future<List<StoryResponse>?> getStories(int? categoryId, int page) async { try { final response = await _client.get( "api/v1/stories", queryParameters: { "categoryId": categoryId, "page": page, }, ); final decoded = BaseListResponse.fromJson(jsonDecode(response.data)); final list = decoded.data.map((e) => StoryResponse.fromJson(e)); return list.toList(); } catch (e) { printMessage(e.toString()); return null; } } StoriesNetworkDataSourceImpl({ required DioClient client, }) : _client = client; @override Future<List<CategoryResponse>?> getCategories() async { try { final response = await _client.get("api/v1/categories"); final decoded = BaseListResponse.fromJson(jsonDecode(response.data)); final list = decoded.data.map((e) => CategoryResponse.fromJson(e)); return list.toList(); } catch (e) { printMessage(e.toString()); return null; } } @override Future<void> setAsRead(int storyId) { return _client.post( "api/v1/story/views", data: { "story_id": storyId, }, ); } }
0
mirrored_repositories/stories-app/lib/data/data_sources
mirrored_repositories/stories-app/lib/data/data_sources/network/view_story_network_data_source_impl.dart
import 'package:jokes_app/data/api/api_client.dart'; import '../../../domain/data_sources/network/view_story_network_data_source.dart'; class ViewStoryNetworkDataSourceImpl extends ViewStoryNetworkDataSource { final DioClient _client; @override Future<bool> unpublish(int storyId, bool state) async { final response = await _client.put( "api/v1/story/visible/$storyId", queryParameters: { "state": state == true ? 1 : 0, }, ); return response.isSuccessful; } ViewStoryNetworkDataSourceImpl({ required DioClient client, }) : _client = client; @override Future<bool> createQuote(int storyId, String body) async { final response = await _client.post( "api/v1/story/quotes", data: { "storyId": storyId, "body": body, }, ); return response.isSuccessful; } @override Future<bool> report(int storyId) async { final res = await _client.post( "api/v1/stories/report", data: { "storyId": storyId, }, ); return res.isSuccessful; } }
0
mirrored_repositories/stories-app/lib/data/data_sources
mirrored_repositories/stories-app/lib/data/data_sources/network/profile_network_data_source_impl.dart
import 'dart:convert'; import 'package:jokes_app/data/api/api_client.dart'; import 'package:jokes_app/domain/data_sources/network/profile_network_data_source.dart'; import 'package:jokes_app/domain/models/network/notification_response.dart'; import 'package:jokes_app/domain/models/network/profile_response.dart'; import 'package:jokes_app/domain/models/network/profile_stats_response.dart'; import '../../../common/utils/printer.dart'; import '../../../domain/models/common/base_response.dart'; import '../../../domain/models/network/category_response.dart'; import '../../../domain/models/network/story_response.dart'; class ProfileNetworkDataSourceImpl extends ProfileNetworkDataSource { final DioClient _client; @override Future<UserResponse> getProfile() async { final response = await _client.get("api/profile/"); final decoded = UserResponse.fromJson(jsonDecode(response.data)); return decoded; } ProfileNetworkDataSourceImpl({ required DioClient client, }) : _client = client; @override Future<ProfileStatsResponse> getStats() async { final response = await _client.get("api/v1/stories/stats"); final decoded = ProfileStatsResponse.fromJson(jsonDecode(response.data)); return decoded; } @override Future<List<StoryResponse>?> getStories( int userId, int? categoryId, int page) async { try { final response = await _client.get( "api/v1/stories/user", queryParameters: { "categoryId": categoryId, "page": page, "userId": userId, }, ); final decoded = BaseListResponse.fromJson(jsonDecode(response.data)); final list = decoded.data.map((e) => StoryResponse.fromJson(e)); return list.toList(); } catch (e) { printMessage(e.toString()); return null; } } @override Future<List<CategoryResponse>?> getCategories(int userId) async { try { final response = await _client.get( "api/v1/user/categories/", queryParameters: { "userId": userId, }, ); final decoded = BaseListResponse.fromJson(jsonDecode(response.data)); final list = decoded.data.map((e) => CategoryResponse.fromJson(e)); return list.toList(); } catch (e) { printMessage(e.toString()); return null; } } @override Future<void> setAsRead(int storyId) { return _client.post( "api/v1/story/views", data: { "story_id": storyId, }, ); } @override Future<List<NotificationResponse>> getNotifications() async { final response = await _client.get("api/v1/user/notification"); final decoded = BaseListResponse.fromJson(jsonDecode(response.data)); final list = decoded.data.map((e) => NotificationResponse.fromJson(e)); return list.toList(); } @override Future<bool> setNotificationRead(int notificationId) async { final response = await _client.post( "api/v1/user/notification", data: { "id": notificationId, }, ); return response.isSuccessful; } }
0
mirrored_repositories/stories-app/lib/data/data_sources
mirrored_repositories/stories-app/lib/data/data_sources/cache/main_data_source_impl.dart
import 'package:encrypt_shared_preferences/provider.dart'; import 'package:jokes_app/common/resource/keys.dart'; import 'package:jokes_app/data/api/api_client.dart'; import 'package:jokes_app/domain/data_sources/cache/main_data_source.dart'; class MainDataSourceImpl extends MainDataSource { final EncryptedSharedPreferences _preferences; @override Stream<String> getToken() => _preferences.stream; MainDataSourceImpl({ required EncryptedSharedPreferences preferences, }) : _preferences = preferences; }
0
mirrored_repositories/stories-app/lib/data/data_sources
mirrored_repositories/stories-app/lib/data/data_sources/cache/profile_cache_data_source_impl.dart
import 'package:encrypt_shared_preferences/provider.dart'; import 'package:jokes_app/domain/data_sources/cache/profile_cache_data_source.dart'; class ProfileCacheDataSourceImpl extends ProfileCacheDataSource { final EncryptedSharedPreferences _preferences; @override Future<void> clearAllCache() { return _preferences.clear(); } ProfileCacheDataSourceImpl({ required EncryptedSharedPreferences preferences, }) : _preferences = preferences; }
0
mirrored_repositories/stories-app/lib/data
mirrored_repositories/stories-app/lib/data/api/api_client.dart
import 'package:dio/dio.dart'; import 'package:dio_logging_interceptor/dio_logging_interceptor.dart'; import 'package:jokes_app/core/session/manager/session_manager.dart'; import 'interceptors.dart'; extension ResponseExt on Response { bool get isSuccessful => statusCode == 200 || statusCode == 201; } class DioClient { final SessionManager _sessionManager; final String _debugUrl = "http://127.0.0.1:8000/"; final String _prodUrl = "http://xaldarof8.pythonanywhere.com/"; final bool _isDebug = false; late Dio _dio; DioClient(this._sessionManager) { _dio = Dio(); _dio.interceptors.add( DioLoggingInterceptor( level: Level.body, compact: false, ), ); _dio.interceptors.add(AuthInterceptor(sessionManager: _sessionManager)); } Future<BaseOptions> _getOptions() async { return BaseOptions( baseUrl: _isDebug ? _debugUrl : _prodUrl, responseType: ResponseType.plain, connectTimeout: _sessionManager.timeout, receiveTimeout: _sessionManager.timeout, headers: { _sessionManager.authorization: _sessionManager.accessToken, }, validateStatus: (code) => _sessionManager.validate(code ?? 0), ); } CancelToken cancelToken() { return CancelToken(); } Future<Response<T>> post<T>(String path, {data, Map<String, dynamic>? queryParameters, Options? options, CancelToken? cancelToken, ProgressCallback? onSendProgress, ProgressCallback? onReceiveProgress}) async { _dio.options = await _getOptions(); return _dio.post<T>(path, data: data, queryParameters: queryParameters, options: options, cancelToken: cancelToken); } Future<Response<T>> get<T>(String path, {Map<String, dynamic>? queryParameters, Options? options, CancelToken? cancelToken, ProgressCallback? onReceiveProgress}) async { _dio.options = await _getOptions(); return _dio.get<T>(path, queryParameters: queryParameters, options: options, cancelToken: cancelToken); } Future<Response<T>> put<T>( String path, { data, Map<String, dynamic>? queryParameters, Options? options, CancelToken? cancelToken, ProgressCallback? onSendProgress, ProgressCallback? onReceiveProgress, }) async { _dio.options = await _getOptions(); return _dio.put(path, data: data, queryParameters: queryParameters); } }
0
mirrored_repositories/stories-app/lib/data
mirrored_repositories/stories-app/lib/data/api/interceptors.dart
import 'package:dio/dio.dart'; import '../../core/session/manager/session_manager.dart'; class AuthInterceptor extends Interceptor { final SessionManager _sessionManager; @override void onError(DioError err, ErrorInterceptorHandler handler) { if (err.response?.statusCode == 401) { _sessionManager.endLocalSession(); } super.onError(err, handler); } AuthInterceptor({ required SessionManager sessionManager, }) : _sessionManager = sessionManager; }
0
mirrored_repositories/stories-app/lib/data
mirrored_repositories/stories-app/lib/data/repositories/story_quotes_repository_impl.dart
import 'package:jokes_app/domain/models/common/domain_result.dart'; import 'package:jokes_app/domain/models/ui/story_quote.dart'; import 'package:jokes_app/domain/repositories/story_quotes_repository.dart'; import '../../domain/data_sources/network/story_quotes_network_data_source.dart'; import '../../domain/mappers/story_quote_mapper.dart'; class StoryQuotesRepositoryImpl extends StoryQuotesRepository { final StoryQuotesNetworkDataSource _networkDataSource; final StoryQuoteMapper _storyQuoteMapper; @override Stream<DomainResult> createQuote(int storyId, String body) async* { try { yield DomainLoading(); final res = await _networkDataSource.createQuote(storyId, body); if (res) { yield DomainSuccess(); } else { yield DomainFail(); } } catch (e) { yield DomainFail(); } } @override Stream<DomainResult> getQuotes(int storyId) async* { try { yield DomainLoading(); final res = await _networkDataSource.getQuotes(storyId); final ui = res.map((e) => _storyQuoteMapper.map(e)); yield DomainSuccess<List<StoryQuote>>(data: ui.toList()); } catch (e) { yield DomainFail(); } } StoryQuotesRepositoryImpl({ required StoryQuotesNetworkDataSource networkDataSource, required StoryQuoteMapper storyQuoteMapper, }) : _networkDataSource = networkDataSource, _storyQuoteMapper = storyQuoteMapper; }
0
mirrored_repositories/stories-app/lib/data
mirrored_repositories/stories-app/lib/data/repositories/main_repository_impl.dart
import 'package:encrypt_shared_preferences/provider.dart'; import 'package:jokes_app/common/resource/keys.dart'; import 'package:jokes_app/domain/data_sources/cache/main_data_source.dart'; import 'package:jokes_app/domain/data_sources/network/main_network_data_source.dart'; import 'package:jokes_app/domain/models/common/app_state.dart'; import 'package:jokes_app/domain/repositories/main_repository.dart'; class MainRepositoryImpl extends MainRepository { final MainDataSource _dataSource; final MainNetworkDataSource _networkDataSource; final EncryptedSharedPreferences _preferences; @override Stream<AppState> getAppState() async* { yield* _dataSource.getToken().map((event) { final token = _preferences.getString(Keys.token); return token == null ? AppState.unAuthorized : AppState.logged; }); } @override Future<bool> isAuthorized() async { return _preferences.getString(Keys.token) == null ? false : true; } @override Future<bool> refreshFCMToken(String token) async { try { final res = await _networkDataSource.refreshFCMToken(token); return res; } catch (e) { return false; } } MainRepositoryImpl({ required MainDataSource dataSource, required MainNetworkDataSource networkDataSource, required EncryptedSharedPreferences preferences, }) : _dataSource = dataSource, _networkDataSource = networkDataSource, _preferences = preferences; }
0
mirrored_repositories/stories-app/lib/data
mirrored_repositories/stories-app/lib/data/repositories/global_repository_impl.dart
import 'package:jokes_app/domain/mappers/profile_mapper.dart'; import 'package:jokes_app/domain/models/common/domain_result.dart'; import 'package:jokes_app/domain/models/ui/profile.dart'; import 'package:jokes_app/domain/repositories/global_repository.dart'; import '../../domain/data_sources/network/global_network_data_source.dart'; class GlobalRepositoryImpl extends GlobalRepository { final GlobalNetworkDataSource _networkDataSource; final UserMapper _userMapper; @override Stream<DomainResult> getTopUsers() async* { try { yield DomainLoading(); final res = await _networkDataSource.getTopUsers(); final ui = res.map((e) => _userMapper.map(e)); yield DomainSuccess<List<User>>(data: ui.toList()); } catch (e) { yield DomainFail(); } } GlobalRepositoryImpl({ required GlobalNetworkDataSource networkDataSource, required UserMapper userMapper, }) : _networkDataSource = networkDataSource, _userMapper = userMapper; }
0
mirrored_repositories/stories-app/lib/data
mirrored_repositories/stories-app/lib/data/repositories/profile_repository_impl.dart
import 'package:jokes_app/domain/data_sources/cache/profile_cache_data_source.dart'; import 'package:jokes_app/domain/data_sources/network/profile_network_data_source.dart'; import 'package:jokes_app/domain/mappers/notification_mapper.dart'; import 'package:jokes_app/domain/mappers/profile_mapper.dart'; import 'package:jokes_app/domain/mappers/profile_stats_mapper.dart'; import 'package:jokes_app/domain/models/common/domain_result.dart'; import 'package:jokes_app/domain/models/ui/notification.dart'; import 'package:jokes_app/domain/models/ui/profile.dart'; import 'package:jokes_app/domain/models/ui/profile_stats.dart'; import 'package:jokes_app/domain/repositories/profile_repository.dart'; import '../../domain/mappers/category_mapper.dart'; import '../../domain/mappers/story_mapper.dart'; import '../../domain/models/ui/category.dart'; import '../../domain/models/ui/story.dart'; class ProfileRepositoryImpl extends ProfileRepository { final ProfileNetworkDataSource _networkDataSource; final ProfileCacheDataSource _cacheDataSource; final UserMapper _profileMapper; final ProfileStatsMapper _profileStatsMapper; final StoryResponseToUiMapper _storyMapper; final CategoryMapper _categoryMapper; final NotificationMapper _notificationMapper; @override Stream<DomainResult> getProfile() async* { try { yield DomainLoading(); final res = await _networkDataSource.getProfile(); final ui = _profileMapper.map(res); yield DomainSuccess<User>(data: ui); } catch (e) { yield DomainFail(); } } @override Stream<DomainResult> getStats() async* { try { yield DomainLoading(); final res = await _networkDataSource.getStats(); final ui = _profileStatsMapper.map(res); yield DomainSuccess<ProfileStats>(data: ui); } catch (e) { yield DomainFail(); } } @override Stream<DomainResult> getStories( int userId, int? categoryId, int page) async* { try { yield DomainLoading(); final res = await _networkDataSource.getStories(userId, categoryId, page); if (res != null) { final mapped = res.map((e) => _storyMapper.map(e)); yield DomainSuccess<List<Story>>(data: mapped.toList()); } } catch (e) { yield DomainFail(); } } @override Stream<DomainResult> getCategories(int userId) async* { try { yield DomainLoading(); final res = await _networkDataSource.getCategories(userId); if (res != null) { final mapped = res.map((e) => _categoryMapper.map(e)); yield DomainSuccess<List<Category>>(data: mapped.toList()); } } catch (e) { yield DomainFail(); } } @override Future<void> setAsRead(int storyId) async { try { _networkDataSource.setAsRead(storyId); } catch (e) { // } } @override Future<void> logout() async { await _cacheDataSource.clearAllCache(); } @override Stream<DomainResult> getNotifications() async* { try { yield DomainLoading(); final res = await _networkDataSource.getNotifications(); final ui = res.map((e) => _notificationMapper.map(e)); yield DomainSuccess<List<UserNotification>>(data: ui.toList()); } catch (e) { yield DomainFail(); } } ProfileRepositoryImpl({ required ProfileNetworkDataSource networkDataSource, required ProfileCacheDataSource cacheDataSource, required UserMapper profileMapper, required ProfileStatsMapper profileStatsMapper, required StoryResponseToUiMapper storyMapper, required CategoryMapper categoryMapper, required NotificationMapper notificationMapper, }) : _networkDataSource = networkDataSource, _cacheDataSource = cacheDataSource, _profileMapper = profileMapper, _profileStatsMapper = profileStatsMapper, _storyMapper = storyMapper, _categoryMapper = categoryMapper, _notificationMapper = notificationMapper; @override Stream<DomainResult> setNotificationRead(int notificationId) async* { try { yield DomainLoading(); final res = await _networkDataSource.setNotificationRead(notificationId); if (res) { yield DomainSuccess(); } else { yield DomainFail(); } } catch (e) { yield DomainFail(); } } }
0
mirrored_repositories/stories-app/lib/data
mirrored_repositories/stories-app/lib/data/repositories/view_story_repository_impl.dart
import 'package:jokes_app/domain/data_sources/network/view_story_network_data_source.dart'; import 'package:jokes_app/domain/models/common/domain_result.dart'; import 'package:jokes_app/domain/repositories/view_story_repository.dart'; class ViewStoryRepositoryImpl extends ViewStoryRepository { final ViewStoryNetworkDataSource _networkDataSource; @override Stream<DomainResult> unpublish(int storyId, bool state) async* { try { yield DomainLoading(); final res = await _networkDataSource.unpublish(storyId, state); if (res) { yield DomainSuccess(); } else { yield DomainFail(); } } catch (e) { yield DomainFail(); } } ViewStoryRepositoryImpl({ required ViewStoryNetworkDataSource networkDataSource, }) : _networkDataSource = networkDataSource; @override Stream<DomainResult> createQuote(int storyId, String body) async* { try { yield DomainLoading(); final res = await _networkDataSource.createQuote(storyId, body); if (res) { yield DomainSuccess(); } else { yield DomainFail(); } } catch (e) { yield DomainFail(); } } @override Future<bool> sendReport(int storyId) async { try { final res = await _networkDataSource.report(storyId); return res; } catch (e) { return false; } } }
0
mirrored_repositories/stories-app/lib/data
mirrored_repositories/stories-app/lib/data/repositories/publish_repository_impl.dart
import 'package:jokes_app/domain/data_sources/network/publish_network_data_source.dart'; import 'package:jokes_app/domain/models/common/domain_result.dart'; import 'package:jokes_app/domain/repositories/publish_repository.dart'; import '../../domain/mappers/category_mapper.dart'; import '../../domain/models/ui/category.dart'; class PublishRepositoryImpl extends PublishRepository { final PublishNetworkDataSource _networkDataSource; final CategoryMapper _categoryMapper; @override Stream<DomainResult> publishStory( String body, String title, int categoryId) async* { try { yield DomainLoading(); final res = await _networkDataSource.publishStory(body, title, categoryId); if (res) { yield DomainSuccess(); } else { yield DomainFail(); } } catch (e) { yield DomainFail(); } } @override Stream<DomainResult> getCategories() async* { try { yield DomainLoading(); final res = await _networkDataSource.getCategories(); if (res != null) { final mapped = res.map((e) => _categoryMapper.map(e)); yield DomainSuccess<List<Category>>(data: mapped.toList()); } } catch (e) { yield DomainFail(); } } PublishRepositoryImpl({ required PublishNetworkDataSource networkDataSource, required CategoryMapper categoryMapper, }) : _networkDataSource = networkDataSource, _categoryMapper = categoryMapper; }
0
mirrored_repositories/stories-app/lib/data
mirrored_repositories/stories-app/lib/data/repositories/auth_repository_impl.dart
import 'package:encrypt_shared_preferences/provider.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:jokes_app/common/resource/keys.dart'; import 'package:jokes_app/domain/data_sources/network/auth_network_data_source.dart'; import 'package:jokes_app/domain/models/common/domain_result.dart'; import 'package:jokes_app/domain/repositories/auth_repository.dart'; import 'package:modified_localization/easy_localization.dart'; class AuthRepositoryImpl extends AuthRepository { final AuthNetworkDataSource _networkDataSource; final EncryptedSharedPreferences _preferences; @override Stream<DomainResult> login(String username, String password) async* { try { yield DomainLoading(); if (username.trim().isEmpty) yield DomainFail(); if (password.trim().isEmpty) yield DomainFail(); final fcmToken = await FirebaseMessaging.instance.getToken(); final res = await _networkDataSource.login( username.trim(), password.trim(), fcmToken ?? ""); _preferences.setString(Keys.token, res.access); yield DomainSuccess(); } catch (e) { yield DomainFail(); } } @override Stream<DomainResult> register(String username, String password) async* { try { yield DomainLoading(); if (username.trim().isEmpty) yield DomainFail(); if (password.trim().isEmpty) yield DomainFail(); final fcmToken = await FirebaseMessaging.instance.getToken(); final res = await _networkDataSource.register( username.trim(), password.trim(), fcmToken ?? ""); _preferences.setString(Keys.token, res.access); yield DomainSuccess(); } catch (e) { yield DomainFail(); } } AuthRepositoryImpl({ required AuthNetworkDataSource networkDataSource, required EncryptedSharedPreferences preferences, }) : _networkDataSource = networkDataSource, _preferences = preferences; }
0
mirrored_repositories/stories-app/lib/data
mirrored_repositories/stories-app/lib/data/repositories/stories_repository_impl.dart
import 'package:jokes_app/domain/data_sources/network/stories_network_data_source.dart'; import 'package:jokes_app/domain/models/common/domain_result.dart'; import 'package:jokes_app/domain/models/ui/category.dart'; import 'package:jokes_app/domain/models/ui/story.dart'; import 'package:jokes_app/domain/repositories/stories_repository.dart'; import '../../domain/mappers/category_mapper.dart'; import '../../domain/mappers/story_mapper.dart'; class StoriesRepositoryImpl extends StoriesRepository { final StoriesNetworkDataSource _networkDataSource; final StoryResponseToUiMapper _storyMapper; final CategoryMapper _categoryMapper; @override Stream<DomainResult> getCategories() async* { try { yield DomainLoading(); final res = await _networkDataSource.getCategories(); if (res != null) { final mapped = res.map((e) => _categoryMapper.map(e)); yield DomainSuccess<List<Category>>(data: mapped.toList()); } } catch (e) { yield DomainFail(); } } @override Stream<DomainResult> getStories(int? categoryId, int page) async* { try { yield DomainLoading(); final res = await _networkDataSource.getStories(categoryId, page); if (res != null) { final mapped = res.map((e) => _storyMapper.map(e)); yield DomainSuccess<List<Story>>(data: mapped.toList()); } } catch (e) { yield DomainFail(); } } StoriesRepositoryImpl({ required StoriesNetworkDataSource networkDataSource, required StoryResponseToUiMapper storyMapper, required CategoryMapper categoryMapper, }) : _networkDataSource = networkDataSource, _storyMapper = storyMapper, _categoryMapper = categoryMapper; @override Future<void> setAsRead(int storyId) async { try { _networkDataSource.setAsRead(storyId); } catch (e) { // } } }
0
mirrored_repositories/stories-app/lib/core
mirrored_repositories/stories-app/lib/core/session/session.dart
abstract class Session { String? get accessToken; String get authorization; int get timeout; bool validate(int code); }
0