repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/Flutter-Foodee-App/lib
mirrored_repositories/Flutter-Foodee-App/lib/Screens/login_screen.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:foodee_app/Screens/main_screen.dart'; import 'package:foodee_app/Screens/signup_screen.dart'; import 'package:google_fonts/google_fonts.dart'; class AuthScreen extends StatelessWidget { const AuthScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: SafeArea( child: Padding( padding: const EdgeInsets.all(15.0), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 50), Text( 'Welcome to Foodee!', style: GoogleFonts.aBeeZee( fontSize: 30, fontWeight: FontWeight.bold, ), ), SizedBox(height: 20), Text( 'Please sign in to continue', style: TextStyle( fontSize: 18, color: Colors.grey[600], ), ), SizedBox(height: 50), TextField( decoration: InputDecoration( prefixIcon: Icon(Icons.alternate_email_rounded), labelText: 'Email', border: OutlineInputBorder( borderRadius: BorderRadius.circular(12), ), ), ), SizedBox(height: 20), TextField( obscureText: true, decoration: InputDecoration( prefixIcon: Icon(Icons.password), labelText: 'Password', border: OutlineInputBorder( borderRadius: BorderRadius.circular(12), ), ), ), SizedBox(height: 60), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ InkWell( onTap: () { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => MainScreen(), )); }, child: Container( width: 300, padding: EdgeInsets.all(10), decoration: BoxDecoration( color: Color(0xfffF28482), borderRadius: BorderRadius.circular(28)), child: Center(child: Text('Sign In')), ), ), ], ), SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text("Don't have an account? "), TextButton( onPressed: () { // Navigate to signup screen Navigator.push( context, MaterialPageRoute( builder: (context) => SignUpScreen(), )); }, child: Text('Sign Up'), ), ], ), ], ), ), ), ), ); } }
0
mirrored_repositories/Flutter-Foodee-App/lib
mirrored_repositories/Flutter-Foodee-App/lib/Screens/detail_screen.dart
import 'package:flutter/material.dart'; import 'package:foodee_app/Screens/main_screen.dart'; import 'package:foodee_app/widgets/flavors.dart'; import 'package:google_fonts/google_fonts.dart'; class DetailScreen extends StatelessWidget { final String imgPath; final String text; const DetailScreen({Key? key, required this.imgPath, required this.text}); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: const Color(0xfffFFEF92), body: SingleChildScrollView( child: Column( children: [ Stack( children: [ Container( decoration: const BoxDecoration( color: Color(0xfffF28482), borderRadius: BorderRadius.only( bottomLeft: Radius.circular(28), bottomRight: Radius.circular(28))), height: 400, width: double.infinity, child: Padding( padding: const EdgeInsets.all(12.0), child: Column( children: [ SizedBox(height: 60), Row( children: [ Text( text, style: GoogleFonts.aBeeZee( fontSize: 25, color: Colors.white), ), Padding( padding: const EdgeInsets.only(left: 150), child: InkWell( onTap: () { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => MainScreen(), )); }, child: Container( padding: EdgeInsets.all(4), decoration: BoxDecoration( color: Color(0xfffF5CAC3), borderRadius: BorderRadius.circular(12)), child: const Icon( Icons.close, color: Color(0xfffF28482), ), ), ), ) ], ), SizedBox(height: 15), Row( children: [ Container( padding: EdgeInsets.all(8), child: Text( 'Classic Taste', style: GoogleFonts.aBeeZee( color: Color(0xfffF28482), fontWeight: FontWeight.w700), ), decoration: BoxDecoration( color: Color(0xfffF7EDE2), borderRadius: BorderRadius.circular(28)), ), ], ), SizedBox(height: 5), Row( children: [ Container( padding: EdgeInsets.all(8), child: Text( 'BestSeller', style: GoogleFonts.aBeeZee( color: Color(0xfffFFFFF), fontWeight: FontWeight.w500), ), decoration: BoxDecoration( color: Color(0xfff84A59D), borderRadius: BorderRadius.circular(28)), ), ], ), ], ), ), ), Padding( padding: const EdgeInsets.only(left: 50, top: 150), child: Image.asset( imgPath, width: 330, ), ) ], ), SizedBox(height: 10), Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Row( children: [ Text( 'Add More Flavors', style: GoogleFonts.aBeeZee(fontSize: 22), ), ], ), ), SizedBox(height: 10), Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: Row( children: [ Flavors( imgPath: "assets/images/cheez.png", text1: 'Cheddar', text2: '+\$0.80'), SizedBox(width: 10), Flavors( imgPath: "assets/images/bacon.png", text1: 'Bacon', text2: '+\$0.80'), SizedBox(width: 10), Flavors( imgPath: "assets/images/onion.png", text1: 'Onion', text2: '+\$0.80'), ], ), ), SizedBox(height: 10), Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( 'Nutritions Facts', style: GoogleFonts.aBeeZee(fontSize: 22), ), Text( '745 Cal', style: GoogleFonts.aBeeZee(fontSize: 22), ), ], ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( '40 g', style: GoogleFonts.aBeeZee( fontSize: 25, ), ), Text( '43 g', style: GoogleFonts.aBeeZee( fontSize: 25, fontWeight: FontWeight.w500), ), Text( '35 g', style: GoogleFonts.aBeeZee( fontSize: 25, fontWeight: FontWeight.w500), ), ], ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( 'total fat 45%', style: GoogleFonts.aBeeZee( fontSize: 12, ), ), Text( 'total carbs 70%', style: GoogleFonts.aBeeZee( fontSize: 12, fontWeight: FontWeight.w500), ), Text( 'protein', style: GoogleFonts.aBeeZee( fontSize: 12, fontWeight: FontWeight.w500), ), ], ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: InkWell( onTap: () { // Handle the "Add to cart" functionality here // You can use this onPressed function to perform any action you desire print('Product added to cart'); }, child: Container( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 15), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( padding: EdgeInsets.all(4), decoration: BoxDecoration( borderRadius: BorderRadius.circular(100), color: Color(0xfffF7EEE4)), child: Text('-')), SizedBox(width: 8), Text( '5', style: TextStyle( fontSize: 15, fontWeight: FontWeight.bold), ), SizedBox(width: 8), Container( decoration: BoxDecoration( color: Color(0xfffF49392), borderRadius: BorderRadius.circular(100)), padding: EdgeInsets.all(4), child: Text( '+', style: TextStyle(color: Colors.white), )), ], ), height: 35, width: 150, decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), border: Border.all(color: Color(0xfffF28482))), ), Container( child: Column( children: [ Text( 'Add to cart', style: GoogleFonts.aBeeZee( color: Color(0xfffFFFFF)), ), Text( '\$32.65', style: GoogleFonts.aBeeZee( color: Color(0xfffFFFFF), fontSize: 9, fontWeight: FontWeight.bold), ) ], ), height: 35, width: 150, decoration: BoxDecoration( color: Color(0xfffF28482), borderRadius: BorderRadius.circular(12), border: Border.all(color: Color(0xfffF28482))), ) ], ), ), height: 40, width: double.infinity, decoration: BoxDecoration( color: Color(0xfffFFFFF), borderRadius: BorderRadius.circular(12)), ), ), ) ], ), ), ); } }
0
mirrored_repositories/Flutter-Foodee-App
mirrored_repositories/Flutter-Foodee-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 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:foodee_app/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/Learning_App
mirrored_repositories/Learning_App/lib/register.dart
import 'package:learning_app/HomePage.dart'; import 'constants.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'rounded_button.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import 'DialogBox.dart'; import 'chat_screen.dart'; class RegistrationScreen extends StatefulWidget { static String id = 'registration_screen'; @override _RegistrationScreenState createState() => _RegistrationScreenState(); } class _RegistrationScreenState extends State<RegistrationScreen> { DialogBox dialogBox = new DialogBox(); final _auth = FirebaseAuth.instance; bool showSpinner = false; String email; String password; @override Widget build(BuildContext context) { return Scaffold( appBar: new AppBar( title: new Text("Register"), centerTitle: true, ), backgroundColor: Colors.white, body: ModalProgressHUD( inAsyncCall: showSpinner, child: Padding( padding: EdgeInsets.symmetric(horizontal: 24.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Hero( tag:'logo', child: Container( //child: Image.asset('images/logo.png'), height: 100.0, ), ), SizedBox( height: 13.0, ), TextField( keyboardType: TextInputType.emailAddress, textAlign: TextAlign.center, onChanged: (value) { email=value; }, decoration:kMessageTextFieldDecoration.copyWith(hintText: 'Enter Your email'), ), SizedBox( height: 8.0, ), TextField( obscureText: true, textAlign: TextAlign.center, onChanged: (value) { password=value; }, decoration: kMessageTextFieldDecoration.copyWith(hintText: 'Enter Your password'), ), SizedBox( height: 24.0, ), RoundedButton( title: 'Register', colour: Colors.orange, onPressed: () async{ // print(email); // print(password); setState(() { showSpinner=true; }); try { final newUser = await _auth.createUserWithEmailAndPassword( email: email, password: password); if(newUser!=null) { Navigator.pushNamed(context, HomePage.id); } dialogBox. information(context,"Congratulations! ","your account has been created successfully"); setState(() { showSpinner=false; }); } catch(e) { dialogBox. information(context,"Error = ",e.toString()); print(e); } }, ), ], ), ), ), ); } }
0
mirrored_repositories/Learning_App
mirrored_repositories/Learning_App/lib/files.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:file_picker/file_picker.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override _MyAppState createState() => new _MyAppState(); } class _MyAppState extends State<MyApp> { final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>(); String _fileName; String _path; Map<String, String> _paths; String _extension; bool _loadingPath = false; bool _multiPick = false; FileType _pickingType = FileType.any; TextEditingController _controller = new TextEditingController(); @override void initState() { super.initState(); _controller.addListener(() => _extension = _controller.text); } void _openFileExplorer() async { setState(() => _loadingPath = true); try { if (_multiPick) { _path = null; _paths = await FilePicker.getMultiFilePath( type: _pickingType, allowedExtensions: (_extension?.isNotEmpty ?? false) ? _extension?.replaceAll(' ', '')?.split(',') : null); } else { _paths = null; _path = await FilePicker.getFilePath( type: _pickingType, allowedExtensions: (_extension?.isNotEmpty ?? false) ? _extension?.replaceAll(' ', '')?.split(',') : null); } } on PlatformException catch (e) { print("Unsupported operation" + e.toString()); } if (!mounted) return; setState(() { _loadingPath = false; _fileName = _path != null ? _path.split('/').last : _paths != null ? _paths.keys.toString() : '...'; }); } void _clearCachedFiles() { FilePicker.clearTemporaryFiles().then((result) { _scaffoldKey.currentState.showSnackBar( SnackBar( backgroundColor: result ? Colors.green : Colors.red, content: Text((result ? 'Temporary files removed with success.' : 'Failed to clean temporary files')), ), ); }); } @override Widget build(BuildContext context) { return new MaterialApp( home: new Scaffold( key: _scaffoldKey, appBar: new AppBar( title: const Text('Upload Files'), centerTitle: true, backgroundColor: Colors.orange, ), body: new Center( child: new Padding( padding: const EdgeInsets.only(left: 10.0, right: 10.0), child: new SingleChildScrollView( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Padding( padding: const EdgeInsets.only(top: 20.0), child: new DropdownButton( hint: new Text('LOAD PATH FROM'), value: _pickingType, items: <DropdownMenuItem>[ new DropdownMenuItem( child: new Text('FROM AUDIO'), value: FileType.audio, ), new DropdownMenuItem( child: new Text('FROM IMAGE'), value: FileType.image, ), new DropdownMenuItem( child: new Text('FROM VIDEO'), value: FileType.video, ), new DropdownMenuItem( child: new Text('FROM MEDIA'), value: FileType.media, ), new DropdownMenuItem( child: new Text('FROM ANY'), value: FileType.any, ), new DropdownMenuItem( child: new Text('CUSTOM FORMAT'), value: FileType.custom, ), ], onChanged: (value) => setState(() { _pickingType = value; if (_pickingType != FileType.custom) { _controller.text = _extension = ''; } })), ), new ConstrainedBox( constraints: BoxConstraints.tightFor(width: 100.0), child: _pickingType == FileType.custom ? new TextFormField( maxLength: 15, autovalidate: true, controller: _controller, decoration: InputDecoration(labelText: 'File extension'), keyboardType: TextInputType.text, textCapitalization: TextCapitalization.none, ) : new Container(), ), new ConstrainedBox( constraints: BoxConstraints.tightFor(width: 200.0), child: new SwitchListTile.adaptive( title: new Text('Pick multiple files', textAlign: TextAlign.right), onChanged: (bool value) => setState(() => _multiPick = value), value: _multiPick, ), ), new Padding( padding: const EdgeInsets.only(top: 50.0, bottom: 20.0), child: Column( children: <Widget>[ new RaisedButton( onPressed: () => _openFileExplorer(), child: new Text("Open file picker"), color: Colors.orange, ), new RaisedButton( onPressed: () => _clearCachedFiles(), child: new Text("Clear temporary files"), color: Colors.orange, ), ], ), ), new Builder( builder: (BuildContext context) => _loadingPath ? Padding( padding: const EdgeInsets.only(bottom: 10.0), child: const CircularProgressIndicator()) : _path != null || _paths != null ? new Container( padding: const EdgeInsets.only(bottom: 30.0), height: MediaQuery.of(context).size.height * 0.50, child: new Scrollbar( child: new ListView.separated( itemCount: _paths != null && _paths.isNotEmpty ? _paths.length : 1, itemBuilder: (BuildContext context, int index) { final bool isMultiPath = _paths != null && _paths.isNotEmpty; final String name = 'File $index: ' + (isMultiPath ? _paths.keys.toList()[index] : _fileName ?? '...'); final path = isMultiPath ? _paths.values.toList()[index].toString() : _path; return new ListTile( title: new Text( name, ), subtitle: new Text(_path), ); }, separatorBuilder: (BuildContext context, int index) => new Divider(), )), ) : new Container(), ), ], ), ), )), ), ); } }
0
mirrored_repositories/Learning_App
mirrored_repositories/Learning_App/lib/rounded_button.dart
import 'package:flutter/material.dart'; class RoundedButton extends StatelessWidget { RoundedButton({this.title, this.colour, @required this.onPressed}); final Color colour; final String title; final Function onPressed; @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.symmetric(vertical: 16.0), child: Material( elevation: 5.0, color: colour, borderRadius: BorderRadius.circular(30.0), child: MaterialButton( onPressed:onPressed, minWidth: 200.0, height: 42.0, child: Text( title, style: TextStyle ( color: Colors.white, ), ), ), ), ); } }
0
mirrored_repositories/Learning_App
mirrored_repositories/Learning_App/lib/chat_screen.dart
import 'package:flutter/material.dart'; import 'constants.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; final _firestore = Firestore.instance; FirebaseUser loggedInUser; class ChatScreen extends StatefulWidget { static const String id = 'chat_screen'; @override _ChatScreenState createState() => _ChatScreenState(); } class _ChatScreenState extends State<ChatScreen> { final messageTextController = TextEditingController(); final _auth = FirebaseAuth.instance; String messageText; @override void initState() { super.initState(); getCurrentUser(); } void getCurrentUser() async { try { final user = await _auth.currentUser(); if (user != null) { loggedInUser = user; } } catch (e) { print(e); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( leading: null, actions: <Widget>[ IconButton( icon: Icon(Icons.close), onPressed: () { _auth.signOut(); Navigator.pop(context); }), ], title: Text('⚡️Chat'), backgroundColor: Colors.orange, centerTitle:true, ), body: SafeArea( child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ MessagesStream(), Container( decoration: kMessageContainerDecoration, child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Expanded( child: TextField( controller: messageTextController, onChanged: (value) { messageText = value; }, decoration: kMessageTextFieldDecoration, ), ), FlatButton( onPressed: () { messageTextController.clear(); _firestore.collection('messages').add({ 'text': messageText, 'sender': loggedInUser.email, }); }, child: Text( 'Send', style: kSendButtonTextStyle, ), ), ], ), ), ], ), ), ); } } class MessagesStream extends StatelessWidget { @override Widget build(BuildContext context) { return StreamBuilder<QuerySnapshot>( stream: _firestore.collection('messages').snapshots(), builder: (context, snapshot) { if (!snapshot.hasData) { return Center( child: CircularProgressIndicator( backgroundColor: Colors.orange, ), ); } final messages = snapshot.data.documents.reversed; List<MessageBubble> messageBubbles = []; for (var message in messages) { final messageText = message.data['text']; final messageSender = message.data['sender']; final currentUser = loggedInUser.email; final messageBubble = MessageBubble( sender: messageSender, text: messageText, isMe: currentUser == messageSender, ); messageBubbles.add(messageBubble); } return Expanded( child: ListView( reverse: true, padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0), children: messageBubbles, ), ); }, ); } } class MessageBubble extends StatelessWidget { MessageBubble({this.sender, this.text, this.isMe}); final String sender; final String text; final bool isMe; @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.all(10.0), child: Column( crossAxisAlignment: isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start, children: <Widget>[ Text( sender, style: TextStyle( fontSize: 12.0, color: Colors.black54, ), ), Material( borderRadius: isMe ? BorderRadius.only( topLeft: Radius.circular(30.0), bottomLeft: Radius.circular(30.0), bottomRight: Radius.circular(30.0)) : BorderRadius.only( bottomLeft: Radius.circular(30.0), bottomRight: Radius.circular(30.0), topRight: Radius.circular(30.0), ), elevation: 5.0, color: isMe ? Colors.orange : Colors.white, child: Padding( padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0), child: Text( text, style: TextStyle( color: isMe ? Colors.white : Colors.black54, fontSize: 15.0, ), ), ), ), ], ), ); } }
0
mirrored_repositories/Learning_App
mirrored_repositories/Learning_App/lib/constants.dart
import 'package:flutter/material.dart'; import 'package:animated_text_kit/animated_text_kit.dart'; const kSendButtonTextStyle = TextStyle( color: Colors.orange, fontWeight: FontWeight.bold, fontSize: 18.0, ); const kMessageTextFieldDecoration = InputDecoration( contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0), hintText: 'Type your message here...', border:InputBorder.none, ); const kMessageContainerDecoration = BoxDecoration( border: Border( top: BorderSide(color: Colors.lightBlueAccent, width: 2.0), ), ); const kTextFieldDecoration = InputDecoration( hintText: 'Enter a value', contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0), border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(32.0)), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.blueAccent, width: 1.0), borderRadius: BorderRadius.all(Radius.circular(32.0)), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.blueAccent, width: 2.0), borderRadius: BorderRadius.all(Radius.circular(32.0)), ), );
0
mirrored_repositories/Learning_App
mirrored_repositories/Learning_App/lib/HomePage.dart
import 'files.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/material.dart'; import 'login.dart'; import 'register.dart'; import 'posts.dart'; import 'chat_screen.dart'; import 'Upload.dart'; //void main() => runApp(HomePage()); class HomePage extends StatefulWidget { static String id = 'welcome_screen'; @override State<StatefulWidget> createState() { return _HomePageState(); } } class _HomePageState extends State<HomePage> { List <PostedC> postedList = []; @override void initState() { // TODO: implement noSuchMethod super.initState(); DatabaseReference postCRef = FirebaseDatabase.instance.reference().child("Posts"); postCRef.once().then((DataSnapshot snap) { var keys = snap.value.keys; var data = snap.value; postedList.clear(); for(var individualKey in keys) { PostedC posts = new PostedC ( data[individualKey]['image'], data[individualKey]['description'], data[individualKey]['date'], data[individualKey]['time'], ); postedList.add(posts); } setState(() { print("Length : $postedList.Length"); }); }); } Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar ( title: new Text("Home"), centerTitle : true, ), backgroundColor:Colors.white, body: new Container( child: postedList.length==0 ? new Text(("No blog Post available")) : new ListView.builder ( itemCount: postedList.length, itemBuilder: (_,index) { return postsU(postedList[index].image,postedList[index].description,postedList[index].date,postedList[index].time); } ), ), bottomNavigationBar: new BottomAppBar( color:Colors.orange, child: new Container( margin: const EdgeInsets.only(left: 40.0 , right: 40.0), child: new Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisSize: MainAxisSize.max, children: <Widget>[ new IconButton( icon: new Icon(Icons.account_circle ), iconSize: 25, color: Colors.white, onPressed: () { Navigator.pushNamed(context, RegistrationScreen.id); }, ), new IconButton( icon: new Icon(Icons.person), iconSize: 25, color: Colors.white, onPressed: () { Navigator.pushNamed(context, LoginScreen.id); }, ), new IconButton( icon: new Icon(Icons.add_a_photo), iconSize: 25, color: Colors.white, onPressed: () { Navigator.push ( context,MaterialPageRoute(builder: (context) { return new UploadPage(); //return new MyApp(); } ) ); }, ), new IconButton( icon: new Icon(Icons.folder), iconSize: 25, color: Colors.white, onPressed: () { Navigator.push ( context,MaterialPageRoute(builder: (context) { //return new UploadPage(); return new MyApp(); } ) ); }, ), new IconButton( icon: new Icon(Icons.chat), iconSize: 25, color: Colors.white, onPressed: () { Navigator.pushNamed(context, ChatScreen.id); }, ), ], ) ), ), ); } Widget postsU(String image,String description,String date,String time) { return new Card ( elevation : 10.0, margin : EdgeInsets.all(15.0), child:new Container ( padding: new EdgeInsets.all(14.0), child: new Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ new Text( date, style: Theme.of(context).textTheme.subtitle, textAlign: TextAlign.center, ), new Text( time, style: Theme.of(context).textTheme.subtitle, textAlign: TextAlign.center, ), ], ), SizedBox(height: 10.0,), new Image.network(image,fit: BoxFit.cover,), SizedBox(height: 10.0,), new Text( description, style: Theme.of(context).textTheme.subhead, textAlign: TextAlign.center, ), ], ), ), ); } }
0
mirrored_repositories/Learning_App
mirrored_repositories/Learning_App/lib/login.dart
import 'package:flutter/material.dart'; import 'package:learning_app/HomePage.dart'; import 'rounded_button.dart'; import 'constants.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import 'DialogBox.dart'; class LoginScreen extends StatefulWidget { static String id = 'login_screen'; @override _LoginScreenState createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { DialogBox dialogBox = new DialogBox(); final _auth = FirebaseAuth.instance; bool showSpinner = false; String email; String password; @override Widget build(BuildContext context) { return Scaffold( appBar: new AppBar( title: new Text("Login"), centerTitle: true, ), backgroundColor: Colors.white, body: ModalProgressHUD( inAsyncCall: showSpinner, child: Padding( padding: EdgeInsets.symmetric(horizontal: 28.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Hero( tag:'logo', child: Container( //child: Image.asset('images/logo.png'), height: 100.0, ), ), SizedBox( height: 13.0, ), TextField( keyboardType: TextInputType.emailAddress, textAlign: TextAlign.center, onChanged: (value) { email=value; }, decoration: kMessageTextFieldDecoration.copyWith(hintText: 'Enter Your email'), ), SizedBox( height: 8.0, ), TextField( obscureText: true, textAlign: TextAlign.center, onChanged: (value) { password=value; }, decoration: kMessageTextFieldDecoration.copyWith(hintText: 'Enter Your password'), ), SizedBox( height: 24.0, ), RoundedButton( title: 'Log In', colour: Colors.orange, onPressed: () async { // print(email); // print(password); setState(() { showSpinner=true; }); try { final user = await _auth.signInWithEmailAndPassword( email: email, password: password); if(user!=null) { Navigator.pushNamed(context, HomePage.id); } dialogBox. information(context,"Logged ","In successfully"); setState(() { showSpinner=false; }); } catch(e) { dialogBox. information(context,"Error = ",e.toString()); print(e); } }, ), ], ), ), ), ); } }
0
mirrored_repositories/Learning_App
mirrored_repositories/Learning_App/lib/main.dart
import 'chat_screen.dart'; import 'login.dart'; import 'package:flutter/material.dart'; import 'HomePage.dart'; import 'register.dart'; void main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp ( title: "Blog App", theme: new ThemeData( primarySwatch: Colors.orange, ), //home:HomePage(), initialRoute: HomePage.id, routes: { HomePage.id:(context) => HomePage(), LoginScreen.id:(context) => LoginScreen(), RegistrationScreen.id:(context) => RegistrationScreen(), ChatScreen.id:(context) => ChatScreen(), }, ); // return MaterialApp( // /* theme: ThemeData.dark().copyWith( // textTheme: TextTheme( // body1: TextStyle(color: Colors.black54), // ), // ),*/ // initialRoute: HomePage.id, // routes: { // HomePage.id:(context) => HomePage(), // LoginScreen.id:(context) => LoginScreen(), // //RegisterScreen.id:(context) => RegisterScreen(), // }, // ); } }
0
mirrored_repositories/Learning_App
mirrored_repositories/Learning_App/lib/posts.dart
class PostedC { String image,description,date,time; PostedC(this.image,this.description,this.date,this.time); }
0
mirrored_repositories/Learning_App
mirrored_repositories/Learning_App/lib/Upload.dart
import 'HomePage.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:image_picker/image_picker.dart'; import 'dart:io'; class UploadPage extends StatefulWidget { State<StatefulWidget> createState() { return _UploadPageState(); } } class _UploadPageState extends State<UploadPage> { String _myValue; String url; File sampleImage; final formKey = new GlobalKey<FormState>(); Future getItem() async { var temp=await ImagePicker.pickImage(source: ImageSource.gallery); setState(() { sampleImage=temp; }); } bool validateAndSave() { final form = formKey.currentState; if(form.validate()) { form.save(); return true; } else { return false; } } void uploadStatusImage() async { if(validateAndSave()) { final StorageReference postImageRef = FirebaseStorage.instance.ref().child("Post Images"); var timeKey = new DateTime.now(); final StorageUploadTask uploadTask = postImageRef.child(timeKey.toString()+".jpg").putFile(sampleImage); var imageUrl= await (await uploadTask.onComplete).ref.getDownloadURL(); url = imageUrl.toString(); print("Image url = "+url); print("our data is"+_myValue); goToHomePage(); saveToDatabase(url); } } void saveToDatabase(url) { var dbTimeKey = new DateTime.now(); var formatDate = new DateFormat('MMM d, yyyy'); var formatTime = new DateFormat('EEEE, hh:mm aaa'); String date = formatDate.format(dbTimeKey); String time = formatTime.format(dbTimeKey); DatabaseReference ref = FirebaseDatabase.instance.reference(); var data = { "image": url, "description":_myValue, "date":date, "time":time, }; ref.child("Posts").push().set(data); } void goToHomePage() { Navigator.push(context, MaterialPageRoute(builder: (context) { return new HomePage(); } ) ); } @override Widget build(BuildContext context) { // TODO: implement build return new Scaffold( appBar: new AppBar( title: new Text("Upload Images"), centerTitle: true, ), body: new Center ( child: sampleImage == null? Text("Select an Item"):enableUpload(), // child: sampleImage == null?enableUpload():Text("Select an Item"), //child : Text(sampleImage == null ? '' : enableUpload()), //child : Text(sampleImage ?? enableUpload())//:enableUpload() //child: new Text(sampleImage!=null?enableUpload():'Default Value'), //child : Text('$sampleImage'), // print($sampleImage); ), floatingActionButton: new FloatingActionButton(onPressed: getItem, tooltip: 'Add Item', child: new Icon(Icons.add_a_photo), ), ); } Widget enableUpload() { return Container( child: new Form( key: formKey, child: Column( children: <Widget>[ Image.file(sampleImage,height: 199.0,width: 660,), SizedBox(height: 15.0,), TextFormField( decoration: new InputDecoration(labelText: "Description"), validator: (value){ return value.isEmpty? 'Image Description is required':null; }, onSaved: (value){ _myValue=value; return _myValue; }, ), SizedBox(height: 15.0,), RaisedButton( elevation: 10.0, child: Text("Add a new Post"), textColor: Colors.white, color: Colors.pink, onPressed: uploadStatusImage, ), ], ), ), ); } }
0
mirrored_repositories/Learning_App
mirrored_repositories/Learning_App/lib/DialogBox.dart
import 'package:flutter/material.dart'; class DialogBox { information(BuildContext context,String title,String description) { return showDialog( context: context, barrierDismissible: true, builder: (BuildContext context) { // return object of type Dialog return AlertDialog( title: Text(title), content: SingleChildScrollView ( child: ListBody( children: <Widget>[ Text(description), ], ), ), actions: <Widget>[ FlatButton ( child: Text("OK"), onPressed: () { return Navigator.pop(context); }, ) ], ); }, ); } }
0
mirrored_repositories/Learning_App
mirrored_repositories/Learning_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:learning_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/casa
mirrored_repositories/casa/lib/main.dart
//@dart=2.9 import 'dart:async'; import 'package:casa/interest_screens/music.dart'; import 'package:casa/interest_screens/music_list.dart'; import 'package:casa/services/confession.dart'; import 'package:casa/welcome_screens/Firstscreen.dart'; import 'package:casa/welcome_screens/Lookingfor.dart'; import 'package:casa/welcome_screens/Profilescreen.dart'; import 'package:casa/welcome_screens/Signup.dart'; import 'package:casa/welcome_screens/login.dart'; import 'package:casa/welcome_screens/uploadconfession.dart'; import 'package:casa/welcome_screens/Welcome.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'Animation/FadeAnimation.dart'; final _auth = FirebaseAuth.instance; final fire = FirebaseFirestore.instance; var list = <String>[]; String username = null; String gender; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatefulWidget { @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { final _CollectionReference = fire.collection("confession"); @override void initState() { super.initState(); localusername(); // TODO: implement initState //getDocs(); try { if (_auth.currentUser.email != null) { print(_auth.currentUser.email); getusername(_auth.currentUser.email); } } catch (e) { print("error adich"); } } // Future<dynamic> getDocs() async { // fire.collection("male").add({ // "name1":" // }) // } Future getusername(String email) async { await fire .collection("music_match") .get() .then((QuerySnapshot querySnapshot) => { querySnapshot.docs.forEach((doc) { if (doc["email"] == email) { print(doc["name"]); username = doc["name"]; } }) }); return username; } localusername() async { SharedPreferences prefs = await SharedPreferences.getInstance(); setState(() { username = prefs.getString('name'); }); } localgender() async { SharedPreferences prefs = await SharedPreferences.getInstance(); setState(() { gender = prefs.getString('gender'); }); } Future getphone(String name) async { String phone; await fire .collection("music_match") .get() .then((QuerySnapshot querySnapshot) => { querySnapshot.docs.forEach((doc) { if (doc["name"] == name) { phone = doc["phone"]; } }) }); return phone; } Future get(String name) async { String phone; await fire .collection("music_match") .get() .then((QuerySnapshot querySnapshot) => { querySnapshot.docs.forEach((doc) { if (doc["name"] == name) { phone = doc["phone"]; } }) }); return phone; } @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( primarySwatch: Colors.blue, ), home: Firstscreen(username: username,)); } }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/welcome_screens/Welcome.dart
import 'package:flutter/material.dart'; class Welcome extends StatefulWidget { @override _WelcomeState createState() => _WelcomeState(); } class _WelcomeState extends State<Welcome> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color.fromRGBO(242, 169, 184, 1), body: Center( child: Image.asset("assets/images/TYRE.png",height: 300,) ), ); } }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/welcome_screens/Firstscreen.dart
//@dart=2.9 import 'dart:async'; import 'package:casa/services/confession.dart'; import 'package:flutter/material.dart'; class Firstscreen extends StatefulWidget { String username; String gender; Firstscreen({String username,String gender}){ this.username=username; this.gender=gender; } @override _FirstscreenState createState() => _FirstscreenState(); } class _FirstscreenState extends State<Firstscreen> { @override void initState() { // TODO: implement initState Timer(Duration(milliseconds: 1500), () { Navigator.push(context, MaterialPageRoute(builder: (_) => Confession(username: widget.username,gender: widget.gender,))); }); super.initState(); } @override Widget build(BuildContext context) { return Scaffold(backgroundColor:Color.fromRGBO(242, 169, 184, 1), body: Center( child:Image.asset('assets/images/logo.png',height: 170,), ), ); } }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/welcome_screens/Signup.dart
//@dart=2.9 import 'dart:math'; import 'package:casa/Animation/FadeAnimation.dart'; import 'package:casa/interest_screens/music.dart'; import 'package:casa/interest_screens/music_list.dart'; import 'package:casa/services/confession.dart'; import 'package:casa/welcome_screens/Lookingfor.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; String warningtext=" "; String content; String target; String time; final _auth = FirebaseAuth.instance; String email; String pass; String name; String phone; String intro; String gender = "MALE"; final fire3 = FirebaseFirestore.instance; class Signupfirebase extends StatefulWidget { @override _SignupfirebaseState createState() => _SignupfirebaseState(); } class _SignupfirebaseState extends State<Signupfirebase> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: Center( child: SingleChildScrollView( child: Container( child: Column( children: <Widget>[ Text( "Casa", style: TextStyle( fontSize: 20, fontStyle: FontStyle.italic, color: Colors.grey), ), Padding( padding: EdgeInsets.fromLTRB(30, 70, 30, 30), child: Column( children: <Widget>[ FadeAnimation( 1.8, Container( padding: EdgeInsets.all(5), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10), boxShadow: [ BoxShadow( color: Color.fromRGBO(143, 148, 251, .2), blurRadius: 20.0, offset: Offset(0, 10)) ]), child: Column( children: <Widget>[ Container( padding: EdgeInsets.all(8.0), child: TextField( onChanged: (value) { name = value; }, decoration: InputDecoration( border: InputBorder.none, hintText: "Name", hintStyle: TextStyle( color: Colors.grey[400])), ), ), Container( padding: EdgeInsets.all(8.0), child: TextField( onChanged: (value) { intro = value; }, decoration: InputDecoration( border: InputBorder.none, hintText: "Introduce yourselves in one line", hintStyle: TextStyle( color: Colors.grey[400])), ), ), Container( padding: EdgeInsets.all(8.0), child: TextField( onChanged: (value) { phone = value; }, decoration: InputDecoration( border: InputBorder.none, hintText: "Phone", hintStyle: TextStyle( color: Colors.grey[400])), ), ), Container( padding: EdgeInsets.all(8.0), decoration: BoxDecoration( border: Border( bottom: BorderSide( color: Colors.grey .withOpacity(0.1)))), child: TextField( onChanged: (value) { email = value; }, decoration: InputDecoration( border: InputBorder.none, hintText: "Email", hintStyle: TextStyle( color: Colors.grey[400])), ), ), Container( padding: EdgeInsets.all(8.0), child: TextField( onChanged: (value) { pass = value; }, decoration: InputDecoration( border: InputBorder.none, hintText: "Password", hintStyle: TextStyle( color: Colors.grey[400])), ), ), ], ), )), SizedBox( height: 30, ), Text('Looking for?'), DropdownButton( hint: Text(gender), items: dropdownItems, onChanged: (val) { setState(() { gender = val; }); }), FadeAnimation( 2, GestureDetector(onTap: ()async{ if(pass.length<6){ setState(() { warningtext="Password should be atleast 6 charracters long"; }); print("hshs"); } String name1, name2, name3, name4, name5; String intro1, intro2, intro3, intro4, intro5; String phone1, phone2, phone3; var random = Random(); int size = 0; if (gender == "MALE") { await fire3 .collection("female").add({ "name":name, "intro":intro, "phone":phone, }); } else { await fire3 .collection("male").add({ "name":name, "intro":intro, "phone":phone, }); } if (gender == "FEMALE") { await fire3 .collection("female") .get() .then( (QuerySnapshot querySnapshot) => { querySnapshot.docs .forEach((doc) { size++; }) }); } else { await fire3 .collection("male") .get() .then( (QuerySnapshot querySnapshot) => { querySnapshot.docs .forEach((doc) { size++; }) }); } int val1 = random.nextInt((size / 3).toInt()); int val2 = random.nextInt((size / 2).toInt()); int val3 = random.nextInt(size); if (val1 == val2) { val2 = val1 + 1; } if (val1 == val3) { val1 = val3 - 1; } if (val1 == val2) { val1 = val2 - 1; } int i = 0; if (gender == "FEMALE") { await fire3 .collection("female") .get() .then( (QuerySnapshot querySnapshot) => { querySnapshot.docs .forEach((doc) { if (i == val1) { name1 = doc["name"]; intro1 = doc["intro"]; phone1 = doc["phone"]; } if (i == val2) { name2 = doc["name"]; intro2 = doc["intro"]; phone2 = doc["phone"]; } if (i == val3) { name3 = doc["name"]; intro3 = doc["intro"]; phone3 = doc["phone"]; } i++; }) }); } if (gender == "MALE") { await fire3 .collection("male") .get() .then( (QuerySnapshot querySnapshot) => { querySnapshot.docs .forEach((doc) { if (i == val1) { name1 = doc["name"]; intro1 = doc["intro"]; phone1 = doc["phone"]; } if (i == val2) { name2 = doc["name"]; intro2 = doc["intro"]; phone2 = doc["phone"]; } if (i == val3) { name3 = doc["name"]; intro3 = doc["intro"]; phone3 = doc["phone"]; } i++; }) }); } // int i = 0; // await fire3 // .collection("music_match") // .get() // .then( // (QuerySnapshot querySnapshot) => { // querySnapshot.docs // .forEach((doc) { // if (i == val1) { // if (doc["gender"] != // gender) { // name1 = doc["name"]; // intro1 = doc["intro"]; // }i++; val1++; // } // if (i == val2) { // if (doc["gender"] != // gender) { // name2 = doc["name"]; // intro2 = doc["intro"]; // } // } // if (i == val3) { // if (doc["gender"] != // gender) { // name3 = doc["name"]; // intro3 = doc["intro"]; // } // } // i++; // }) // }); try{ final newuser = await _auth .createUserWithEmailAndPassword( email: email, password: pass); fire3 .collection("music_match") .doc(name) .set({ "email": email, "name": name, "phone": phone, "intro": intro, "name1": name1, "intro1": intro1, "name2": name2, "intro2": intro2, "name3": name3, "intro3": intro3, "phone1": phone1, "phone2": phone2, "phone3": phone3, }); SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setString('email', email); prefs.setString('name', name); prefs.setString('gender', gender); print(gender); if (newuser != null) { Navigator.push(context, MaterialPageRoute( builder: (context) { return Music(name: name,); })); } }catch(e){setState(() { warningtext="try a different email id"; });} }, child: Container( height: 50, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), gradient: LinearGradient(colors: [ Colors.pink, Colors.pink, ])), child: Center( child: Text( "Sign up", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold), ), ), ), )), SizedBox( height: 70, ), FadeAnimation( 1.5, Text( warningtext, style: TextStyle( color: Color.fromRGBO(143, 148, 251, 1)), )), ], ), ) ], ), ), ), )); } } List<DropdownMenuItem<String>> get dropdownItems { List<DropdownMenuItem<String>> menuItems = [ DropdownMenuItem(child: Text("MALE"), value: "MALE"), DropdownMenuItem(child: Text("FEMALE"), value: "FEMALE"), ]; return menuItems; }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/welcome_screens/Feedback.dart
//@dart=2.9 import 'package:casa/Animation/FadeAnimation.dart'; import 'package:casa/services/confession.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; String content; String target; String time; final fire2 = FirebaseFirestore.instance; class Feedbackformadmin extends StatefulWidget { String username; Feedbackformadmin({String username}){ this.username=username; } @override _FeedbackformadminState createState() => _FeedbackformadminState(); } class _FeedbackformadminState extends State<Feedbackformadmin> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: Center( child: SingleChildScrollView( child: Container( child: Column( children: <Widget>[ Padding( padding: EdgeInsets.fromLTRB(30, 70, 30, 30), child: Column( children: <Widget>[ FadeAnimation( 1.8, Container( padding: EdgeInsets.all(5), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10), boxShadow: [ BoxShadow( color: Color.fromRGBO(143, 148, 251, .2), blurRadius: 20.0, offset: Offset(0, 10)) ]), child: Column( children: <Widget>[ Container(height: 350, padding: EdgeInsets.all(8.0), child: TextField(onChanged: (value){ content=value; }, decoration: InputDecoration( border: InputBorder.none, hintText: "Enter your complaint here", hintStyle: TextStyle(color: Colors.grey[400])), ), ) ], ), )), SizedBox( height: 30, ), FadeAnimation( 2, Container( height: 50, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), gradient: LinearGradient(colors: [ Color.fromRGBO(242, 169, 184, 1), Color.fromRGBO(242, 169, 184, 1), ])), child: Center( child: GestureDetector( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (context) => Confession(username: widget.username)), ); fire2.collection("report").add({ "content":content, }); }, child: Text( "Report", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold), )), ), )), SizedBox( height: 70, ), FadeAnimation( 1.5, Text( "", style: TextStyle( color: Color.fromRGBO(143, 148, 251, 1)), )), ], ), ) ], ), ), ), )); } }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/welcome_screens/Profilescreen.dart
//@dart=2.9 import 'package:casa/interest_screens/music_list.dart'; import 'package:casa/main.dart'; import 'package:casa/services/confession.dart'; import 'package:casa/welcome_screens/Feedback.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:curved_navigation_bar/curved_navigation_bar.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:page_transition/page_transition.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'login.dart'; bool checked=false; class ProfilePage extends StatefulWidget { String name; String gender; ProfilePage({String name,String gender}){ this.name=name; this.gender=gender; } @override MapScreenState createState() => MapScreenState(); } class MapScreenState extends State<ProfilePage> with SingleTickerProviderStateMixin { int index=2; bool _status = true; final FocusNode myFocusNode = FocusNode(); @override void initState() { // TODO: implement initState super.initState(); } @override Widget build(BuildContext context) { return new Scaffold( body: new Container( color: Color.fromRGBO(242, 169, 184, 1), child: new ListView( children: <Widget>[ Column( children: <Widget>[ new Container( height: 250.0, color: Color.fromRGBO(242, 169, 184, 1), child: new Column( children: <Widget>[ Padding( padding: EdgeInsets.only(left: 20.0, top: 20.0), child: new Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Icon( Icons.arrow_back_ios, color: Colors.black, size: 22.0, ), Padding( padding: EdgeInsets.only(left: 25.0), child: new Text('Casa', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20.0, fontFamily: 'sans-serif-light', color: Colors.black)), ) ], )), Padding( padding: EdgeInsets.only(top: 20.0), child: new Stack(fit: StackFit.loose, children: <Widget>[ new Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Container( width: 140.0, height: 140.0, decoration: new BoxDecoration( shape: BoxShape.circle, image: new DecorationImage( image: new ExactAssetImage( 'assets/images/logo.png'), fit: BoxFit.cover, ), )), ], ), Padding( padding: EdgeInsets.only(top: 90.0, right: 100.0), child: new Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ], )), ]), ) ], ), ), new Container( color:Color.fromRGBO(242, 169, 184, 1), child: Padding( padding: EdgeInsets.only(bottom: 25.0), child: new Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Padding( padding: EdgeInsets.only( left: 25.0, right: 25.0, top: 25.0), child: new Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisSize: MainAxisSize.max, children: <Widget>[ new Column( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ ], ), new Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: <Widget>[ Container(), ], ) ], )), Padding( padding: EdgeInsets.only( left: 25.0, right: 25.0, top: 25.0), child: new Row( mainAxisSize: MainAxisSize.max, children: <Widget>[ new Column( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ new Text( 'Name', style: TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold), ), ], ), ], )), Padding( padding: EdgeInsets.only( left: 25.0, right: 25.0, top: 2.0), child: new Row( mainAxisSize: MainAxisSize.max, children: <Widget>[ new Flexible( child: Text( widget.name??"sign up to create an account" ), ), ], )), Padding( padding: EdgeInsets.only( left: 25.0, right: 25.0, top: 25.0), child: new Row( mainAxisSize: MainAxisSize.max, children: <Widget>[ new Column( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ new Text( 'Have any complaints?', style: TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold), ), ], ), ], )), Padding( padding: EdgeInsets.only( left: 25.0, right: 25.0, top: 2.0), child: new Row( mainAxisSize: MainAxisSize.max, children: <Widget>[ new Flexible( child: GestureDetector(onTap: (){ Navigator.push(context, MaterialPageRoute(builder: (_) => Feedbackformadmin(username: widget.name,))); }, child: Text( "Report here",style: TextStyle(color: Colors.lightBlue), ), ), ), ], )), Padding( padding: EdgeInsets.only( left: 25.0, right: 25.0, top: 25.0), child: new Row( mainAxisSize: MainAxisSize.max, children: <Widget>[ new Column( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ Row( children: [ new Text( 'Did you schedule a cofffe date?', style: TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold), ), Container(width: 10, child: CheckboxListTile( value: checked, onChanged: (newValue) async{ var x; setState(() { checked=!checked; }); await FirebaseFirestore.instance.collection("coffee").get().then((QuerySnapshot querySnapshot) => { querySnapshot.docs .forEach((doc) { if(doc["name"]==widget.name){ print(doc["name"]); x=doc.id; } }) }); await fire.collection("coffee").doc(x).delete(); } ), ) ], ), ], ), ], )), !_status ? _getActionButtons() : new Container(), ], ), ), ) ], ), ], ), ), bottomNavigationBar: CurvedNavigationBar( backgroundColor: Color.fromRGBO(242, 169, 184, 1), index: index, items: [ Icon(Icons.music_note, size: 30), Icon(FontAwesomeIcons.solidHeart, size: 30), Icon(Icons.person, size: 30), ], onTap: (index) { setState(() { this.index = index; print(index); }); if (index == 0) { print(widget.name); if (widget.name != null) { Navigator.push( context, PageTransition( type: PageTransitionType.fade, child: Music_list( name: widget.name, ))); } else { Navigator.push( context, PageTransition( type: PageTransitionType.fade, child: Loginfirebase())); } } if(index==1){ Navigator.push(context, PageTransition(type: PageTransitionType.fade, child: Confession(username: widget.name,gender: widget.gender,))); } }, height: MediaQuery.of(context).size.height / 17.5, ),); } @override void dispose() { // Clean up the controller when the Widget is disposed myFocusNode.dispose(); super.dispose(); } Widget _getActionButtons() { return Padding( padding: EdgeInsets.only(left: 25.0, right: 25.0, top: 45.0), child: new Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Expanded( child: Padding( padding: EdgeInsets.only(right: 10.0), child: Container( child: new RaisedButton( child: new Text("Save"), textColor: Color.fromRGBO(242, 169, 184, 1), color: Colors.green, onPressed: () { setState(() { _status = true; FocusScope.of(context).requestFocus(new FocusNode()); }); }, shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0)), )), ), flex: 2, ), Expanded( child: Padding( padding: EdgeInsets.only(left: 10.0), child: Container( child: new RaisedButton( child: new Text("Cancel"), textColor: Colors.white, color: Colors.red, onPressed: () { setState(() { _status = true; FocusScope.of(context).requestFocus(new FocusNode()); }); }, shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0)), )), ), flex: 2, ), ], ), ); } }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/welcome_screens/uploadconfession.dart
//@dart=2.9 import 'package:casa/Animation/FadeAnimation.dart'; import 'package:casa/services/confession.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; String content; String target; String time; final fire2 = FirebaseFirestore.instance; class Login extends StatefulWidget { @override _LoginState createState() => _LoginState(); } class _LoginState extends State<Login> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: Center( child: SingleChildScrollView( child: Container( child: Column( children: <Widget>[ Text("Trust me, no ones gonna know 😉",style: TextStyle(fontSize: 20), ), Text("Confessions need to get approved by the admin to show in the app",style: TextStyle(fontSize: 10), ), Padding( padding: EdgeInsets.fromLTRB(30, 70, 30, 30), child: Column( children: <Widget>[ FadeAnimation( 1.8, Container( padding: EdgeInsets.all(5), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10), boxShadow: [ BoxShadow( color: Color.fromRGBO(143, 148, 251, .2), blurRadius: 20.0, offset: Offset(0, 10)) ]), child: Column( children: <Widget>[ Container( padding: EdgeInsets.all(8.0), decoration: BoxDecoration( border: Border( bottom: BorderSide( color: Colors.grey .withOpacity(0.1)))), child: TextField( onChanged: (value){ target=value; }, decoration: InputDecoration( border: InputBorder.none, hintText: "Who are your mentioning?", hintStyle: TextStyle(color: Colors.grey[400])), ), ), Container(height: 350, padding: EdgeInsets.all(8.0), child: TextField(onChanged: (value){ content=value; }, decoration: InputDecoration( border: InputBorder.none, hintText: "Your confession", hintStyle: TextStyle(color: Colors.grey[400])), ), ) ], ), )), SizedBox( height: 30, ), FadeAnimation( 2, Container( height: 50, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), gradient: LinearGradient(colors: [ Colors.pink, Colors.pink, ])), child: Center( child: GestureDetector( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (context) => Confession()), ); fire2.collection("confession").add({ "content":content, "allowed":false, "target":target, "likes":0, "date":DateTime.now().day.toString(), }); }, child: Text( "Post", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold), )), ), )), SizedBox( height: 70, ), FadeAnimation( 1.5, Text( "", style: TextStyle( color: Color.fromRGBO(143, 148, 251, 1)), )), ], ), ) ], ), ), ), )); } }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/welcome_screens/login.dart
//@dart=2.9 import 'package:casa/Animation/FadeAnimation.dart'; import 'package:casa/interest_screens/music_list.dart'; import 'package:casa/services/confession.dart'; import 'package:casa/welcome_screens/Signup.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:page_transition/page_transition.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../main.dart'; String content; String target; String time; final _auth = FirebaseAuth.instance; String email; String pass; class Loginfirebase extends StatefulWidget { @override _LoginfirebaseState createState() => _LoginfirebaseState(); } class _LoginfirebaseState extends State<Loginfirebase> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: Center( child: SingleChildScrollView( child: Container( child: Column( children: <Widget>[ Text("Casa",style: TextStyle(fontSize: 20), ), Padding( padding: EdgeInsets.fromLTRB(30, 70, 30, 30), child: Column( children: <Widget>[ FadeAnimation( 1.8, Container( padding: EdgeInsets.all(5), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10), boxShadow: [ BoxShadow( color: Color.fromRGBO(143, 148, 251, .2), blurRadius: 20.0, offset: Offset(0, 10)) ]), child: Column( children: <Widget>[ Container( padding: EdgeInsets.all(8.0), decoration: BoxDecoration( border: Border( bottom: BorderSide( color: Colors.grey .withOpacity(0.1)))), child: TextField( onChanged: (value){ email=value; }, decoration: InputDecoration( border: InputBorder.none, hintText: "Email", hintStyle: TextStyle(color: Colors.grey[400])), ), ), Container( padding: EdgeInsets.all(8.0), child: TextField(onChanged: (value){ pass=value; }, decoration: InputDecoration( border: InputBorder.none, hintText: "Password", hintStyle: TextStyle(color: Colors.grey[400])), ), ) ], ), )), SizedBox( height: 30, ), FadeAnimation( 2, Container( height: 50, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), gradient: LinearGradient(colors: [ Colors.pink, Colors.pink, ])), child: Center( child: GestureDetector( onTap: ()async { final user = await _auth.signInWithEmailAndPassword( email: email, password: pass); String username=await getusername(email); print(username); SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setString('email', email); prefs.setString('name', username); var gender="FEMALE"; await fire3 .collection("male") .get() .then( (QuerySnapshot querySnapshot) => { querySnapshot.docs .forEach((doc) { if(doc["name"]==username){ setState(() { gender="MALE"; }); } }) }); prefs.setString('gender', gender); if (user != null) { Navigator.push(context, MaterialPageRoute(builder: (context) { return Music_list(name: username,); })); } }, child: Text( "Login", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold), )), ), )), SizedBox( height: 70, ), FadeAnimation( 1.5, GestureDetector(onTap: (){ Navigator.push(context, PageTransition(type: PageTransitionType.fade, child: Signupfirebase())); }, child: Text( "Dont have an account? Sign up!", style: TextStyle( color: Color.fromRGBO(143, 148, 251, 1)), ), )), ], ), ) ], ), ), ), )); } } Future getusername(String email)async{ await fire.collection("music_match").get().then((QuerySnapshot querySnapshot) => { querySnapshot.docs .forEach((doc) { if(doc["email"]==email){ print(doc["name"]); username=doc["name"]; } }) }); return username; }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/welcome_screens/Lookingfor.dart
//@dart=2.9 import 'dart:math'; import 'package:casa/Animation/FadeAnimation.dart'; import 'package:casa/services/confession.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; String gender; final fire3 = FirebaseFirestore.instance; class Lookingfor extends StatefulWidget { String name; Lookingfor({String name}){ this.name=name; } @override _LookingforState createState() => _LookingforState(); } class _LookingforState extends State<Lookingfor> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: Center( child: SingleChildScrollView( child: Container( child: Column( children: <Widget>[ Text("Im looking for a",style: TextStyle(fontSize: 20,fontStyle: FontStyle.italic,color: Colors.grey), ), DropdownButton(value: "OTHER",items: dropdownItems, onChanged: (val){ gender=val; }), Padding( padding: EdgeInsets.fromLTRB(30, 70, 30, 30), child: Column( children: <Widget>[ FadeAnimation( 2, Container( height: 50, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), gradient: LinearGradient(colors: [ Color.fromRGBO(242, 169, 184, 1), Color.fromRGBO(242, 169, 184, 1), ])), child: Center( child: GestureDetector( onTap: ()async { String name1,name2,name3,name4,name5; String intro1,intro2,intro3,intro4,intro5; var random=Random(); int size=0; await fire3.collection("music_match").get().then((QuerySnapshot querySnapshot) => { querySnapshot.docs.forEach((doc) { size++; }) }); await fire3.collection("music_match").doc(widget.name).update({ "gender":gender, }); }, child: Text( "Proceed", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold), )), ), )), SizedBox( height: 70, ), FadeAnimation( 1.5, Text( "", style: TextStyle( color: Color.fromRGBO(143, 148, 251, 1)), )), ], ), ) ], ), ), ), )); } } List<DropdownMenuItem<String>> get dropdownItems{ List<DropdownMenuItem<String>> menuItems = [ DropdownMenuItem(child: Text("MALE"),value: "MALE"), DropdownMenuItem(child: Text("FEMALE"),value: "FEMALE"), DropdownMenuItem(child: Text("OTHER"),value: "OTHER"), ]; return menuItems; }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/welcome_screens/Coffeedate.dart
//@dart=2.9 import 'package:casa/interest_screens/music_list.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:url_launcher/url_launcher.dart'; final FirebaseFirestore _firestore = FirebaseFirestore.instance; var CollectionReference6 = _firestore.collection("coffee"); class Coffeedate extends StatefulWidget { String username; Coffeedate({String username}) { this.username = username; } @override _CoffeedateState createState() => _CoffeedateState(); } class _CoffeedateState extends State<Coffeedate> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( "People looking for a coffee date", style: TextStyle(fontSize: 16), ), backgroundColor: Color.fromRGBO(242, 169, 184, 1), ), body: StreamBuilder( stream: FirebaseFirestore.instance.collection("coffee").snapshots(), builder: (context, snapshot) { if (snapshot.hasData) { return SingleChildScrollView( scrollDirection: Axis.vertical, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: 12, ), ListView.builder( physics: NeverScrollableScrollPhysics(), shrinkWrap: true, itemBuilder: (BuildContext context, int index) { DocumentSnapshot documentSnapshot = snapshot.data.docs[index]; return documentSnapshot["name"] != widget.username ? Padding( padding: const EdgeInsets.all(8.0), child: Cardconf2( name: documentSnapshot["name"] ?? "test", phone: documentSnapshot["phone"] ?? "test"), ) : Text(""); }, itemCount: snapshot.data.docs.length), ], ), ); } else { return CircularProgressIndicator(); } })); } } class Cardconf2 extends StatefulWidget { String name; String phone; Cardconf2({String name, String phone}) { this.name = name; this.phone = phone; } @override _Cardconf2State createState() => _Cardconf2State(); } class _Cardconf2State extends State<Cardconf2> { bool check = false; @override Widget build(BuildContext context) { return Column( children: [ Container( height: 80, width: MediaQuery.of(context).size.width, decoration: BoxDecoration( borderRadius: BorderRadius.circular(24), color: Colors.white.withOpacity(0.4), boxShadow: [ BoxShadow( color: Color.fromRGBO(242, 169, 184, 1), blurRadius: 12, offset: Offset(0, 12)) ]), // child: Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // Padding( // padding: const EdgeInsets.fromLTRB(9, 15, 0, 0), // child: Text( // "Find a coffee date", // style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20), // ), // ), // SizedBox(height: 90,), // Center(child: Icon(Icons.,size: 100,),), // ], // ), child: Padding( padding: const EdgeInsets.fromLTRB(20, 0, 0, 0), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ SingleChildScrollView( scrollDirection: Axis.horizontal, child: Container(width:MediaQuery.of(context).size.width / 2.2 , child: Text( widget.name, style: TextStyle(fontSize: 18), ), )), SizedBox( width: MediaQuery.of(context).size.width / 3.3, ), Row( children: [ GestureDetector( onTap: () async { String url = "https://wa.me/+91" + widget.phone; await launch(url); }, child: Icon(FontAwesomeIcons.whatsapp)), ], ), ], ), ), ), SizedBox( height: 16, ) ], ); } }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/Animation/FadeAnimation.dart
import 'package:flutter/material.dart'; import 'package:simple_animations/simple_animations/controlled_animation.dart'; import 'package:simple_animations/simple_animations/multi_track_tween.dart'; class FadeAnimation extends StatelessWidget { final double delay; final Widget child; FadeAnimation(this.delay, this.child); @override Widget build(BuildContext context) { final tween = MultiTrackTween([ Track("opacity").add(Duration(milliseconds: 500), Tween(begin: 0.0, end: 1.0)), Track("translateY").add( Duration(milliseconds: 500), Tween(begin: -30.0, end: 0.0), curve: Curves.easeOut) ]); return ControlledAnimation( delay: Duration(milliseconds: (500 * delay).round()), duration: tween.duration, tween: tween, child: child, builderWithChild: (context, child, animation) => Opacity( opacity:1.0, child: Transform.translate( offset: Offset(0, 0.9), child: child ), ), ); } }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/playground/layout.dart
// FutureBuilder( // future: fetchmovies(), // builder: (BuildContext context, AsyncSnapshot snapshot){ // if(snapshot.hasData){ // return ListView.builder(itemCount: snapshot.data.length,itemBuilder: (BuildContext context,int index){ // return Row( // children: [ // Container(height: 250,alignment:Alignment.centerLeft, // child: Card( // child: Image.network("https://image.tmdb.org/t/p/w500"+snapshot.data[index+1]["poster_path"]), // ),), // SizedBox(width: 20,), // Container(width: MediaQuery.of(context).size.width/2, // child: Column(crossAxisAlignment: CrossAxisAlignment.start, // children: [ // Text(snapshot.data[index+1]["original_title"],style: TextStyle(color: Colors.white),), // SizedBox(height: 10,), // Text(snapshot.data[index+11]["release_date"],style: TextStyle(color: Color(0xff868597))), // SizedBox(height: 10,), // Text(snapshot.data[index+1]["overview"],style: TextStyle(color:Color(0xff868597))), // ], // ), // ), // ], // ); // }); // } // return Center(child: CircularProgressIndicator(),); // } // // ),
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/playground/fire.dart
// // // import 'package:flutter/material.dart'; // import 'package:flutter/foundation.dart'; // import 'dart:ui'; // // import 'package:flutter/material.dart'; // import 'package:cloud_firestore/cloud_firestore.dart'; // import 'package:fluttertoast/fluttertoast.dart'; // import 'package:joli/screens/contactemployee.dart'; // import 'package:joli/screens/employeedashboard.dart'; // // class EmployerDashboard extends StatefulWidget { // // static String id='pay_employee_screen'; // // @override // _EmployerDashboardState createState() => _EmployerDashboardState(); // } // // class _EmployerDashboardState extends State<EmployerDashboard> { // static final FirebaseFirestore _firestore = FirebaseFirestore.instance; // static final _CollectionReference = _firestore.collection("employees").doc("employeesinfo").collection("profile"); // static final _DocumentReference = _CollectionReference.doc('profileinfo'); // // String name,district,profession; // @override // Widget build(BuildContext context) { // return SafeArea( // // child: Scaffold( // backgroundColor: Color(0xFFF0F1F3), // body: Padding( // padding: const EdgeInsets.all(15.0), // child: Column( // children: [ // const SizedBox(height: 20.0), // Container( // child: Padding( // padding: const EdgeInsets.all(20.0), // child: Text("Employer Dashboard", // textAlign: TextAlign.left, // style: TextStyle( // fontSize: 30, // fontWeight: FontWeight.bold, // letterSpacing: 0.5, // color: Color(0xFFF0F1F3), // ), // ), // ), // height: 100, // width: 400, // padding: EdgeInsets.symmetric(horizontal: 12,vertical: 6), // decoration: BoxDecoration( // color: Color(0xFF172e4a), // borderRadius: BorderRadius.circular(12), // border: Border.all(color: Color(0xFF172e4a),width: 2), // ), // // ), // const SizedBox(height: 15.0), // // // StreamBuilder( // stream: _CollectionReference.snapshots(), // builder: (context, snapshot) { // if (snapshot.hasData) { // return ListView.builder( // shrinkWrap: true, // itemCount: snapshot.data.docs.length, // itemBuilder: (context, index) { // DocumentSnapshot documentSnapshot = // snapshot.data.docs[index]; // // String _phoneNo =documentSnapshot["phoneNo"]; // return Column( // children: [ // // const SizedBox(height: 10.0,), // RaisedButton( // // color: Colors.white38, // shape: RoundedRectangleBorder( // borderRadius: BorderRadius.circular(16)), // child: Row( // children: <Widget>[ // Expanded( // child: Text(documentSnapshot["Name"],style: TextStyle(color: Colors.black),), // ), // Expanded( // child: Text(documentSnapshot["PhoneNo"],style: TextStyle(color: Colors.black)), // ), // Expanded( // child: Text(documentSnapshot["District"],style: TextStyle(color: Colors.black)), // ), // Expanded( // child: Text( // documentSnapshot["Profession"],style: TextStyle(color: Colors.black)), // ) // ], // ), // onPressed: (){ // navigateToDetail(documentSnapshot); // }, // // ), // ], // ); // }); // } else { // return Align( // alignment: FractionalOffset.bottomCenter, // child: CircularProgressIndicator(), // ); // } // }, // ), // // // // RaisedButton( // // color: Colors.transparent, // // shape: RoundedRectangleBorder( // // borderRadius: BorderRadius.circular(16)), // // child: Text("Create"), // // textColor: Colors.white, // // onPressed: () { // // // // }, // // ), // ] // ), // ), // ), // ); // } // navigateToDetail( DocumentSnapshot employee) { // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => ContactEmployee(employee))); // } // // }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/playground/constants.dart
import 'package:flutter/material.dart'; const kBackgroundColor = Color(0xFF202020); const kPrimaryColor = Color(0xFFFFBD73);
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/playground/login].dart
// Skip to content // Search or jump to… // Pull requests // Issues // Marketplace // Explore // // @unstoppablemallu // afgprogrammer // / // Flutter-Login-Page-Design // Public // Code // Issues // Pull requests // Actions // Projects // Wiki // Security // Insights // Flutter-Login-Page-Design/lib/main.dart // // Kais NEFFATI (Ingenico Partner) Fixing padding problem when keyboard appear // Latest commit b8be1ec on Apr 15, 2020 // History // 1 contributor // 131 lines (128 sloc) 4.86 KB // // import 'package:day13/Animation/FadeAnimation.dart'; // import 'package:flutter/material.dart'; // // void main() => runApp( // MaterialApp( // debugShowCheckedModeBanner: false, // home: HomePage() // ) // ); // // class HomePage extends StatefulWidget { // @override // _HomePageState createState() => _HomePageState(); // } // // class _HomePageState extends State<HomePage> { // @override // Widget build(BuildContext context) { // final width = MediaQuery.of(context).size.width; // return Scaffold( // backgroundColor: Colors.white, // body: SingleChildScrollView( // child: Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: <Widget>[ // Container( // height: 400, // child: Stack( // children: <Widget>[ // Positioned( // top: -40, // height: 400, // width: width, // child: FadeAnimation(1, Container( // decoration: BoxDecoration( // image: DecorationImage( // image: AssetImage('assets/images/background.png'), // fit: BoxFit.fill // ) // ), // )), // ), // Positioned( // height: 400, // width: width+20, // child: FadeAnimation(1.3, Container( // decoration: BoxDecoration( // image: DecorationImage( // image: AssetImage('assets/images/background-2.png'), // fit: BoxFit.fill // ) // ), // )), // ) // ], // ), // ), // Padding( // padding: EdgeInsets.symmetric(horizontal: 40), // child: Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: <Widget>[ // FadeAnimation(1.5, Text("Login", style: TextStyle(color: Color.fromRGBO(49, 39, 79, 1), fontWeight: FontWeight.bold, fontSize: 30),)), // SizedBox(height: 30,), // FadeAnimation(1.7, Container( // decoration: BoxDecoration( // borderRadius: BorderRadius.circular(10), // color: Colors.white, // boxShadow: [ // BoxShadow( // color: Color.fromRGBO(196, 135, 198, .3), // blurRadius: 20, // offset: Offset(0, 10), // ) // ] // ), // child: Column( // children: <Widget>[ // Container( // padding: EdgeInsets.all(10), // decoration: BoxDecoration( // border: Border(bottom: BorderSide( // color: Colors.grey[200] // )) // ), // child: TextField( // decoration: InputDecoration( // border: InputBorder.none, // hintText: "Username", // hintStyle: TextStyle(color: Colors.grey) // ), // ), // ), // Container( // padding: EdgeInsets.all(10), // child: TextField( // decoration: InputDecoration( // border: InputBorder.none, // hintText: "Password", // hintStyle: TextStyle(color: Colors.grey) // ), // ), // ) // ], // ), // )), // SizedBox(height: 20,), // FadeAnimation(1.7, Center(child: Text("Forgot Password?", style: TextStyle(color: Color.fromRGBO(196, 135, 198, 1)),))), // SizedBox(height: 30,), // FadeAnimation(1.9, Container( // height: 50, // margin: EdgeInsets.symmetric(horizontal: 60), // decoration: BoxDecoration( // borderRadius: BorderRadius.circular(50), // color: Color.fromRGBO(49, 39, 79, 1), // ), // child: Center( // child: Text("Login", style: TextStyle(color: Colors.white),), // ), // )), // SizedBox(height: 30,), // FadeAnimation(2, Center(child: Text("Create Account", style: TextStyle(color: Color.fromRGBO(49, 39, 79, .6)),))), // ], // ), // ) // ], // ), // ), // ); // } // } // © 2022 GitHub, Inc. // Terms // Privacy // Security // Status // Docs // Contact GitHub // Pricing // API // Training // Blog // About // Loading complete
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/interest_screens/music_list.dart
//@dart=2.9 //@dart=2.9 import 'dart:ui'; import 'package:casa/services/confession.dart'; import 'package:casa/welcome_screens/Coffeedate.dart'; import 'package:casa/welcome_screens/Profilescreen.dart'; import 'package:casa/welcome_screens/login.dart'; import 'package:page_transition/page_transition.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:casa/welcome_screens/uploadconfession.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:curved_navigation_bar/curved_navigation_bar.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:readmore/readmore.dart'; import '../main.dart'; String gender2; var x; final FirebaseFirestore _firestore = FirebaseFirestore.instance; var CollectionReference2 = _firestore.collection("music_match"); class Music_list extends StatefulWidget { String name; Music_list({String name}){ this.name=name; } @override _Music_listState createState() => _Music_listState(); } class _Music_listState extends State<Music_list> { int index = 0; @override void initState() { // TODO: implement initState final _CollectionReference = _firestore.collection("confession"); super.initState(); localgenderlist(); //isfemale(); } // Future isfemale()async{ // await fire.collection("male").get().then((QuerySnapshot querySnapshot) => { // querySnapshot.docs // .forEach((doc) { // if(doc["name"]==widget.name){ // setState(() { // x=true; // print(x); // }); // } // })});setState(() { // x=false; // });; // print(x); // } localgenderlist() async { SharedPreferences prefs = await SharedPreferences.getInstance(); setState(() { gender2 = prefs.getString('gender'); print(gender2); }); } final _CollectionReference = fire.collection("confession"); @override Widget build(BuildContext context) { return Scaffold( extendBody: true, appBar: AppBar( backgroundColor: Colors.black, elevation: 0, toolbarHeight: 0, ), backgroundColor: Color.fromRGBO(242, 169, 184, 1), body:StreamBuilder(stream:CollectionReference2.snapshots(),builder: (context2,snapshot1){ return StreamBuilder( stream: FirebaseFirestore.instance.collection("confession").snapshots(), builder: (context, snapshot) { if (snapshot.hasData) { return gender2=="MALE"?SingleChildScrollView( scrollDirection: Axis.vertical, child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.fromLTRB(14, 8, 0, 0), child: Row( children: [Icon(FontAwesomeIcons.solidHeart), Text(' Your Top music matches',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 22),), ], ), ), Padding( padding: const EdgeInsets.fromLTRB(0, 15, 0, 0), child: Container( height: 170, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: snapshot1.data.docs.length, itemBuilder: (BuildContext context, int index) { DocumentSnapshot documentSnapshot1 = snapshot1.data.docs[index]; if(documentSnapshot1["name"]==widget.name){return Row( children: [ Cardsmall(content: documentSnapshot1["intro1"],target: documentSnapshot1["name1"],phone:documentSnapshot1["phone1"] ,), Cardsmall(content: documentSnapshot1["intro2"],target: documentSnapshot1["name2"],phone:documentSnapshot1["phone2"] ), Cardsmall(content: documentSnapshot1["intro3"],target: documentSnapshot1["name3"],phone:documentSnapshot1["phone3"] ), ], );} else{ print("UGHHHHH"); return Text("");} }), ), ), Divider( thickness: 1, color: Colors.white.withOpacity(0.3), ), SizedBox( height: 12, ), ListView.builder( physics: NeverScrollableScrollPhysics(), shrinkWrap: true, itemBuilder: (BuildContext context, int index) { DocumentSnapshot documentSnapshot = snapshot.data.docs[index]; return documentSnapshot["allowed"]==true?Padding( padding: const EdgeInsets.all(8.0), child: GestureDetector(onTap: ()async{ int checker=0; var phone=await getphone(widget.name); print(phone); await fire.collection("coffee").get().then((QuerySnapshot querySnapshot) => { querySnapshot.docs .forEach((doc) { if(doc["name"]==widget.name){ checker=1; } }) }); if(checker==0){await fire.collection("coffee").add({ "name":widget.name, "phone":phone, });} Navigator.push( context, PageTransition( type: PageTransitionType.fade, child: Coffeedate(username: widget.name,))); },child: Cardconf(time:documentSnapshot["date"].toString() ,like: documentSnapshot["likes"]??3, name: documentSnapshot["target"]??"test", text: documentSnapshot["content"]??"test")), ):Text("") ; }, itemCount: 1), ], ), ):SingleChildScrollView( scrollDirection: Axis.vertical, child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.fromLTRB(14, 8, 0, 0), child: Row( children: [Icon(FontAwesomeIcons.solidHeart), Text(' Your Top music matches',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 22),), ], ), ), Padding( padding: const EdgeInsets.fromLTRB(0, 15, 0, 0), child: Container( height: 170, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: snapshot1.data.docs.length, itemBuilder: (BuildContext context, int index) { DocumentSnapshot documentSnapshot1 = snapshot1.data.docs[index]; if(documentSnapshot1["name"]==widget.name){return Row( children: [ Cardsmallmale(content: documentSnapshot1["intro1"],target: documentSnapshot1["name1"],phone:documentSnapshot1["phone1"] ,), Cardsmallmale(content: documentSnapshot1["intro2"],target: documentSnapshot1["name2"],phone:documentSnapshot1["phone2"] ), Cardsmallmale(content: documentSnapshot1["intro3"],target: documentSnapshot1["name3"],phone:documentSnapshot1["phone3"] ), ], );} else{ print("UGHHHHH"); return Text("");} }), ), ), Divider( thickness: 1, color: Colors.white.withOpacity(0.3), ), SizedBox( height: 12, ), ListView.builder( physics: NeverScrollableScrollPhysics(), shrinkWrap: true, itemBuilder: (BuildContext context, int index) { DocumentSnapshot documentSnapshot = snapshot.data.docs[index]; return documentSnapshot["allowed"]==true?Padding( padding: const EdgeInsets.all(8.0), child: GestureDetector(onTap: ()async{ int checker=0; var phone=await getphone(widget.name); print(phone); await fire.collection("coffee").get().then((QuerySnapshot querySnapshot) => { querySnapshot.docs .forEach((doc) { if(doc["name"]==widget.name){ checker=1; } }) }); if(checker==0){await fire.collection("coffee").add({ "name":widget.name, "phone":phone, });} Navigator.push( context, PageTransition( type: PageTransitionType.fade, child: Coffeedate(username: widget.name,))); },child: Cardconf(time:documentSnapshot["date"].toString() ,like: documentSnapshot["likes"]??3, name: documentSnapshot["target"]??"test", text: documentSnapshot["content"]??"test")), ):Text("") ; }, itemCount: 1), ], ), ); } else { return CircularProgressIndicator(); } }); },), bottomNavigationBar: CurvedNavigationBar( backgroundColor: Color.fromRGBO(242, 169, 184, 1), index: index, items: [ Icon(Icons.music_note, size: 30), Icon(FontAwesomeIcons.solidHeart, size: 30), Icon(Icons.person, size: 30), ], onTap: (index) { setState(() { this.index = index; if(index==1){ if(widget.name!=null){ Navigator.push(context, PageTransition(type: PageTransitionType.fade, child: Confession(username: widget.name,))); } } if (index == 2) { print(widget.name); if (widget.name != null) { Navigator.push( context, PageTransition( type: PageTransitionType.fade, child:ProfilePage( name: widget.name, ))); } else { Navigator.push( context, PageTransition( type: PageTransitionType.fade, child: ProfilePage(name: widget.name,))); } } }); }, height: MediaQuery.of(context).size.height / 17.5, ), ); } } // StreamBuilder( // stream: _CollectionReference.snapshots(), // builder: (context, snapshot) { // if (snapshot.hasData) { // // return ListView.builder( // shrinkWrap: true, // itemCount: snapshot.data.docs.length, // itemBuilder: (context, index) { // DocumentSnapshot documentSnapshot = // snapshot.data.docs[index]; // // String _phoneNo =documentSnapshot["phoneNo"]; // return Row( // children: [ // SizedBox( // width: 20, // ), // Container( // width: MediaQuery.of(context).size.width / 2, // child: Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // Text( // documentSnapshot["content"], // style: TextStyle(color: Colors.black), // ), // SizedBox( // height: 110, // ),Heart // Text(documentSnapshot["likes"].toString(), // style: TextStyle(color: Color(0xff868597))), // SizedBox( // height: 10, // ), // Text(documentSnapshot["target"], // style: TextStyle(color: Color(0xff868597))), // ], // ), // ), // ], // ); // }); // } else { // return CircularProgressIndicator(); // } // }, // ), class Hearticon extends StatefulWidget { bool check; Hearticon({bool check}) { this.check = check; } @override _HearticonState createState() => _HearticonState(); } class _HearticonState extends State<Hearticon> { hloogys2() { setState(() { widget.check = true; setState(() {}); }); } Widget build(BuildContext context) { return widget.check ? Icon( FontAwesomeIcons.solidHeart, color: Colors.red, size: 30, ) : Icon(FontAwesomeIcons.solidHeart, color: Color.fromRGBO(255, 169, 184, 1)); } } class Cardconf extends StatefulWidget { String text, name; String time; int like; Cardconf({String text, String name, int like,String time}) { this.like = like; this.text = text; this.name = name; this.time=time; } @override _CardconfState createState() => _CardconfState(); } class _CardconfState extends State<Cardconf> { bool check = false; @override Widget build(BuildContext context) { return Column( children: [ Container( height: 350, width: MediaQuery.of(context).size.width, decoration: BoxDecoration( borderRadius: BorderRadius.circular(24), color: Colors.white.withOpacity(0.4), boxShadow: [ BoxShadow( color: Color.fromRGBO(242, 169, 184, 1), blurRadius: 12, offset: Offset(0, 12)) ]), // child: Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // Padding( // padding: const EdgeInsets.fromLTRB(9, 15, 0, 0), // child: Text( // "Find a coffee date", // style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20), // ), // ), // SizedBox(height: 90,), // Center(child: Icon(Icons.,size: 100,),), // ], // ), child: Padding( padding: const EdgeInsets.all(48.0), child: Image.asset("assets/images/COFFEE.png"), ), ), SizedBox( height: 16, ) ], ); } } class Cardsmall extends StatefulWidget { String target; String content; String phone; Cardsmall({String target,String content,String phone}){ this.target=target; this.content=content; this.phone=phone; } @override _CardsmallState createState() => _CardsmallState(); } class _CardsmallState extends State<Cardsmall> { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 0), child: Column( children: [ Container( height: 140, width: MediaQuery.of(context).size.width / 1.5, decoration: BoxDecoration( borderRadius: BorderRadius.circular(24), color: Colors.white.withOpacity(0.4), boxShadow: [ BoxShadow( color: Color.fromRGBO(242, 169, 184, 1), blurRadius: 12, offset: Offset(0, 12)) ]), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.fromLTRB(9, 15, 0, 0), child: Text( '@'+widget.target, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20), ), ), Padding( padding: const EdgeInsets.fromLTRB(15, 12, 12, 0), child: Container( height: 50, child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Text( widget.content, style: TextStyle(fontSize: 12), ))), ), GestureDetector(onTap: ()async{ String url="https://wa.me/+91"+widget.phone; await launch(url); }, child: Container(decoration: BoxDecoration(), width: MediaQuery.of(context).size.width / 1.5 ,child: Padding( padding: const EdgeInsets.fromLTRB(190, 0, 0, 0), child: Row( children: [Text(">>>",style: TextStyle(fontSize: 20),), Icon(FontAwesomeIcons.whatsapp), ], ), )) ), ], ), ), ], ), ); } } class Cardsmallmale extends StatefulWidget { String target; String content; String phone; Cardsmallmale({String target,String content,String phone}){ this.target=target; this.content=content; this.phone=phone; } @override _Cardsmallmale createState() => _Cardsmallmale(); } class _Cardsmallmale extends State<Cardsmallmale> { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 0), child: Column( children: [ Container( height: 140, width: MediaQuery.of(context).size.width / 1.5, decoration: BoxDecoration( borderRadius: BorderRadius.circular(24), color: Colors.white.withOpacity(0.4), boxShadow: [ BoxShadow( color: Color.fromRGBO(242, 169, 184, 1), blurRadius: 12, offset: Offset(0, 12)) ]), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.fromLTRB(9, 15, 0, 0), child: Text( '@'+widget.target, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20), ), ), Padding( padding: const EdgeInsets.fromLTRB(15, 12, 12, 0), child: Container( height: 50, child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Text( widget.content, style: TextStyle(fontSize: 12), ))), ), GestureDetector(onTap: (){ }, child: Container(decoration: BoxDecoration(), width: MediaQuery.of(context).size.width / 1.5 ,child: Padding( padding: const EdgeInsets.fromLTRB(130, 0, 10, 0), child: Row( children: [Text("Wait to get matched back",style: TextStyle(fontSize: 10),), ], ), )) ), ], ), ), ], ), ); } } // import 'dart:math'; // // import 'package:casa/interest_screens/music.dart'; // import 'package:cloud_firestore/cloud_firestore.dart'; // import 'package:flutter/material.dart'; // int indexofnameindoc; // final list = <List<String>>[]; // var list2 = <List<String>>[]; // var listname = <String>[]; // final fire4 = FirebaseFirestore.instance; // var CollectionReference4 = fire4.collection("music"); // var onecount=0; // class Musiclist extends StatefulWidget { // // String name; // Musiclist({String name}){ // this.name=name; // } // // @override // _MusiclistState createState() => _MusiclistState(); // } // // class _MusiclistState extends State<Musiclist> { // // // @override // void initState() { // // TODO: implement initState // getnameindex("adam"); // prints1(indexofnameindoc); // // super.initState(); // } // // Future getdocs() async { // await CollectionReference4.get().then((QuerySnapshot querySnapshot) => { // querySnapshot.docs.forEach((doc) { // list.add(doc["list"].cast<String>()); // }) // }); // list2 = list; // return list2; // } // // Future getnameindex(String name) async { // int count=0; // await CollectionReference4.get().then((QuerySnapshot querySnapshot) => { // querySnapshot.docs.forEach((doc) { // if(doc["name"]==widget.name){ // indexofnameindoc=count; // return count; // }count++; // }) // }); // // } // // // Future getname() async { // await CollectionReference4.get().then((QuerySnapshot querySnapshot) => { // querySnapshot.docs.forEach((doc) { // listname.add(doc["name"]); // }) // }); // // return listname; // } // // Future prints1(int index) async { // var loo = await getdocs(); // String name = "adam"; // var mylist = <String>[]; // mylist = loo[indexofnameindoc]; // mylist.sort(); // int count = 0; // int count2 = 0; // int nameindex = 0; // for (int i = 0; i < loo.length; i++) { // if(i==indexofnameindoc){continue;} // count = 0; // for (int j = 0; j < loo[i].length && j < mylist.length; j++) { // list[i].sort(); // if (list[i][j].toString() == mylist[j].toString()) { // count++; // } // } // // if (count > count2) { // count2 = count; // nameindex = i; // } // } // var toprintname = await getname(); // onecount=nameindex; // if(nameindex>loo.length){ // print(toprintname[loo.length%nameindex]); // } // // // return toprintname[nameindex]; // // } // void prints2() async { // String name2=" "; // var loo = await getdocs(); // String name = "adam"; // var mylist = <String>[]; // mylist = loo[indexofnameindoc]; // mylist.sort(); // int count = 0; // int count2 = 0; // var toprintname; // int nameindex2 = 0; // for (int i = 0; i < loo.length; i++) { // count = 0; // if(i==onecount||i==indexofnameindoc){continue;} // // for (int j = 0; j < loo[i].length && j < mylist.length; j++) { // list[i].sort(); // if (list[i][j].toString() == mylist[j].toString()) { // count++; // } // } // // if (count > count2) { // toprintname = await getname(); // // name2=toprintname[i]??"heyy"; // // } // } // // print(name2); // // // // } // // // @override // Widget build(BuildContext context) { // return Scaffold( // body:FutureBuilder( // future:prints1(indexofnameindoc), // builder: (BuildContext context, AsyncSnapshot snapshot){ // return Center(child: Text(snapshot.data.toString())); // } // ) // ); // } // } Future getphone(String name)async{ String phone; await fire.collection("music_match").get().then((QuerySnapshot querySnapshot) => { querySnapshot.docs .forEach((doc) { if(doc["name"]==name){ phone=doc["phone"]; } }) }); return phone; }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/interest_screens/music.dart
//@dart=2.9 import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:page_transition/page_transition.dart'; import 'music_list.dart'; final growableList = <String>[]; final fire4 = FirebaseFirestore.instance; class Music extends StatefulWidget { String name; Music({String name}){ this.name=name; } @override _MusicState createState() => _MusicState(); } class _MusicState extends State<Music> { bool check11 = false; bool check12 = false; bool check13 = false; bool check14 = false; bool check16 = false; bool check17 = false; bool check18 = false; bool check19 = false; bool check21 = false; bool check22 = false; bool check23 = false; bool check24 = false; bool check26 = false; bool check27 = false; bool check28 = false; bool check29 = false; bool check31 = false; bool check32 = false; bool check33 = false; bool check34 = false; bool check36 = false; bool check37 = false; bool check38 = false; bool check39 = false; bool check41 = false; bool check42 = false; bool check43 = false; bool check44 = false; bool check46 = false; bool check47 = false; bool check48 = false; bool check49 = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.transparent, shadowColor: Colors.transparent, toolbarHeight: 2, ), body: SingleChildScrollView( scrollDirection: Axis.vertical, child: Column( children: [ Container( height: MediaQuery.of(context).size.height / 12.5, width: MediaQuery.of(context).size.width, child: Padding( padding: const EdgeInsets.fromLTRB(20, 20, 20, 0), child: Text( "What type of music do you prefer? Select upto 5 options for options for each quesions"), ), ), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: [ SizedBox( width: MediaQuery.of(context).size.width / 20, ), GestureDetector( onTap: () { growableList.add("pop"); check11 = !check11; setState(() {}); }, child: Chipcard( text: " pop", check: check11, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check12 = !check12; setState(() {}); growableList.add("folk"); }, child: Chipcard( text: " folk", check: check12, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check13 = !check13; setState(() {}); growableList.add("indie"); }, child: Chipcard( text: " indie", check: check13, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check14 = !check14; setState(() {}); growableList.add("rock"); }, child: Chipcard( text: " rock", check: check14, ), ), SizedBox( width: 15, ), ], ), ), SizedBox( height: 0, ), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: [ SizedBox( width: MediaQuery.of(context).size.width / 20, ), GestureDetector( onTap: () { check16 = !check16; setState(() {}); growableList.add("r&b"); }, child: Chipcard( text: " R&B", check: check16, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check17 = !check17; setState(() {}); growableList.add("hindi"); }, child: Chipcard(text: " hindi", check: check17), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check18 = !check18; setState(() {}); growableList.add("malayalam"); }, child: Chipcard( text: " malayalam", check: check18, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check19 = !check19; setState(() {}); growableList.add("romantic"); }, child: Chipcard( text: " romantic", check: check19, ), ), SizedBox( width: 15, ), ], ), ), //done SizedBox( height: 10, ), Container( height: MediaQuery.of(context).size.height / 12.5, width: MediaQuery.of(context).size.width, child: Padding( padding: const EdgeInsets.fromLTRB(20, 20, 20, 0), child: Text("Select your top 5 artists from the following"), ), ), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: [ SizedBox( width: MediaQuery.of(context).size.width / 20, ), GestureDetector( onTap: () { check21 = !check21; setState(() {}); growableList.add("prateek"); }, child: Chipcard( text: " prateek kuhad", check: check21, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check22 = !check22; setState(() {}); growableList.add("bruno"); }, child: Chipcard( text: " bruno mars", check: check22, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check23 = !check23; setState(() {}); growableList.add("lil"); }, child: Chipcard( text: " lil nas x", check: check23, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check24 = !check24; setState(() {}); growableList.add("arijit"); }, child: Chipcard( text: " arijit singh", check: check24, ), ), SizedBox( width: 15, ), ], ), ), SizedBox( height: 0, ), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: [ SizedBox( width: MediaQuery.of(context).size.width / 20, ), GestureDetector( onTap: () { check26 = !check26; setState(() {}); growableList.add("taylor"); }, child: Chipcard( text: " taylor swift", check: check26, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check27 = !check27; setState(() {}); growableList.add("ed"); }, child: Chipcard(text: " ed sheeran", check: check27), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check28 = !check28; setState(() {}); growableList.add("shreya"); }, child: Chipcard( text: " shreya goshal", check: check28, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check29 = !check29; setState(() {}); growableList.add("ritviz"); }, child: Chipcard( text: " ritviz", check: check29, ), ), SizedBox( width: 15, ), ], ), ), SizedBox( height: 10, ), Container( height: MediaQuery.of(context).size.height / 12.5, width: MediaQuery.of(context).size.width, child: Padding( padding: const EdgeInsets.fromLTRB(20, 20, 20, 0), child: Text("Select your top 5 music from the following"), ), ), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: [ SizedBox( width: MediaQuery.of(context).size.width / 20, ), GestureDetector( onTap: () { check31 = !check31; setState(() {}); growableList.add("happier"); }, child: Chipcard( text: " happier", check: check31, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check32 = !check32; setState(() {}); growableList.add("ranjha"); }, child: Chipcard( text: " ranjha", check: check32, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check33 = !check33; setState(() {}); growableList.add("safarnama"); }, child: Chipcard( text: " safarnama", check: check33, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check34 = !check34; setState(() {}); growableList.add("heat"); }, child: Chipcard( text: " heat waves", check: check34, ), ), SizedBox( width: 15, ), ], ), ), SizedBox( height: 0, ), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: [ SizedBox( width: MediaQuery.of(context).size.width / 20, ), GestureDetector( onTap: () { check36 = !check36; setState(() {}); growableList.add("dusk"); }, child: Chipcard( text: " dusk till dawn", check: check36, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check37 = !check37; setState(() {}); growableList.add("inf"); }, child: Chipcard(text: " infinity", check: check37), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check38 = !check38; setState(() {}); growableList.add("ilikme"); }, child: Chipcard( text: " i like me better", check: check38, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check39 = !check39; setState(() {}); growableList.add("srivalli"); }, child: Chipcard( text: " srivalli", check: check39, ), ), SizedBox( width: 15, ), ], ), ), SizedBox( height: 10, ), Container( height: MediaQuery.of(context).size.height / 12.5, width: MediaQuery.of(context).size.width, child: Padding( padding: const EdgeInsets.fromLTRB(20, 20, 20, 0), child: Text("Select your top 5 favourite music bands"), ), ), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: [ SizedBox( width: MediaQuery.of(context).size.width / 20, ), GestureDetector( onTap: () { check41 = !check41; setState(() {}); growableList.add("oned"); }, child: Chipcard( text: " one direction", check: check41, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check42 = !check42; setState(() {}); growableList.add("bts"); }, child: Chipcard( text: " bts", check: check42, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check43 = !check43; setState(() {}); growableList.add("thedoors"); }, child: Chipcard( text: " the doors", check: check43, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check44 = !check44; setState(() {}); growableList.add("nirvana"); }, child: Chipcard( text: " nirvana", check: check44, ), ), SizedBox( width: 15, ), ], ), ), SizedBox( height: 0, ), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: [ SizedBox( width: MediaQuery.of(context).size.width / 20, ), GestureDetector( onTap: () { check46 = !check46; setState(() {}); growableList.add("wcmt"); }, child: Chipcard( text: " when chai met toast", check: check46, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check47 = !check47; setState(() {}); growableList.add("euphoria"); }, child: Chipcard(text: " euphoria", check: check47), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check48 = !check48; setState(() {}); growableList.add("agnee"); }, child: Chipcard( text: " agnee", check: check48, ), ), SizedBox( width: 15, ), GestureDetector( onTap: () { check49 = !check49; setState(() {}); growableList.add("black"); }, child: Chipcard( text: " blackpink", check: check49, ), ), SizedBox( width: 15, ), ], ), ), SizedBox(height: 20,), GestureDetector(onTap: (){ print(growableList); fire4.collection("music").doc(widget.name).set({ "list":growableList, }); Navigator.push( context, PageTransition( type: PageTransitionType.fade, child: Music_list( name: widget.name, ))); }, child: Container( height: 40,width: 150, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), gradient: LinearGradient(colors: [ Color.fromRGBO(242, 169, 184, 1), Color.fromRGBO(242, 169, 184, 1), ])), child: Center( child: Text( "Proceed", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold), ), ), ), ), ], ), )); } } class Chipcard extends StatefulWidget { bool check; String text; Chipcard({String text, bool check}) { this.text = text; this.check = check; } @override _ChipcardState createState() => _ChipcardState(); } class _ChipcardState extends State<Chipcard> { @override Widget build(BuildContext context) { return Chip( backgroundColor: widget.check == true ? Color.fromRGBO(242, 169, 184, 1) : Colors.grey.withOpacity(0.3), label: Text(widget.text), ); } }
0
mirrored_repositories/casa/lib
mirrored_repositories/casa/lib/services/confession.dart
//@dart=2.9 import 'dart:ui'; import 'package:casa/interest_screens/music_list.dart'; import 'package:casa/welcome_screens/Profilescreen.dart'; import 'package:casa/welcome_screens/Signup.dart'; import 'package:casa/welcome_screens/login.dart'; import 'package:casa/welcome_screens/uploadconfession.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:curved_navigation_bar/curved_navigation_bar.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:readmore/readmore.dart'; import 'package:page_transition/page_transition.dart'; import '../main.dart'; final _auth = FirebaseAuth.instance; final FirebaseFirestore _firestore = FirebaseFirestore.instance; var CollectionReference2 = _firestore.collection("trending"); class Confession extends StatefulWidget { String username; String gender; Confession({String username,String gender }) { this.username = username; this.gender=gender; } @override _ConfessionState createState() => _ConfessionState(); } class _ConfessionState extends State<Confession> { int index = 1; @override void initState() { // TODO: implement initState final _CollectionReference = _firestore.collection("confession"); super.initState(); } final _CollectionReference = fire.collection("confession"); @override Widget build(BuildContext context) { return Scaffold( extendBody: true, appBar: AppBar( backgroundColor: Colors.black, elevation: 0, toolbarHeight: 0, ), backgroundColor: Color.fromRGBO(242, 169, 184, 1), body: StreamBuilder( stream: CollectionReference2.snapshots(), builder: (context2, snapshot1) { return StreamBuilder( stream: FirebaseFirestore.instance .collection("confession") .snapshots(), builder: (context, snapshot) { if (snapshot.hasData) { return SingleChildScrollView( scrollDirection: Axis.vertical, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.fromLTRB(14, 8, 0, 0), child: Row( children: [ Icon(FontAwesomeIcons.solidHeart), GestureDetector( onTap: () { }, child: Text( ' Trending', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 22), )), ], ), ), Padding( padding: const EdgeInsets.fromLTRB(0, 15, 0, 0), child: Container( height: 180, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: snapshot1.data.docs.length, itemBuilder: (BuildContext context, int index) { DocumentSnapshot documentSnapshot1 = snapshot1.data.docs[index]; return Cardsmall( content: documentSnapshot1["content"], target: documentSnapshot1["target"], ); }), ), ), Divider( thickness: 1, color: Colors.white.withOpacity(0.3), ), SizedBox( height: 12, ), ListView.builder( physics: NeverScrollableScrollPhysics(), shrinkWrap: true, itemBuilder: (BuildContext context, int index) { DocumentSnapshot documentSnapshot = snapshot.data.docs[index]; return documentSnapshot["allowed"] == true ? Padding( padding: const EdgeInsets.all(8.0), child: Cardconf( time: documentSnapshot["date"] .toString(), like: documentSnapshot["likes"] ?? 3, name: documentSnapshot["target"] ?? "test", text: documentSnapshot["content"] ?? "test"), ) : Text(""); }, itemCount: snapshot.data.docs.length), ], ), ); } else { return Center(child: CupertinoActivityIndicator()); } }); }, ), floatingActionButton: FloatingActionButton( onPressed: () async{ var x; int i=0; final list = <String>[]; Map<int,String> map=Map(); await FirebaseFirestore.instance.collection("male").get().then((QuerySnapshot querySnapshot) => { querySnapshot.docs.forEach((doc) { x= doc["name"]; if(x=="Abhishek S Kurup"){ FirebaseFirestore.instance.collection("male").doc(doc.id).delete(); } list.add(x); }) }); print(list); Navigator.push( context, MaterialPageRoute(builder: (context) => Login()), ); }, child: Icon(FontAwesomeIcons.plus), backgroundColor: Color.fromRGBO(255, 145, 184, 1), ), bottomNavigationBar: CurvedNavigationBar( backgroundColor: Color.fromRGBO(242, 169, 184, 1), index: index, items: [ Icon(Icons.music_note, size: 30), Icon(FontAwesomeIcons.solidHeart, size: 30), Icon(Icons.person, size: 30), ], onTap: (index) { setState(() { this.index = index; print(index); }); if (index == 0) { print(widget.username); if (widget.username != null) { Navigator.push( context, PageTransition( type: PageTransitionType.fade, child: Music_list( name: widget.username, ))); } else { Navigator.push( context, PageTransition( type: PageTransitionType.fade, child: Loginfirebase())); } } if (index == 2) { print(widget.username); if (widget.username != null) { Navigator.push( context, PageTransition( type: PageTransitionType.fade, child: ProfilePage(gender: widget.gender, name: widget.username, ))); } else { Navigator.push( context, PageTransition( type: PageTransitionType.fade, child: ProfilePage( name:widget.username, ))); } } }, height: MediaQuery.of(context).size.height / 17.5, ), ); } } // StreamBuilder( // stream: _CollectionReference.snapshots(), // builder: (context, snapshot) { // if (snapshot.hasData) { // // return ListView.builder( // shrinkWrap: true, // itemCount: snapshot.data.docs.length, // itemBuilder: (context, index) { // DocumentSnapshot documentSnapshot = // snapshot.data.docs[index]; // // String _phoneNo =documentSnapshot["phoneNo"]; // return Row( // children: [ // SizedBox( // width: 20, // ), // Container( // width: MediaQuery.of(context).size.width / 2, // child: Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // Text( // documentSnapshot["content"], // style: TextStyle(color: Colors.black), // ), // SizedBox( // height: 110, // ),Heart // Text(documentSnapshot["likes"].toString(), // style: TextStyle(color: Color(0xff868597))), // SizedBox( // height: 10, // ), // Text(documentSnapshot["target"],CurvedNavigationBar // style: TextStyle(color: Color(0xff868597))), // ], // ), // ), // ], // ); // }); // } else { // return CircularProgressIndicator(); // } // }, // ), class Hearticon extends StatefulWidget { bool check; Hearticon({bool check}) { this.check = check; } @override _HearticonState createState() => _HearticonState(); } class _HearticonState extends State<Hearticon> { hloogys2() { setState(() { widget.check = true; setState(() {}); }); } Widget build(BuildContext context) { return widget.check ? Icon( FontAwesomeIcons.solidHeart, color: Colors.red, size: 30, ) : Icon(FontAwesomeIcons.solidHeart, color: Color.fromRGBO(255, 169, 184, 1)); } } class Cardconf extends StatefulWidget { String text, name; String time; int like; Cardconf({String text, String name, int like, String time}) { this.like = like; this.text = text; this.name = name; this.time = time; } @override _CardconfState createState() => _CardconfState(); } class _CardconfState extends State<Cardconf> { bool check = false; @override Widget build(BuildContext context) { return Column( children: [ Container( height: 350, width: MediaQuery.of(context).size.width, decoration: BoxDecoration( borderRadius: BorderRadius.circular(24), color: Colors.white.withOpacity(0.4), boxShadow: [ BoxShadow( color: Color.fromRGBO(242, 169, 184, 1), blurRadius: 12, offset: Offset(0, 12)) ]), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.fromLTRB(9, 15, 0, 0), child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Text( '@' + widget.name, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20), ), ), ), Padding( padding: const EdgeInsets.fromLTRB(15, 12, 12, 18), child: Container( height: 240, child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Text( widget.text, textAlign: TextAlign.justify, style: TextStyle(fontSize: 18), ))), ), Row( children: [ Padding( padding: const EdgeInsets.all(8.0), child: Text(widget.time + " Feb"), ), SizedBox( width: 250, ), Text(widget.like.toString()), SizedBox( width: 5, ), GestureDetector( onTap: () async{ print("heyy"); check = !check; if(check==true){ await fire.collection("confession").get().then((QuerySnapshot querySnapshot) => { querySnapshot.docs .forEach((doc) { if(doc["content"]==widget.text){ print(doc.id); fire.collection("confession").doc(doc.id).update({ "likes":widget.like+1, }); } })});} else{ await fire.collection("confession").get().then((QuerySnapshot querySnapshot) => { querySnapshot.docs .forEach((doc) { if(doc["content"]==widget.text){ print(doc.id); fire.collection("confession").doc(doc.id).update({ "likes":widget.like-1, }); } })}); } setState(() {}); }, child: Hearticon( check: check, )) ], ) ], ), ), SizedBox( height: 16, ) ], ); } } class Cardsmall extends StatefulWidget { String target; String content; Cardsmall({String target, String content}) { this.target = target; this.content = content; } @override _CardsmallState createState() => _CardsmallState(); } class _CardsmallState extends State<Cardsmall> { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 0), child: Column( children: [ Container( height: 160, width: MediaQuery.of(context).size.width / 1.5, decoration: BoxDecoration( borderRadius: BorderRadius.circular(24), color: Colors.white.withOpacity(0.4), boxShadow: [ BoxShadow( color: Color.fromRGBO(242, 169, 184, 1), blurRadius: 12, offset: Offset(0, 12)) ]), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.fromLTRB(9, 15, 0, 0), child: Text( '@' + widget.target, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20), ), ), Padding( padding: const EdgeInsets.fromLTRB(15, 12, 12, 10), child: Container( height: 80, child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Text( widget.content, style: TextStyle(fontSize: 12), ))), ), ], ), ), ], ), ); } }
0
mirrored_repositories/Flutter-Chat-App
mirrored_repositories/Flutter-Chat-App/lib/main.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:firebase_database/ui/firebase_animated_list.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:image_picker/image_picker.dart'; import 'dart:math'; import 'dart:io'; final ThemeData kIOSTheme = new ThemeData( primarySwatch: Colors.orange, primaryColor: Colors.grey[100], primaryColorBrightness: Brightness.light, ); final ThemeData kDefaultTheme = new ThemeData( primarySwatch: Colors.deepPurple, accentColor: Colors.amberAccent[400], ); final googleSignIn = new GoogleSignIn(); final analytics = new FirebaseAnalytics(); final auth = FirebaseAuth.instance; final reference = FirebaseDatabase.instance.reference().child('messages'); const String _name = "Your Name"; void main() { runApp(new FriendlychatApp()); } Future<Null> _ensureLoggedIn() async { GoogleSignInAccount user = googleSignIn.currentUser; if (user == null) user = await googleSignIn.signInSilently(); if (user == null) { user = await googleSignIn.signIn(); analytics.logLogin(); } if (await auth.currentUser() == null) { GoogleSignInAuthentication credentials = await googleSignIn.currentUser.authentication; await auth.signInWithGoogle( idToken: credentials.idToken, accessToken: credentials.accessToken, ); } } class FriendlychatApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: "Friendlychat", theme: defaultTargetPlatform == TargetPlatform.iOS ? kIOSTheme : kDefaultTheme, home: new ChatScreen(), ); } } @override class ChatMessage extends StatelessWidget { ChatMessage({this.snapshot, this.animation}); final DataSnapshot snapshot; final Animation animation; Widget build(BuildContext context) { return new SizeTransition( sizeFactor: new CurvedAnimation( parent: animation, curve: Curves.easeOut), axisAlignment: 0.0, child: new Container( margin: const EdgeInsets.symmetric(vertical: 10.0), child: new Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Container( margin: const EdgeInsets.only(right: 16.0), child: new CircleAvatar(backgroundImage: new NetworkImage( snapshot.value['senderPhotoUrl'])), ), new Expanded( child: new Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Text( snapshot.value['senderName'], style: Theme .of(context) .textTheme .subhead), new Container( margin: const EdgeInsets.only(top: 5.0), child: snapshot.value['imageUrl'] != null ? //modified new Image.network( //new snapshot.value['imageUrl'], //new width: 250.0, //new ) : //new new Text(snapshot.value['text']), ), ], ), ), ], ), ), ); } } class ChatScreen extends StatefulWidget { @override State createState() => new ChatScreenState(); } class ChatScreenState extends State<ChatScreen> { final TextEditingController _textController = new TextEditingController(); bool _isComposing = false; @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("Friendlychat"), elevation: Theme .of(context) .platform == TargetPlatform.iOS ? 0.0 : 4.0, ), body: new Column(children: <Widget>[ new Flexible( child: new FirebaseAnimatedList( query: reference, sort: (a, b) => b.key.compareTo(a.key), padding: new EdgeInsets.all(8.0), reverse: true, itemBuilder: (_, DataSnapshot snapshot, Animation<double> animation, int index) { return new ChatMessage( snapshot: snapshot, animation: animation ); }, // itemBuilder: (_, DataSnapshot snapshot, Animation<double> animation) { // return new ChatMessage( // snapshot: snapshot, // animation: animation // ); // }, ), ), new Divider(height: 1.0), new Container( decoration: new BoxDecoration(color: Theme .of(context) .cardColor), child: _buildTextComposer(), ), ])); } Widget _buildTextComposer() { return new IconTheme( data: new IconThemeData(color: Theme .of(context) .accentColor), child: new Container( margin: const EdgeInsets.symmetric(horizontal: 8.0), child: new Row(children: <Widget>[ new Container( //new margin: new EdgeInsets.symmetric(horizontal: 4.0), //new child: new IconButton( //new icon: new Icon(Icons.photo_camera), //new onPressed: () async { await _ensureLoggedIn(); // new File imageFile = await ImagePicker.pickImage( source: ImageSource.camera); int random = new Random().nextInt(100000); //new StorageReference ref = //new FirebaseStorage.instance.ref().child( "image_$random.jpg"); //new StorageUploadTask uploadTask = ref.put(imageFile); //new Uri downloadUrl = (await uploadTask.future).downloadUrl; _sendMessage(imageUrl: downloadUrl.toString()); } ), //new ), new Flexible( child: new TextField( controller: _textController, onChanged: (String text) { setState(() { _isComposing = text.length > 0; }); }, onSubmitted: _handleSubmitted, decoration: new InputDecoration.collapsed(hintText: "Send a message"), ), ), new Container( margin: new EdgeInsets.symmetric(horizontal: 4.0), child: Theme .of(context) .platform == TargetPlatform.iOS ? new CupertinoButton( child: new Text("Send"), onPressed: _isComposing ? () => _handleSubmitted(_textController.text) : null, ) : new IconButton( icon: new Icon(Icons.send), onPressed: _isComposing ? () => _handleSubmitted(_textController.text) : null, )), ]), decoration: Theme .of(context) .platform == TargetPlatform.iOS ? new BoxDecoration( border: new Border(top: new BorderSide(color: Colors.grey[200]))) : null), ); } Future<Null> _handleSubmitted(String text) async { _textController.clear(); setState(() { _isComposing = false; }); await _ensureLoggedIn(); _sendMessage(text: text); } void _sendMessage({ String text, String imageUrl }) { reference.push().set({ 'text': text, 'imageUrl': imageUrl, 'senderName': googleSignIn.currentUser.displayName, 'senderPhotoUrl': googleSignIn.currentUser.photoUrl, }); analytics.logEvent(name: 'send_message'); } }
0
mirrored_repositories/Flutter-Chat-App
mirrored_repositories/Flutter-Chat-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:temp_flutter_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(new FriendlychatApp()); // 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/Image-View-3D-Flutter
mirrored_repositories/Image-View-3D-Flutter/lib/main.dart
import 'package:flutter/material.dart'; import 'package:image_view_3d/screen/cardekho.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: "Pinged", debugShowCheckedModeBanner: false, home: DemoPage(), ); } }
0
mirrored_repositories/Image-View-3D-Flutter/lib
mirrored_repositories/Image-View-3D-Flutter/lib/screen/cardekho.dart
import 'package:imageview360/imageview360.dart'; import 'package:flutter/material.dart'; class DemoPage extends StatefulWidget { DemoPage({Key key, this.title}) : super(key: key); final String title; @override _DemoPageState createState() => _DemoPageState(); } class _DemoPageState extends State<DemoPage> { List<AssetImage> imageList = List<AssetImage>(); bool autoRotate = true; int rotationCount = 2; int swipeSensitivity = 2; bool allowSwipeToRotate = true; RotationDirection rotationDirection = RotationDirection.anticlockwise; Duration frameChangeDuration = Duration(milliseconds: 50); bool imagePrecached = false; @override void initState() { //* To load images from assets after first frame build up. WidgetsBinding.instance .addPostFrameCallback((_) => updateImageList(context)); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( bottomNavigationBar: BottomAppBar( color: Color(0xffFC704A), child: Container( height: 60, child: Center( child: Text( "Book Now", style: TextStyle( fontSize: 26, color: Colors.white, fontWeight: FontWeight.w600, ), ), )), elevation: 5, ), backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, title: Text( "", style: TextStyle(color: Colors.black), ), centerTitle: true, ), body: Stack( // alignment: Alignment.center, children: <Widget>[ (imagePrecached == true) ? ImageView360( key: UniqueKey(), imageList: imageList, autoRotate: false, rotationCount: 2, rotationDirection: RotationDirection.anticlockwise, frameChangeDuration: Duration(milliseconds: 170), swipeSensitivity: swipeSensitivity, allowSwipeToRotate: allowSwipeToRotate, ) : Text("Pre-Caching images..."), Container( margin: EdgeInsets.only(left: 20, top: 10), child: Text( "Ford Mustang", style: TextStyle( fontSize: 26, fontWeight: FontWeight.w800, letterSpacing: 1.5), ), ), Container( height: 250, margin: EdgeInsets.only(top: 300), child: ListView.builder( itemCount: 7, scrollDirection: Axis.horizontal, itemBuilder: (context, index) { return Container( decoration: BoxDecoration( color: Color(0xffFC704A), borderRadius: BorderRadius.circular(20)), margin: EdgeInsets.all(20), //height: 50, width: 150, child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ index == 0 ? Icon( Icons.av_timer, size: 60, color: Colors.grey[300], ) : Icon( Icons.camera, size: 60, color: Colors.grey[300], ), index == 0 ? Text( "410 KM/h", style: TextStyle( fontSize: 18, fontWeight: FontWeight.w800, letterSpacing: 1.5, color: Colors.grey[300]), ) : Text( "13.6L", style: TextStyle( fontSize: 18, fontWeight: FontWeight.w800, letterSpacing: 1.5, color: Colors.grey[300]), ) ], )); }, ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( margin: EdgeInsets.only(left: 20, top: 580), child: Text( "₹5000", style: TextStyle( fontSize: 26, fontWeight: FontWeight.w800, letterSpacing: 1.5), ), ), ], ), ], ), ); } void updateImageList(BuildContext context) async { for (int i = 1; i <= 36; i++) { imageList.add(AssetImage('lib/images/$i.jpg')); //* To precache images so that when required they are loaded faster. await precacheImage(AssetImage('lib/images/$i.jpg'), context); } setState(() { imagePrecached = true; }); } }
0
mirrored_repositories/Image-View-3D-Flutter
mirrored_repositories/Image-View-3D-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 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:image_view_3d/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_Trello
mirrored_repositories/Flutter_Trello/lib/main.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_trello/app/utils/todo.dart'; import 'app/pages/trello/trello_Screen.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override void initState() { super.initState(); deleteCompleteTask(); } void deleteCompleteTask() { Firestore.instance .collection(Todo().features["completed"]) .getDocuments() .then((QuerySnapshot snapshot) { snapshot.documents.forEach((DocumentSnapshot documentSnapshot) { Timestamp timestamp = documentSnapshot.data["date"]; String date = timestamp.toDate().year.toString() + timestamp.toDate().month.toString() + timestamp.toDate().day.toString(); if (date != "${DateTime.now().year}${DateTime.now().month}${DateTime.now().day}") { Firestore.instance .collection(Todo().features["completed"]) .document(documentSnapshot.documentID) .delete(); } }); }); } @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([ DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight, ]); return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: TrelloScreen(), ); } }
0
mirrored_repositories/Flutter_Trello/lib/app
mirrored_repositories/Flutter_Trello/lib/app/widgets/export_widgets.dart
export 'trelloScreen/tasksCard_widget.dart'; export 'trelloScreen/tasksForm_widget.dart';
0
mirrored_repositories/Flutter_Trello/lib/app/widgets
mirrored_repositories/Flutter_Trello/lib/app/widgets/trelloScreen/tasksForm_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter_trello/app/services/online_crud.dart'; import 'package:flutter_trello/app/utils/todo.dart'; import 'tasksCard_widget.dart'; Container buildContainer(Size size, String todoName) { return Container( alignment: Alignment.topCenter, width: size.width - 100, child: SingleChildScrollView( child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.only(topLeft: Radius.circular(5.0))), child: ListTile( title: TextField( textInputAction: TextInputAction.done, onChanged: (String value) { todoName = value; }, decoration: InputDecoration(hintText: "Add list", labelText: "List Name"), ), subtitle: MaterialButton( onPressed: () { if (todoName.isNotEmpty) { // * creating new task Services(collectionName: Todo().features["todo"]) ..addRecord(docName: todoName); } }, child: Text("Add"), ), ), ), ), ); }
0
mirrored_repositories/Flutter_Trello/lib/app/widgets
mirrored_repositories/Flutter_Trello/lib/app/widgets/trelloScreen/tasksCard_widget.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter_trello/app/services/online_crud.dart'; import 'package:flutter_trello/app/utils/todo.dart'; Positioned cardBanner(Color firstColor, Color secondColor, [double width]) { return Positioned( top: 0.0, child: Column( children: [ Container( width: width ?? 300, height: 8, decoration: BoxDecoration( gradient: LinearGradient( begin: FractionalOffset.bottomLeft, end: FractionalOffset.topRight, colors: <Color>[firstColor, secondColor], ), color: Colors.green, borderRadius: BorderRadius.only( topLeft: Radius.circular(5.0), ), ), ), ], ), ); } Container buildCardTitle(String title, List<DocumentSnapshot> list) { return Container( width: 300, padding: EdgeInsets.only(top: 15, bottom: 5, left: 10), child: Row( children: [ Text( title, style: TextStyle( color: Colors.blueGrey.shade700, fontWeight: FontWeight.bold, fontSize: 16), ), Container( padding: EdgeInsets.all(4), decoration: BoxDecoration( border: Border.all(color: Colors.grey)), child: Text(list.length.toString(), style: TextStyle(color: Colors.grey.shade600)), ), ], ), ); } Card taskCard(int index, List<DocumentSnapshot> list) { return Card( child: Padding( padding: const EdgeInsets.all(8.0), child: Text(list[index].data["task"]), ), ); } Card doneTaskCard(int index, List<DocumentSnapshot> list) { return Card( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: const EdgeInsets.only(left: 8.0), child: Text(list[index].data["task"]), ), PopupMenuButton<String>( onSelected: (String value) { // * shifting to different collection Services(collectionName: value) ..addRecord(docName: list[index].data["task"]); // * delete from done collection Services(collectionName: Todo().features["completed"]) ..deleteRecord(docName: list[index].data["task"]); }, itemBuilder: (BuildContext context) { return <PopupMenuEntry<String>>[ PopupMenuItem( value: Todo().features["todo"], child: Text("Todo"), ), PopupMenuItem( value: Todo().features["inprocess"], child: Text("In Process"), ), ]; }, ), ], ), ); } Container doneTaskDragTraget(Size size) { return Container( width: size.width, height: 62, decoration: BoxDecoration(color: Colors.blueGrey.shade100), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( children: [ Text("Swipe"), Icon(Icons.keyboard_arrow_right, color: Colors.blueGrey), ], ), Text( "Add Todo", style: TextStyle(color: Colors.blueGrey), ), ], ), ), Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.delete, color: Colors.blueGrey), Text( "Drag list here", style: TextStyle(color: Colors.blueGrey), ), ], ), ), Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( children: [ Icon(Icons.arrow_left, color: Colors.blueGrey), Text("Swipe"), ], ), Text( "Done List", style: TextStyle(color: Colors.blueGrey), ), ], ), ), ], ), ); }
0
mirrored_repositories/Flutter_Trello/lib/app/pages
mirrored_repositories/Flutter_Trello/lib/app/pages/try/ref.dart
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { PageController pageController; List<Container> pages = [ Container( margin: EdgeInsets.symmetric( horizontal: 10.0, ), color: Colors.redAccent), Container( margin: EdgeInsets.symmetric( horizontal: 10.0, ), color: Colors.purpleAccent), Container( margin: EdgeInsets.symmetric( horizontal: 10.0, ), color: Colors.greenAccent) ]; @override void initState() { super.initState(); pageController = PageController( initialPage: 1, viewportFraction: 0.8, ); } @override Widget build(BuildContext context) { return Scaffold( body: Container( margin: EdgeInsets.symmetric( vertical: 50.0, ), child: PageView.builder( controller: pageController, itemCount: pages.length, itemBuilder: (BuildContext context, int index){ return pages[index]; }, ), ), ); } }
0
mirrored_repositories/Flutter_Trello/lib/app/pages
mirrored_repositories/Flutter_Trello/lib/app/pages/try/reOrderList.dart
import 'package:flutter/material.dart'; class ReOrderList extends StatefulWidget { @override _ReOrderListState createState() => _ReOrderListState(); } class _ReOrderListState extends State<ReOrderList> { GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>(); List<String> orderCharacter = [ 'akon', 'bkon', 'ckon', 'dkon', 'ekon', 'fkon', ]; int insetIndex = 0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Re-Order List"), ), body: AnimatedList( key: _listKey, initialItemCount: orderCharacter.length, itemBuilder: (BuildContext context, int index, Animation<double> animation) { return SizeTransition( sizeFactor: animation, child: Card( child: Text("item ${orderCharacter[index]}"), ), ); }, ), floatingActionButton: FloatingActionButton( onPressed: () { setState(() { insetIndex = orderCharacter.length ; orderCharacter.insert(insetIndex, "sangam"); _listKey.currentState.insertItem(insetIndex); }); }, child: Icon(Icons.add), ), ); } } // return Scaffold( // appBar: AppBar( // title: Text("Re-Order List"), // ), // body: ReorderableListView( // children: List.generate( // orderCharacter.length, // (index) => Container( // key: Key(index.toString()), // width: MediaQuery.of(context).size.width, // child: Card( // child: Text(orderCharacter[index]), // ), // ), // ), // onReorder: (int oldOrder, int newOrder) { // print('Old order: $oldOrder'); // print('New order: $newOrder'); // if(newOrder > oldOrder){ // newOrder -= 1; // } // setState(() { // final String item = orderCharacter.removeAt(oldOrder); // print(item); // orderCharacter.insert(newOrder, item); // }); // }, // ), // floatingActionButton: FloatingActionButton(onPressed: (){ // setState(() { // orderCharacter.insert(1, "sangam"); // }); // }, child: Icon(Icons.add),), // );
0
mirrored_repositories/Flutter_Trello/lib/app/pages
mirrored_repositories/Flutter_Trello/lib/app/pages/trello/trello_Screen.dart
import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter_trello/app/services/online_crud.dart'; import 'package:flutter_trello/app/utils/todo.dart'; // * exporting widgets import '../../widgets/export_widgets.dart'; class TrelloScreen extends StatefulWidget { @override _TrelloScreenState createState() => _TrelloScreenState(); } class _TrelloScreenState extends State<TrelloScreen> { Firestore firestore = Firestore(); PageController pageController; List<Container> todoList; List<DocumentSnapshot> thingsTodoList; List<DocumentSnapshot> doingList; List<DocumentSnapshot> doneList; String collectionName; String todoName; Timestamp timeDate; @override void initState() { super.initState(); fetchThingsToDo(); fetchDoing(); fetchDone(); } fetchDone() { doneList = []; Services(collectionName: Todo().features["completed"]) ..fetchCompletedTask("date").listen((QuerySnapshot snapshot) { print("CRUD tryL: ${snapshot.documents.length}"); setState(() { doneList.clear(); }); snapshot.documents.forEach( (DocumentSnapshot documentSnapshot) { // * ARRAY START setState(() { doneList.add(documentSnapshot); }); // * END }, ); if (snapshot.documents.length == 0) { setState(() { doneList.clear(); }); } }); } fetchDoing() { doingList = []; Services(collectionName: Todo().features["inprocess"]) ..fetchCompletedTask("date").listen((QuerySnapshot snapshot) { setState(() { doingList.clear(); }); snapshot.documents.forEach( (DocumentSnapshot documentSnapshot) { // * ARRAY START setState(() { doingList.add(documentSnapshot); }); // * END }, ); // ! if (snapshot.documents.length == 0) { setState(() { doingList.clear(); }); } }); } fetchThingsToDo() { thingsTodoList = []; Services(collectionName: Todo().features["todo"]) ..fetchCompletedTask("date").listen( (QuerySnapshot snapshot) { setState(() { thingsTodoList.clear(); }); snapshot.documents.forEach( (DocumentSnapshot documentSnapshot) { // * ARRAY START setState(() { thingsTodoList.add(documentSnapshot); }); // * END }, ); if (snapshot.documents.length == 0) { setState(() { thingsTodoList.clear(); }); } }, ); } @override Widget build(BuildContext context) { Size size = MediaQuery.of(context).size; return Scaffold( // * End Drawer 🙌 endDrawer: SafeArea( child: Center( child: _buildDone(), ), ), // * End Drawer 🙌 drawer: SafeArea( child: Center( child: buildContainer(size, todoName), ), ), body: SafeArea( child: SingleChildScrollView( physics: BouncingScrollPhysics(), scrollDirection: Axis.horizontal, child: Row( children: [ // * things to do 🧿 _buildThingTooDO(), _buildDoing(), // _buildDone(), ], ), ), ), //* DONE - target state bottomNavigationBar: buildDoneDragTarget(size, collectionName), ); } // * done state DragTarget<String> buildDoneDragTarget(Size size, String collectionName) { return DragTarget( onAccept: (String value) async { // * accepting in process task to done task if (collectionName == "doing") { // * setting up for shifting task to different collection await firestore .collection(collectionName) .document(value) .get() .then((document) { setState(() { timeDate = document.data["date"]; }); // * shifting task to different collection Services(collectionName: Todo().features["completed"]) ..shiftTasks(value: value, dateTime: timeDate); }); // * deleting task from previous collection Services(collectionName: collectionName) ..deleteRecord(docName: value); } // else{ // TODO vibrate when improcess list is dragged // // await HapticFeedback.vibrate(); // } }, builder: (BuildContext context, List<dynamic> acceptedData, List<dynamic> rejectedData) { return doneTaskDragTraget(size); }, ); } Container _buildDone() { return Container( alignment: Alignment.topCenter, width: 300, child: Card( child: Stack( children: [ SingleChildScrollView( child: Column( children: [ buildCardTitle("Done ", doneList), // * title list _buildDoneList(doneList), ], ), ), cardBanner(Colors.lightGreen, Colors.green), ], ), ), ); } Padding _buildDoneList(List<DocumentSnapshot> list) { return Padding( padding: const EdgeInsets.all(8.0), child: list.length > 0 ? ListView.builder( shrinkWrap: true, itemCount: list.length, physics: NeverScrollableScrollPhysics(), itemBuilder: (BuildContext context, int index) { // String data = doneList[index].data["task"]; return doneTaskCard(index, list); }, ) : Text("No Data"), ); } // * in process state Container _buildDoing() { return Container( alignment: Alignment.topCenter, width: 300, child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10), )), child: Stack( children: [ SingleChildScrollView( child: Column( children: [ buildCardTitle("In progress ", doingList), // * title list _buildDoingDragTraget() ], ), ), cardBanner(Colors.orangeAccent, Colors.orange), ], ), ), ); } DragTarget<String> _buildDoingDragTraget() { return DragTarget( onAccept: (String value) async { if (collectionName != Todo().features["inprocess"]) { print(value); await firestore .collection(collectionName) .document(value) .get() .then((document) { setState(() { timeDate = document.data["date"]; }); // * shifting task doing collection Services(collectionName: Todo().features["inprocess"]) ..shiftTasks(value: value, dateTime: timeDate); }); // * deleting task Services(collectionName: collectionName) ..deleteRecord(docName: value); } }, builder: (BuildContext context, List<dynamic> accecptedData, List<dynamic> rejectedData) { return inProcessList(doingList); }, ); } Padding inProcessList(List<DocumentSnapshot> doingList) { return Padding( padding: const EdgeInsets.all(8.0), child: doingList.length > 0 ? ListView.builder( shrinkWrap: true, itemCount: doingList.length, physics: BouncingScrollPhysics(), itemBuilder: (BuildContext context, int index) { String data = doingList[index].data["task"]; return _buildDoingDragable(data, index); }, ) : Container( decoration: BoxDecoration(border: Border.all(color: Colors.blueGrey)), padding: EdgeInsets.all(10), child: Text( "+ Drag List here", style: TextStyle(color: Colors.blueGrey), ), ), ); } Draggable<String> _buildDoingDragable(String data, int index) { return LongPressDraggable<String>( onDragStarted: () { print("doing"); setState(() { collectionName = Todo().features["inprocess"]; }); }, data: data, child: taskCard(index, doingList), feedback: Container( width: 300, padding: EdgeInsets.all(8), child: taskCard(index, doingList), ), childWhenDragging: Card( color: Colors.grey.shade100, child: Padding( padding: const EdgeInsets.all(8.0), child: Text(doingList[index].data["task"]), ), ), ); } // * things to do card START // * To-do state Container _buildThingTooDO() { return Container( alignment: Alignment.topCenter, width: 300, child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(10), )), child: Stack( children: [ SingleChildScrollView( child: Column( children: [ buildCardTitle("Todo ", thingsTodoList), // * title list _buildThingsTODODragTraget( collectionName, thingsTodoList, doingList), ], ), ), cardBanner(Colors.redAccent, Colors.red.shade700), ], ), ), ); } DragTarget<String> _buildThingsTODODragTraget(String collectionName, List<DocumentSnapshot> thingsTodoList, List<DocumentSnapshot> doingList) { return DragTarget( onAccept: (String value) async { if (collectionName != Todo().features["todo"]) { print(value); await firestore .collection(collectionName) .document(value) .get() .then((document) { setState(() { timeDate = document.data["date"]; }); // * shifting task thingstodo collection Services(collectionName: Todo().features["todo"]) ..shiftTasks(value: value, dateTime: timeDate); }); // * deleting task Services(collectionName: collectionName) ..deleteRecord(docName: value); } }, builder: (BuildContext context, List<dynamic> accecptedData, List<dynamic> rejectedData) { return thingstodoList(thingsTodoList, doingList); }, ); } Padding thingstodoList( List<DocumentSnapshot> thingsTodoList, List<DocumentSnapshot> doingList) { return Padding( padding: const EdgeInsets.all(8.0), child: thingsTodoList.length > 0 ? ListView.builder( shrinkWrap: true, itemCount: thingsTodoList.length, physics: BouncingScrollPhysics(), itemBuilder: (BuildContext context, int index) { String data = thingsTodoList[index].data["task"]; return _buildThingsTODODragable(data, index); }, ) : Container( decoration: BoxDecoration(border: Border.all(color: Colors.blueGrey)), padding: EdgeInsets.all(10), child: Text( doingList.length > 0 // * if in process list is empty 😍 ? "+ Drag List here" : "Empty Todo List", style: TextStyle(color: Colors.blueGrey), ), ), ); } Draggable<String> _buildThingsTODODragable(String data, int index) { return LongPressDraggable<String>( onDragStarted: () { setState(() { collectionName = Todo().features["todo"]; }); }, data: data, child: taskCard(index, thingsTodoList), feedback: Container( width: 300, padding: EdgeInsets.all(8), child: taskCard(index, thingsTodoList), ), childWhenDragging: Card( color: Colors.grey.shade100, child: Padding( padding: const EdgeInsets.all(8.0), child: Text(thingsTodoList[index].data["task"]), ), ), ); } // * things to do card END }
0
mirrored_repositories/Flutter_Trello/lib/app
mirrored_repositories/Flutter_Trello/lib/app/utils/todo.dart
import 'package:cloud_firestore/cloud_firestore.dart'; class Todo { Map<String, String> features = { "todo": "thingstodo", "inprocess": "doing", "completed": "done" }; Map<String, dynamic> shiftingData(String value, Timestamp dateTime) { return { "task": value, "date": dateTime, }; } Map<String, dynamic> addingData(String value) { return { "task": value, "date": DateTime.now() }; } }
0
mirrored_repositories/Flutter_Trello/lib/app
mirrored_repositories/Flutter_Trello/lib/app/services/online_crud.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import '../utils/todo.dart'; class Services { Todo todo = Todo(); String collectionName; CollectionReference collectionReference; Services({this.collectionName}) { collectionReference = Firestore.instance.collection(collectionName); } // * adding new task with new dateTime Future<void> addRecord({String docName}) async { return await collectionReference .document(docName) .setData(todo.addingData(docName)); } //* adding previous task && previous dateTime Future<void> shiftTasks({String value, Timestamp dateTime}) { return collectionReference .document(value) .setData(todo.shiftingData(value, dateTime)); } // * read Future<DocumentSnapshot> fetchSingleDoc({String docsName}) async { return await collectionReference.document(docsName).get(); } // * deleting task Future<void> deleteRecord({String docName}) async { return await collectionReference.document(docName).delete(); } // * fetch completed task [Done] order by date😍 Stream<QuerySnapshot> fetchCompletedTask([String orderBy = "date"]) { return collectionReference.orderBy(orderBy).snapshots(); } }
0
mirrored_repositories/last_song
mirrored_repositories/last_song/lib/helpers.dart
import 'dart:async'; import 'package:flutter/foundation.dart'; import 'nova.dart'; import 'somafm.dart'; import 'bbcradio.dart'; class ChannelManager extends ChangeNotifier { final List<Channel> channels = []; int _currentChannel = -1; late Timer? _timer; bool isFetchingCurrentTrack = false; Channel get currentChannel { if (_currentChannel != -1) { return channels[_currentChannel]; } else { return Channel(); } } void changeChannel(Channel channel) { _currentChannel = channels.indexOf(channel); notifyListeners(); } void addChannel(Channel channel) { channels.add(channel); if (channels.length == 1) { _currentChannel = 0; } } Future<void> initialize() async { for (var s in Nova.subchannels) { addChannel(Nova(s['code'], s['name'], s['image'], s['id'])); } final subchannels = await SomaFm.loadSubChannels(); for (var s in subchannels) { addChannel(SomaFm(s['id'], s['title'], s['image'], s['xlimage'], s['description'], s['dj'])); } for (var s in BBCRadio.subchannels) { addChannel(BBCRadio(s['code'], s['name'])); } } Future<int> fetchCurrentTrack( {bool cancel = false, bool manual = false}) async { //debugPrint( // '${DateTime.now().toIso8601String().substring(11, 19)}: in fetchCurrentTrack(cancel: $cancel, manual: $manual)'); if (cancel) { // reschedule a new timer if requested and cancel the previous one if (_timer != null) { _timer?.cancel(); launchTimer(); } } isFetchingCurrentTrack = true; notifyListeners(); int ret = await currentChannel.fetchCurrentTrack(manual); isFetchingCurrentTrack = false; notifyListeners(); return ret; } void launchTimer() { // schedule a check of current track for an update, every 30s _timer = Timer.periodic( const Duration(seconds: 30), (timer) => fetchCurrentTrack()); } } class SubChannel { late String codename; late String title; late String imageUrl; late String bigImageUrl; late String id; SubChannel( {this.codename = 'subchannel', this.title = 'Subchannel', this.imageUrl = '', this.bigImageUrl = '', this.id = '-1'}); @override String toString() { return 'Subchannel(code: $codename, title: $title, imageUrl: $imageUrl, bigImageUrl: $bigImageUrl, id: $id)'; } } class Show { late String author; late String name; late String description; late String airingTime; late String imageUrl; DateTime? start; DateTime? end; Show( {this.author = 'Author', this.name = 'Show', this.description = '', this.airingTime = '00:00 - 00:00', this.imageUrl = ''}); @override String toString() { return 'Show(author: $author, name: $name, description: $description, airingTime: $airingTime, imageUrl: $imageUrl)'; } } class Channel extends ChangeNotifier { late String radio; late Show show; late SubChannel subchannel; late Track currentTrack; bool isFavorite = false; List<Track> recentTracks = <Track>[]; Channel({ this.radio = 'Radio', //this.isFavorite = false, }) { currentTrack = Track(); show = Show(); subchannel = SubChannel(); } Future<int> fetchCurrentTrack([bool manual = false]) async { return 0; } Future<List<Track>> getRecentTracks() async { return <Track>[]; } } class Track { int id; String artist; String title; String album; String imageUrl; String duration; String diffusionDate; Track({ this.id = -1, this.artist = 'Artist', this.title = 'Title', this.album = 'Album', this.imageUrl = '', this.duration = '00:00', this.diffusionDate = "2000-01-01T00:00:00", }); @override String toString() { return 'Track(diffusionDate:$diffusionDate, artist:$artist, title:$title, album:$album)'; } void updateFrom(Track track) { id = track.id; artist = track.artist; title = track.title; album = track.album; imageUrl = track.imageUrl; duration = track.duration; diffusionDate = track.diffusionDate; } } class AppConfig { static const String name = 'Last Song'; static const String version = '0.0.2'; static const String url = 'https://github.com/solsticedhiver/last_song'; static String userAgent = '${name.replaceAll(' ', '')}/$version +$url'; static const String defaultImage = 'assets/img/black-record-vinyl-640x640.png'; static const double bottomSheetSizeLargeScreen = 75; static const double bottomSheetSizeSmallScreen = 55; }
0
mirrored_repositories/last_song
mirrored_repositories/last_song/lib/current_track.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'helpers.dart'; import 'myextensions.dart'; class CurrentTrackWidget extends StatelessWidget { final BoxConstraints constraints; const CurrentTrackWidget({super.key, required this.constraints}); @override Widget build(BuildContext context) { double bSS; if (constraints.maxHeight > 700) { bSS = AppConfig.bottomSheetSizeLargeScreen; } else { bSS = AppConfig.bottomSheetSizeSmallScreen; } Widget ctw; if (constraints.maxWidth > 1000) { ctw = CurrentTrackWidgetLargeScreen( bottomSheetSize: bSS, constraints: constraints); } else { ctw = CurrentTrackWidgetSmallScreen(bottomSheetSize: bSS); } return Consumer<ChannelManager>(builder: (context, cm, child) { return Stack( fit: StackFit.expand, children: [ ctw, Visibility( visible: cm.isFetchingCurrentTrack, child: const Positioned( top: 0, left: 0, right: 0, child: LinearProgressIndicator( // deepOrange is not seen beside the appBar of the same color color: Colors.black87, backgroundColor: Colors.white, minHeight: 2, value: null, ), )), ], ); }); } } class CurrentTrackWidgetSmallScreen extends StatelessWidget { final double bottomSheetSize; const CurrentTrackWidgetSmallScreen( {super.key, required this.bottomSheetSize}); @override Widget build(BuildContext context) { //debugPrint('in CurrentTrackWidgetSmallScreen.build()'); double imgSize = 400; if (MediaQuery.of(context).size.width < 420) { imgSize = MediaQuery.of(context).size.width - 20; } return Container( padding: EdgeInsets.only( bottom: bottomSheetSize, left: 10, right: 10, top: 10), child: Column( mainAxisSize: MainAxisSize.min, textDirection: TextDirection.ltr, children: <Widget>[ CurrentTrackImage(imgSize: imgSize), Flexible( flex: 2, //fit: FlexFit.tight, child: Container( padding: const EdgeInsets.only( top: 10, bottom: 5, right: 10, left: 10), child: const CurrentTrackText(isSmallScreen: true), ), ), ], ), ); } } class CurrentTrackWidgetLargeScreen extends StatelessWidget { final double bottomSheetSize; final BoxConstraints constraints; const CurrentTrackWidgetLargeScreen( {super.key, required this.bottomSheetSize, required this.constraints}); @override Widget build(BuildContext context) { double imgSize = 400; double gap = 30; double left = 30; // on very large screen if (constraints.maxHeight > 900 && constraints.maxWidth > 1500) { // increase image size imgSize = 700; gap = 45; left = 45; } return Container( padding: EdgeInsets.only( top: 10, bottom: bottomSheetSize, left: left, right: 20), child: Row( //mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ CurrentTrackImage(imgSize: imgSize), SizedBox(width: gap), const Flexible( flex: 0, child: CurrentTrackText(), ), ], ), ); } } class CurrentTrackImage extends StatefulWidget { final double imgSize; const CurrentTrackImage({super.key, required this.imgSize}); @override State<CurrentTrackImage> createState() => _CurrentTrackImageState(); } class _CurrentTrackImageState extends State<CurrentTrackImage> { bool isButtonVisible = true; bool isFoundImageVisible = true; String imageUrl = ''; @override void initState() { isButtonVisible = true; isFoundImageVisible = true; super.initState(); } @override Widget build(BuildContext context) { //debugPrint('in _CurrentWidgetImageState.build()'); Widget image; Widget defaultImage = Image.asset( AppConfig.defaultImage, height: widget.imgSize, width: widget.imgSize, fit: BoxFit.fill, ); return Consumer<ChannelManager>(builder: (context, cm, child) { String newImageUrl = cm.currentChannel.currentTrack.imageUrl; if (newImageUrl != imageUrl) { //setState! isFoundImageVisible = true; } imageUrl = newImageUrl; if (imageUrl.isNotEmpty) { image = CachedNetworkImage( imageUrl: imageUrl, httpHeaders: { 'User-Agent': AppConfig.userAgent, }, errorWidget: (context, url, error) => SizedBox( height: widget.imgSize, width: widget.imgSize, ), height: widget.imgSize, width: widget.imgSize, fit: BoxFit.fill, ); } else { image = SizedBox( width: widget.imgSize, height: widget.imgSize, ); } return Stack( alignment: Alignment.bottomRight, children: [ defaultImage, Visibility(visible: isFoundImageVisible, child: image), Visibility( visible: imageUrl.isNotEmpty, child: Container( decoration: const BoxDecoration( shape: BoxShape.circle, color: Colors.deepOrange, ), child: IconButton( color: Colors.white70, icon: isFoundImageVisible ? const Icon(Icons.hide_image) : const Icon(Icons.image), onPressed: () { setState( () { isFoundImageVisible = !isFoundImageVisible; }, ); }, ))) ], ); }); } } class CurrentTrackText extends StatelessWidget { final bool isSmallScreen; const CurrentTrackText({super.key, this.isSmallScreen = false}); @override Widget build(BuildContext context) { return Consumer<ChannelManager>(builder: (context, cm, child) { String dd = cm.currentChannel.currentTrack.diffusionDate .split('T')[1] .substring(0, 8); String artist; artist = cm.currentChannel.currentTrack.artist .split('/') .map((e) => e.toTitleCase()) .join(' /\n'); return Column( mainAxisAlignment: isSmallScreen ? MainAxisAlignment.start : MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ RichText( text: TextSpan( text: dd.substring(0, 5), style: TextStyle( fontSize: isSmallScreen ? 25 : 40, fontWeight: isSmallScreen ? FontWeight.bold : FontWeight.normal, color: Theme.of(context).primaryColor), children: <TextSpan>[ TextSpan( text: dd.substring(5, 8), style: const TextStyle( fontSize: 20, fontWeight: FontWeight.normal)) ]), ), Flexible( child: Text(artist, overflow: TextOverflow.clip, softWrap: true, style: TextStyle( fontSize: isSmallScreen ? 30 : 55, fontWeight: FontWeight.bold))), Text(cm.currentChannel.currentTrack.title.toTitleCase(), overflow: TextOverflow.clip, softWrap: true, style: TextStyle( fontSize: isSmallScreen ? 20 : 35, fontWeight: FontWeight.normal)), (cm.currentChannel.currentTrack.album.isNotEmpty && cm.currentChannel.currentTrack.album != 'Album') ? Text(cm.currentChannel.currentTrack.album, overflow: TextOverflow.clip, softWrap: true, style: TextStyle( fontSize: isSmallScreen ? 20 : 35, fontWeight: FontWeight.normal, fontStyle: FontStyle.italic)) : const SizedBox( height: 0, width: 0, ), Text( '${cm.currentChannel.currentTrack.duration.replaceFirst(RegExp(r'^0'), '').replaceFirst(':', 'min ')}s', style: TextStyle( fontSize: isSmallScreen ? 15 : 20, color: Theme.of(context).primaryColor)), ]); }); } }
0
mirrored_repositories/last_song
mirrored_repositories/last_song/lib/lastsong.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'helpers.dart'; import 'myextensions.dart'; class LastSongListRoute extends StatelessWidget { const LastSongListRoute({super.key}); @override Widget build(BuildContext context) { return Consumer<ChannelManager>( builder: (context, cm, child) { final recentTracks = cm.currentChannel.recentTracks; return Scaffold( appBar: AppBar( backgroundColor: Colors.deepOrange, foregroundColor: Colors.white, title: const Text('Recently played songs'), ), body: Container( alignment: recentTracks.isNotEmpty ? Alignment.topCenter : Alignment.center, child: recentTracks.isNotEmpty //? _buildListItemSong(recentTracks) ? SingleChildScrollView( child: DataTableSong( tracks: recentTracks, channel: cm.currentChannel)) : const Text('Nothing to show here'), ), ); }, ); } } class DataTableSong extends StatelessWidget { final List<Track> tracks; final Channel channel; const DataTableSong({super.key, required this.tracks, required this.channel}); @override Widget build(BuildContext context) { return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { bool isSmallScreen; if (constraints.maxWidth > 1000) { isSmallScreen = false; } else { isSmallScreen = true; } final int empties = tracks.where((e) => e.album == 'Album').length; // remove last column (Album) if none is defined if (empties == tracks.length) { isSmallScreen = true; } List<DataColumn> columns = <DataColumn>[ DataColumn( label: Expanded( child: Text( 'Time', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20, color: Theme.of(context).primaryColor), ), ), ), const DataColumn( label: Expanded( child: Text( 'Artist', style: TextStyle( fontStyle: FontStyle.normal, fontWeight: FontWeight.bold, fontSize: 20), ), ), ), const DataColumn( label: Expanded( child: Text( 'Title', style: TextStyle( fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: 20), ), ), ), ]; if (!isSmallScreen) { columns.add( const DataColumn( label: Expanded( child: Text( 'Album', style: TextStyle( fontStyle: FontStyle.italic, fontWeight: FontWeight.normal, fontSize: 20), ), ), ), ); } final rows = <DataRow>[]; for (var track in tracks) { String dd = track.diffusionDate.split('T')[1].substring(0, 8); List<DataCell> cells = [ DataCell(Text(dd, style: TextStyle( fontWeight: FontWeight.bold, color: Theme.of(context).primaryColor))), DataCell(Text(track.artist.toTitleCase(), style: const TextStyle(fontWeight: FontWeight.bold))), DataCell(Text(track.title.toTitleCase())), ]; // add album only is screen is large enough if (!isSmallScreen) { cells.add(DataCell(Text(track.album != 'Album' ? track.album : '---', style: const TextStyle(fontStyle: FontStyle.italic)))); } rows.add(DataRow(cells: cells)); } return Column( children: [ Center( child: Container( padding: const EdgeInsets.all(15), child: Text('${channel.radio} / ${channel.show.name}', style: const TextStyle( fontWeight: FontWeight.bold, fontSize: 20)))), DataTable( headingRowColor: MaterialStateProperty.resolveWith<Color?>( (Set<MaterialState> states) { return Theme.of(context).secondaryHeaderColor; }), columns: columns, rows: rows), ], ); }); } }
0
mirrored_repositories/last_song
mirrored_repositories/last_song/lib/mydrawer.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'favorites.dart'; import 'helpers.dart'; class MyDrawer extends StatelessWidget { final Widget child; const MyDrawer({super.key, required this.child}); @override Drawer build(BuildContext context) { return Drawer( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ DrawerHeader( decoration: BoxDecoration(color: Theme.of(context).primaryColor), child: Column( children: [ Image.asset( 'assets/img/black-record-vinyl-excl-point-64x64.png', height: 64, width: 64, ), const SizedBox( width: 15, height: 15, ), const Text('${AppConfig.name} ${AppConfig.version}', style: TextStyle(color: Colors.white, fontSize: 25)), ], ), ), const ListTile( title: Text('Radio channels', style: TextStyle(fontStyle: FontStyle.italic))), Expanded( flex: 1, child: child, ), ], ), ); } } class MyRadioExpansionPanelList extends StatefulWidget { const MyRadioExpansionPanelList({ super.key, required this.children, }); final List<List<Widget>> children; @override State<MyRadioExpansionPanelList> createState() => _MyRadioExpansionPanelListState(); } class _MyRadioExpansionPanelListState extends State<MyRadioExpansionPanelList> { final List<bool> _drawerExpansionPanelListState = <bool>[]; @override Widget build(BuildContext context) { List<ExpansionPanel> children = []; int pos = 0; for (var subList in widget.children) { final listView = ListView.builder( shrinkWrap: true, physics: const ClampingScrollPhysics(), itemCount: _drawerExpansionPanelListState[pos] ? subList.length : 0, prototypeItem: subList.first, itemBuilder: (context, index) { return subList[index]; }, ); children.add(ExpansionPanel( headerBuilder: (context, isExpanded) { return ListTile( title: Text( (subList[0] as MyRadioExpansionPanelListTile).channel.radio)); }, body: listView, isExpanded: _drawerExpansionPanelListState[widget.children.indexOf(subList)], )); pos++; } // for return SingleChildScrollView( child: ExpansionPanelList( expansionCallback: (panelIndex, isExpanded) { setState(() { _drawerExpansionPanelListState[panelIndex] = isExpanded; }); }, children: children, )); } @override void initState() { super.initState(); _drawerExpansionPanelListState .addAll(List<bool>.generate(widget.children.length, (index) => false)); } } class MyRadioExpansionPanelListTile extends StatefulWidget { const MyRadioExpansionPanelListTile({super.key, required this.channel}); final Channel channel; @override State<MyRadioExpansionPanelListTile> createState() => _MyRadioExpansionPanelListTileState(); } class _MyRadioExpansionPanelListTileState extends State<MyRadioExpansionPanelListTile> { late bool isFavorite; @override Widget build(BuildContext context) { return ListTile( key: ObjectKey(widget.channel), title: Text(widget.channel.subchannel.title), subtitle: Text(widget.channel.radio), leading: SizedBox( width: 48, height: 48, child: widget.channel.subchannel.imageUrl.startsWith('assets') // use 64x64px for memache image because the image is used in bottomsheet too ? Image.asset( widget.channel.subchannel.imageUrl, cacheHeight: 64, cacheWidth: 64, ) : CachedNetworkImage( imageUrl: widget.channel.subchannel.imageUrl, httpHeaders: { 'User-Agent': AppConfig.userAgent, }, errorWidget: (context, url, error) => const SizedBox(height: 64, width: 64), memCacheHeight: 64, memCacheWidth: 64, )), trailing: IconButton( icon: Icon(Icons.favorite, color: isFavorite ? Colors.red : ListTileTheme.of(context).iconColor), onPressed: () { Favorites favorites = Provider.of<Favorites>(context, listen: false); setState(() { isFavorite = !isFavorite; }); if (isFavorite) { favorites.add(widget.channel); } else { favorites.remove(widget.channel); } favorites.saveFavorites(); }, ), onTap: () { final cm = Provider.of<ChannelManager>(context, listen: false); cm.changeChannel(widget.channel); cm.fetchCurrentTrack(cancel: true); Navigator.pop(context); }, ); } @override void initState() { super.initState(); isFavorite = widget.channel.isFavorite; } }
0
mirrored_repositories/last_song
mirrored_repositories/last_song/lib/myextensions.dart
extension ChangeCaseString on String { // https://gist.github.com/filiph/d4e0c0a9efb0f869f984317372f5bee8?permalink_comment_id=3486118#gistcomment-3486118 String toTitleCase() { final stringBuffer = StringBuffer(); var capitalizeNext = true; for (final letter in toLowerCase().codeUnits) { // UTF-16: A-Z => 65-90, a-z => 97-122. if (capitalizeNext && letter >= 97 && letter <= 122) { stringBuffer.writeCharCode(letter - 32); capitalizeNext = false; } else { // UTF-16: 32 == space, 46 == period if (letter == 32 || letter == 46) capitalizeNext = true; stringBuffer.writeCharCode(letter); } } return stringBuffer.toString(); } }
0
mirrored_repositories/last_song
mirrored_repositories/last_song/lib/bandcamp.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:html/parser.dart' as parser; import 'helpers.dart'; class ResponseBandcamp { String imageUrl = ''; String duration = ''; ResponseBandcamp(this.imageUrl, this.duration); } Future<ResponseBandcamp> searchBandcamp(String s, String type) async { assert(type == 'a' || type == 't' || type == 'b'); // a = album, t = track, b = band String imageUrl = ''; String duration = ''; final rawData = json.encode({ 'search_text': s, 'search_filter': type, 'full_page': false, 'fan_id': null }); final headers = { 'x-requested-with': 'XMLHttpRequest', 'accept': 'application/json', 'content-type': 'application/json; charset=UTF-8', 'user-agent': AppConfig.userAgent, }; // the official API is not free, so using the result of elastic search Uri uri = Uri.parse( 'https://bandcamp.com/api/bcsearch_public_api/1/autocomplete_elastic'); final http.Response resp; try { resp = await http .post(uri, body: rawData, headers: headers) .timeout(const Duration(seconds: 15)); } catch (e) { debugPrint('debug: bandcamp search = $e'); return ResponseBandcamp(imageUrl, duration); } if (resp.statusCode == 200) { Map<String, dynamic> reply = jsonDecode(resp.body); final results = reply['auto']['results']; for (var res in results) { if (res['type'] == type) { // reconstruct image url because res['img'] is a 404 imageUrl = 'https://f4.bcbits.com/img/a${res["art_id"]}_13.jpg'; // 13 => 400p, 16 => 700p if (type == 't') { duration = await lookForTrackDuration(res['item_url_path']); } break; } } } else { debugPrint('debug: bandcamp search = ${resp.statusCode}'); return ResponseBandcamp(imageUrl, duration); } if (imageUrl != '') { debugPrint('debug: found on bandcamp $imageUrl'); } return ResponseBandcamp(imageUrl, duration); } Future<String> lookForTrackDuration(String url) async { String duration = ''; final http.Response resp; try { resp = await http.get(Uri.parse(url), headers: { 'User-Agent': AppConfig.userAgent, }).timeout(const Duration(seconds: 15)); } catch (e) { debugPrint('debug: bandcamp duration look up = $e'); return duration; } if (resp.statusCode != 200) { return duration; } final document = parser.parse(resp.body); final script = document.querySelector('script[type="application/ld+json"]'); if (script != null) { final jd = json.decode(script.text)['duration']; // coded like P00H10M11S for 10:11 if (jd != null) { duration = '${jd.substring(4, 6)}:${jd.substring(7, 9)}'; } } return duration; }
0
mirrored_repositories/last_song
mirrored_repositories/last_song/lib/discogs.dart
import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:http/http.dart' as http; import 'helpers.dart'; const String discogsKey = 'GRcTnfYcKdIFUeOEtUtA'; const String discogsSecret = 'dtmKATJxslqZHzKHFmRhJUDFLXNVBGlb'; class ResponseDiscogs { String imageUrl; String duration; ResponseDiscogs(this.imageUrl, this.duration); } Future<ResponseDiscogs> searchDiscogs(Map<String, String> search) async { String imageUrl = ''; String duration = ''; String queryString = Uri( queryParameters: search.map((key, value) => MapEntry(key, value.toString()))).query; /* # Pagination - per_page number - page number # Search parameters - query string (optional) Example: nirvana Your search query - type string (optional) Example: release String. One of release, master, artist, label - title string (optional) Example: nirvana - nevermind Search by combined “Artist Name - Release Title” title field. - release_title string (optional) Example: nevermind Search release titles. - credit string (optional) Example: kurt Search release credits. - artist string (optional) Example: nirvana Search artist names. - anv string (optional) Example: nirvana Search artist ANV. - label string (optional) Example: dgc Search label names. - genre string (optional) Example: rock Search genres. - style string (optional) Example: grunge Search styles. - country string (optional) Example: canada Search release country. - year string (optional) Example: 1991 Search release year. - format string (optional) Example: album Search formats. - catno string (optional) Example: DGCD-24425 Search catalog number. - barcode string (optional) Example: 7 2064-24425-2 4 Search barcodes. - track string (optional) Example: smells like teen spirit Search track titles. - submitter string (optional) Example: milKt Search submitter username. - contributor string (optional) Example: jerome99 Search contributor usernames. */ //print(queryString); final client = http.Client(); final url = Uri.parse('https://api.discogs.com/database/search?$queryString'); final headers = { 'User-Agent': AppConfig.userAgent, 'Authorization': 'Discogs key=$discogsKey, secret=${discogsSecret.split('').reversed.join()}', }; http.Response resp; try { resp = await client .get(url, headers: headers) .timeout(const Duration(seconds: 15)); } catch (e) { return ResponseDiscogs(imageUrl, duration); } if (resp.statusCode == 403) { // CloudFlare anti-scrap technique IUAM // TODO: find a way to work-around that } if (resp.statusCode == 200) { Map<String, dynamic> reply = jsonDecode(resp.body); //print(reply); final results = reply['results']; for (var res in results) { //print(res['title']); if (res['title'].toLowerCase().contains(search['q']?.toLowerCase())) { imageUrl = res['cover_image']; //print(imageUrl); break; } } } else { //debugPrint('debug: ${resp.statusCode}: ${resp.body}'); debugPrint('debug: discogs search = ${resp.statusCode}'); } if (imageUrl != '') { debugPrint('debug: found on discogs $imageUrl'); } return ResponseDiscogs(imageUrl, duration); }
0
mirrored_repositories/last_song
mirrored_repositories/last_song/lib/bbcradio.dart
import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'bandcamp.dart'; import 'helpers.dart'; import 'package:http/http.dart' as http; const String bbcLatestSegments = 'https://rms.api.bbc.co.uk/v2/services/SERVICE/segments/latest?experience=domestic&offset=0&limit=10'; const String bbcCurrentShow = 'https://rms.api.bbc.co.uk/v2/broadcasts/latest?service=SERVICE&on_air=now'; class BBCRadio extends Channel { static List<dynamic> subchannels = [ {"code": "bbc_radio_one", "name": "BBC Radio 1"}, {"code": "bbc_radio_two", "name": "BBC Radio 2"}, {"code": "bbc_radio_three", "name": "BBC Radio 3"}, {"code": "bbc_radio_four", "name": "BBC Radio 4"}, {"code": "bbc_radio_five_live", "name": "BBC Radio 5"}, //{"code": "bbc_radio_six", "name": "BBC Radio 6"}, ]; BBCRadio(String code, String name) { radio = 'BBC Radio'; subchannel.codename = code; subchannel.title = name; subchannel.imageUrl = 'assets/img/$code.png'; subchannel.bigImageUrl = subchannel.imageUrl; } @override String toString() { return 'BBCRadio(subchannel: ${subchannel.toString()}'; } @override Future<int> fetchCurrentTrack([bool manual = false]) async { int ret = 0; int _ = await getCurrentShow(); recentTracks = await getRecentTracks(); if (recentTracks.isNotEmpty) { currentTrack.updateFrom(recentTracks[0]); } if (currentTrack.imageUrl == '' && currentTrack.artist != 'Artist' && currentTrack.title != 'Title') { ResponseBandcamp sb = await searchBandcamp( '${currentTrack.artist} ${currentTrack.title}', 't'); if (sb.imageUrl != '') { currentTrack.imageUrl = sb.imageUrl; } if (sb.duration != '') { currentTrack.duration = sb.duration; } } notifyListeners(); return ret; } @override Future<List<Track>> getRecentTracks() async { List<Track> ret = <Track>[]; final http.Response resp; final headers = { 'User-Agent': AppConfig.userAgent, }; try { final String bbcRadioUrl = bbcLatestSegments.replaceFirst('SERVICE', subchannel.codename); resp = await http .get(Uri.parse(bbcRadioUrl), headers: headers) .timeout(const Duration(seconds: 15)); //print(resp.statusCode); } catch (e) { debugPrint('debug: $e'); return ret; } if (resp.statusCode == 200) { Map<String, dynamic> rj = jsonDecode(resp.body); for (var segment in rj['data']) { Track track = Track( artist: segment['titles']['primary'], title: segment['titles']['secondary'], imageUrl: segment['image_url']); if (segment['titles']['tertiary'] != null) { track.album = segment['titles']['tertiary']; } if (track.imageUrl == 'https://ichef.bbci.co.uk/images/ic/{recipe}/p0bqcdzf.jpg') { track.imageUrl = ''; } else { track.imageUrl = track.imageUrl.replaceFirst('{recipe}', '400x400'); } if (show.start != null) { DateTime dd = show.start!.add(Duration(seconds: segment['offset']['start'])); if (DateTime.now().compareTo(dd) == 1) { track.diffusionDate = dd.toIso8601String(); } else { // this means it comes from the previous show // TODO: fetch it, and get the start time ? } } int duration = segment['offset']['end'] - segment['offset']['start']; track.duration = '${duration ~/ 60}:${duration % 60}'; ret.add(track); } } //print(ret); return ret; } Future<int> getCurrentShow() async { final http.Response resp; final headers = { 'User-Agent': AppConfig.userAgent, }; int ret = 0; try { resp = await http .get( Uri.parse( bbcCurrentShow.replaceFirst('SERVICE', subchannel.codename)), headers: headers) .timeout(const Duration(seconds: 15)); //print(resp.statusCode); } catch (e) { debugPrint('debug: $e'); return ret; } ret = 1; if (resp.statusCode == 200) { Map<String, dynamic> rj = json.decode(utf8.decode(resp.bodyBytes)); final broadcast = rj['data'][0]; final programme = broadcast['programme']; // which one to pick between titles/primary, titles/secondary, titles/primary_title, titles/entity_title ? show.name = programme['titles']['secondary']; show.author = programme['titles']['primary']; show.start = DateTime.parse(broadcast['start']).toLocal(); show.end = DateTime.parse(broadcast['end']).toLocal(); show.airingTime = '${show.start.toString().substring(11, 16)} - ${show.end.toString().substring(11, 16)}'; show.imageUrl = programme['images'][0]['url'].replaceFirst('{recipe}', '400x400'); if (programme['synopses']['long'] != null) { show.description = programme['synopses']['long']; } else if (programme['synopses']['medium'] != null) { show.description = programme['synopses']['medium']; } else if (programme['synopses']['short'] != null) { show.description = programme['synopses']['short']; } } return ret; } } //const String bbcRadio = // 'https://rms.api.bbc.co.uk/v2/services/bbc_radio_one/tracks/latest/playable?limit=10'; // 'https://rms.api.bbc.co.uk/v2/services/bbc_radio_one/segments/latest?experience=domestic&offset=0&limit=10'; // https://rms.api.bbc.co.uk/docs/swagger.json#/definitions/ErrorResponse // curl -X 'GET' 'https://rms.api.bbc.co.uk/v2/broadcasts/latest?service=bbc_radio_one&on_air=now' -H 'accept: application/json' -H 'X-API-Key: 3A5LU4tQWvWW3lpgF5OT4IWUoyLaju9z'|jq . // curl -X 'GET' 'https://rms.api.bbc.co.uk/v2/broadcasts/latest?service=bbc_radio_one&on_air=previous&previous=120' -H 'accept: application/json' -H 'X-API-Key: 3A5LU4tQWvWW3lpgF5OT4IWUoyLaju9z'|jq . /* curl 'https://rms.api.bbc.co.uk/v2/services/bbc_radio_one/segments/latest?experience=domestic&offset=0&limit=4' \ -H 'Accept: application/json' \ -H 'Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7' \ -H 'Cache-Control: no-cache' \ -H 'Connection: keep-alive' \ -H 'DNT: 1' \ -H 'Origin: https://www.bbc.co.uk' \ -H 'Pragma: no-cache' \ -H 'Referer: https://www.bbc.co.uk/' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Site: same-site' \ -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36' \ -H 'X-API-Key: 3A5LU4tQWvWW3lpgF5OT4IWUoyLaju9z' \ -H 'sec-ch-ua: "Chromium";v="109", "Not_A Brand";v="99"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "Linux"' \ -H 'sec-gpc: 1' \ --compressed */
0
mirrored_repositories/last_song
mirrored_repositories/last_song/lib/somafm.dart
import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:timezone/timezone.dart' as tz; import 'package:timezone/data/latest.dart' as tz; import 'package:http/http.dart' as http; import 'package:html/parser.dart' as parser; import 'helpers.dart'; import 'bandcamp.dart'; import 'discogs.dart'; /* SomaFM Terms of Service includes the following paragraph: Scrobbling and Automated Re-Posting of Playlists Forbidden "Scrobbling" and/or automated re-posting of playlists and now playing information is against our terms of use, and we may block access to users or services what are doing this. I guess, we are not be allowed to do what we are doing in this file, after all? depending on how you read it? */ class SomaFm extends Channel { static Future<List<dynamic>> loadSubChannels() async { // list of channels available at https://api.somafm.com/channels.json (or somafm.com) // TODO: use the online version instead of the hardcoded downloaded one ? final cj = await rootBundle.loadString('assets/somafm_channels.json'); return json.decode(cj)['channels']; } SomaFm(String subchannel, String name, String imageUrl, String bigImageUrl, String description, String dj) : super(radio: 'Soma FM') { this.subchannel.title = name; this.subchannel.imageUrl = imageUrl; this.subchannel.bigImageUrl = bigImageUrl; this.subchannel.codename = subchannel; show.author = dj; show.airingTime = ''; show.imageUrl = this.subchannel.bigImageUrl; show.name = this.subchannel.title; show.description = description; } @override String toString() { return 'SomaFm(subchannel: ${subchannel.toString()}'; } @override Future<int> fetchCurrentTrack([bool manual = false]) async { int ret = 0; Track track; recentTracks = await getRecentTracks(); if (recentTracks.isNotEmpty) { track = recentTracks.elementAt(0); } else { track = Track(); } if (track.title != currentTrack.title && track.artist != currentTrack.artist) { currentTrack.updateFrom(track); // search for an image cover ResponseBandcamp resp = await searchBandcamp( '${track.title} ${track.album} ${track.artist}', 't'); if (resp.imageUrl.isNotEmpty) { currentTrack.imageUrl = resp.imageUrl; if (resp.duration.isNotEmpty) { currentTrack.duration = resp.duration; } } else { resp = await searchBandcamp('${track.title} ${track.artist}', 't'); if (resp.imageUrl.isNotEmpty) { currentTrack.imageUrl = resp.imageUrl; } else { // try with discogs ResponseDiscogs resp = await searchDiscogs({ 'artist': track.artist, 'q': track.album, }); if (resp.imageUrl.isNotEmpty) { currentTrack.imageUrl = resp.imageUrl; } } } notifyListeners(); ret += 1; } return ret; } @override Future<List<Track>> getRecentTracks() async { // get timezone and current date of San Francisco tz.initializeTimeZones(); tz.Location sanFrancisco = tz.getLocation('America/Los_Angeles'); tz.TZDateTime now = tz.TZDateTime.now(sanFrancisco); String timeZone = convertSecondsToHours( sanFrancisco.timeZone(now.millisecondsSinceEpoch).offset ~/ 1000); String currentDate = now.toString().substring(0, 10); List<Track> ret = <Track>[]; String page = 'https://somafm.com/recent/${subchannel.codename}.html'; final http.Response resp; try { resp = await http.get(Uri.parse(page), headers: { 'User-Agent': AppConfig.userAgent, }).timeout(const Duration(seconds: 15)); } catch (e) { debugPrint('debug: $e'); return ret; } if (resp.statusCode != 200) { return ret; } final document = parser.parse(resp.body); final rows = document.querySelectorAll('#playinc table tr'); rows.removeAt(0); // remove header of table for (var element in rows) { final tds = element.querySelectorAll('td'); if (tds.length != 5) continue; final time = tds[0].text.replaceFirst(' (Now) ', '').trim(); String artist = 'Artist'; if (tds[1].firstChild != null && tds[1].firstChild?.text != null) { artist = (tds[1].firstChild?.text)!; } String album = 'Album'; if (tds[3].firstChild != null && tds[3].firstChild?.text != null) { album = (tds[3].firstChild?.text)!; } // convert SF local time to our local time // add current SF date in front of parsed hour // this gives error at midnight DateTime diffusionDate = DateTime.parse('${currentDate}T$time $timeZone'); Track track = Track( diffusionDate: diffusionDate.toLocal().toString().replaceFirst(' ', 'T'), artist: artist, title: tds[2].text, album: album); //debugPrint('$track'); ret.add(track); } return ret; } } String convertSecondsToHours(int offset) { int minutes = offset ~/ 60; int hours = minutes ~/ 60; String sh = hours.abs().toString().padLeft(2, '0'); String sign = ''; if (hours / hours.abs() < 0) sign = '-'; String sm = (minutes % 60).toString().padLeft(2, '0'); return '$sign$sh$sm'; }
0
mirrored_repositories/last_song
mirrored_repositories/last_song/lib/nova.dart
import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:intl/intl.dart'; import 'package:http/http.dart' as http; import 'package:html_unescape/html_unescape.dart'; import 'package:html/parser.dart' as parser; import 'bandcamp.dart'; import 'helpers.dart'; const String radioNova = 'https://www.nova.fr/wp-json/radios/'; class Nova extends Channel { static List<dynamic> subchannels = [ { "code": "radio-nova", "name": "Radio Nova", "id": "910", "image": "/2/2022/12/Radio-Nova-en-direct.png" }, { "code": "nouvo-nova", "name": "Nouvo Nova", "id": "79676", "image": "/2/2022/11/Web-radio--Nouvo-Nova.png" }, { "code": "nova-la-nuit", "name": "Nova la Nuit", "id": "916", "image": "/2/2022/11/Web-radio--Nova-la-Nuit.png" }, { "code": "nova-classics", "name": "Nova Classics", "id": "913", "image": "/2/2020/10/Web-radio--Nova-Classics.png" }, { "code": "nova-danse", "name": "Nova Danse", "id": "560", "image": "/2/2020/09/Web-radio--Nova-Danse.png" }, ]; // datetime until which the last update request is valid according to cache-control(max-age) header, age and date static DateTime validity = DateTime.now().subtract(const Duration(minutes: 1)); Nova(String code, String name, String imageUrl, String id) : super(radio: 'Radio Nova') { subchannel.codename = code; subchannel.title = name; subchannel.id = id; subchannel.imageUrl = 'https://www.nova.fr/wp-content/uploads/sites$imageUrl'; subchannel.bigImageUrl = subchannel.imageUrl; show.description = ""; } @override String toString() { return 'Nova(subchannel: ${subchannel.toString()}'; } String addTrackDuration(String diffusionDate, String duration) { return DateTime.parse(diffusionDate) .add(Duration( seconds: int.parse(duration.split(':')[1]), minutes: int.parse(duration.split(':')[0]))) .toString(); } int updateFromJson(Map<String, dynamic> jsonData) { int ret = 0; final ct = jsonData['currentTrack']; //debugPrint(json.encode(ct).toString()); if (ct != null) { if (currentTrack.title != ct['title']) { ret += 1; currentTrack.id = int.parse(ct['id']); currentTrack.artist = ct['artist']; currentTrack.title = ct['title']; currentTrack.imageUrl = ct['image'] is String ? ct['image'] : ''; if (currentTrack.imageUrl.endsWith('nova-default.png')) { currentTrack.imageUrl = ''; } currentTrack.diffusionDate = ct['diffusion_date']; currentTrack.duration = ct['duration']; currentTrack.diffusionDate = addTrackDuration(currentTrack.diffusionDate, currentTrack.duration); currentTrack.diffusionDate = DateTime.parse(currentTrack.diffusionDate).toIso8601String(); } } final cs = jsonData['currentShow']; if (cs != null) { show.name = cs['title']; show.author = HtmlUnescape().convert(cs['author']); show.airingTime = '${cs["start_time"]} - ${cs["end_time"]}'; } final radio = jsonData['radio']; if (radio != null) { show.imageUrl = radio['thumbnail']; } return ret; } @override Future<int> fetchCurrentTrack([bool manual = false]) async { int ret = 0; final http.Response resp; // update if cache is old if (DateTime.now().compareTo(validity) >= 0) { try { resp = await http .get(Uri.parse('$radioNova${subchannel.codename}')) .timeout(const Duration(seconds: 15)); //print(resp.statusCode); } catch (e) { debugPrint('debug: $e'); return 0; } if (resp.statusCode == 200) { ret = updateFromJson(jsonDecode(resp.body)); // try to get an image cover if there is none if (currentTrack.artist != 'Artist' && currentTrack.imageUrl.isEmpty) { ResponseBandcamp resp = await searchBandcamp( '${currentTrack.artist} ${currentTrack.title}', 't'); if (resp.imageUrl.isNotEmpty) { currentTrack.imageUrl = resp.imageUrl; } } // update validity variable int age = 0; if (ret > 0) { // parse age header String? ageHeader = resp.headers['age']; if (ageHeader != null) { age = int.parse(ageHeader); } int maxAge = 0; // parse cache-control header String? cacheControl = resp.headers['cache-control']; if (cacheControl != null) { final cc = cacheControl.split(','); for (var element in cc) { String e = element.trim().toLowerCase(); if (e.startsWith('max-age=')) { maxAge = int.parse(e.replaceFirst('max-age=', '')); break; } } } // add cache age to date header String? date = resp.headers['date']; if (date != null) { validity = DateFormat('EEE, d MMM y HH:mm:ss Z', 'en_US') .parse(date.replaceAll('GMT', '+0000'), true) .add(Duration(seconds: maxAge - age)); } } } } else { ret = 0; } recentTracks = await getRecentTracks(); // if ajax call returned nothing but last track list is more up to date if (recentTracks.isNotEmpty) { Track lastTrack = recentTracks[0]; final DateTime ltd = DateTime.parse(lastTrack.diffusionDate); final DateTime cd = DateTime.parse(currentTrack.diffusionDate); if (cd.compareTo(ltd) == -1) { debugPrint('Late update'); currentTrack.updateFrom(lastTrack); } } notifyListeners(); return ret; } @override Future<List<Track>> getRecentTracks() async { String url = 'https://www.nova.fr/wp-admin/admin-ajax.php'; List<Track> ret = <Track>[]; // 20 minutes from now String now = DateTime.now().toString(); String startTime = now.substring(11, 16); // action=loadmore_programs&date=&time=18%3A08&page=1&radio=910 String radioId = subchannel.id; final rawData = { 'action': 'loadmore_programs', 'date': '', 'time': startTime, 'page': '1', 'radio': radioId }; final headers = { 'x-requested-with': 'XMLHttpRequest', 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'user-agent': AppConfig.userAgent, }; final http.Response resp; try { resp = await http .post(Uri.parse(url), body: rawData, headers: headers) .timeout(const Duration(seconds: 15)); //print(resp.statusCode); } catch (e) { debugPrint('debug: $e'); return ret; } if (resp.statusCode != 200) { return ret; } final document = parser.parse(resp.body); for (var element in document.getElementsByClassName('wwtt_right')) { final time = element.querySelector('p.time')?.text; final dd = '${now.substring(0, 10)}T$time:00'; String diffusionDate = DateTime.parse(dd).toIso8601String(); final title = element.querySelectorAll('p')[1].text; final artist = element.querySelector('h2'); final imgWwtt = element.querySelector('.img_wwtt'); final img = imgWwtt?.getElementsByTagName('img'); String imageUrl = ''; if (img != null && img.isNotEmpty) { imageUrl = img.first.attributes['src']!; } Track track = Track( diffusionDate: diffusionDate, title: title, artist: artist != null ? artist.text : 'Artist', imageUrl: imageUrl); //debugPrint('$track'); ret.add(track); } //debugPrint(ret); return ret; } }
0
mirrored_repositories/last_song
mirrored_repositories/last_song/lib/main.dart
import 'dart:async'; import 'dart:io'; import 'package:http/http.dart' as http; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'helpers.dart'; import 'favorites.dart'; import 'myextensions.dart'; import 'lastsong.dart'; import 'mydrawer.dart'; import 'current_track.dart'; void main(List<String> args) async { WidgetsFlutterBinding.ensureInitialized(); try { // check we can reach some let's encrypt certificate based website final http.Response _ = await http.get(Uri.parse('https://valid-isrgrootx1.letsencrypt.org/')); } on HandshakeException { // load Let's Encrypt new certificate if this has failed ByteData data = await PlatformAssetBundle().load('assets/ca/lets-encrypt-r3.pem'); SecurityContext.defaultContext .setTrustedCertificatesBytes(data.buffer.asUint8List()); } on SocketException { // TODO: we need to recheck that later on debugPrint('debug: Failed to test for valid-isrgrootx1.letsencrypt.org'); } runApp(MultiProvider( providers: [ ChangeNotifierProvider<Favorites>(create: (context) { Favorites favorites = Favorites(); return favorites; }), ChangeNotifierProvider<ChannelManager>( create: (context) { ChannelManager cm = ChannelManager(); return cm; }, ), ], builder: (context, child) { final favorites = context.watch<Favorites>(); final cm = context.watch<ChannelManager>(); // initialization is done here, be sure to do it only once if (cm.channels.isEmpty) { Future.delayed(Duration.zero, () async { await cm.initialize(); final f = await Favorites.loadFavorites(cm.channels); favorites.set(f); if (favorites.isNotEmpty) { cm.changeChannel(favorites.first); } else { cm.changeChannel(cm.channels.first); } cm.fetchCurrentTrack(); cm.launchTimer(); }); } return 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: AppConfig.name, theme: ThemeData( //useMaterial3: true, primaryColor: Colors.deepOrange, primaryColorLight: Colors.deepOrange, //primarySwatch: Colors.deepOrange, ), home: Consumer<ChannelManager>(builder: (context, channel, child) { return MyHomePage( title: "Last played song on ${channel.currentChannel.radio}"); }), //debugShowCheckedModeBanner: false, ); } } class MyHomePage extends StatelessWidget { const MyHomePage({super.key, required this.title}); final String title; void showSnackBar(BuildContext context) { ScaffoldMessenger.of(context) ..clearSnackBars() ..showSnackBar(const SnackBar( backgroundColor: Colors.black87, content: Text('No update available'), behavior: SnackBarBehavior.floating, )); } @override Widget build(BuildContext context) { final cm = Provider.of<ChannelManager>(context, listen: true); final List<List<Widget>> channelsByType = <List<Widget>>[]; if (channelsByType.isEmpty) { // initialize _channelsByType final Map<String, dynamic> networks = {}; for (var c in cm.channels) { String type = c.runtimeType.toString(); if (networks.keys.contains(type)) { networks[type].add(MyRadioExpansionPanelListTile(channel: c)); } else { networks[type] = [MyRadioExpansionPanelListTile(channel: c)]; } } for (var k in networks.keys) { channelsByType.add(networks[k]); } } Scaffold scaffold = Scaffold( drawer: MyDrawer(child: MyRadioExpansionPanelList(children: channelsByType)), appBar: AppBar( backgroundColor: Colors.deepOrange, foregroundColor: Colors.white, title: Text((MediaQuery.of(context).size.width < 700) ? title.replaceFirst(' played ', ' ').replaceFirst(' on ', ' - ') : title), actions: _buildActionButtons(context), ), body: LayoutBuilder(builder: (context, constraints) { return RefreshIndicator( child: SingleChildScrollView( physics: const AlwaysScrollableScrollPhysics(), child: ConstrainedBox( constraints: BoxConstraints( minHeight: constraints.maxHeight, ), child: IntrinsicHeight( child: Center( child: CurrentTrackWidget(constraints: constraints), )))), onRefresh: () async { int ret = await cm.fetchCurrentTrack(cancel: true, manual: true); if (ret < 1) { showSnackBar(context); } }); }), floatingActionButton: FloatingActionButton( backgroundColor: Colors.deepOrange, foregroundColor: Colors.white, onPressed: () async { int ret = await cm.fetchCurrentTrack(cancel: true, manual: true); if (ret < 1) { showSnackBar(context); } }, tooltip: 'Update current track', child: const Icon(Icons.sync), ), bottomSheet: const MyBottomSheet(), ); return scaffold; } List<Widget> _buildActionButtons(BuildContext context) { final actions = <IconButton>[ IconButton( icon: const Icon(Icons.copy_all), tooltip: 'Copy all', onPressed: () { final cm = Provider.of<ChannelManager>(context, listen: false); StringBuffer txt = StringBuffer( '${cm.currentChannel.currentTrack.artist.toTitleCase()} - ${cm.currentChannel.currentTrack.title.toTitleCase()}'); if (cm.currentChannel.currentTrack.album.isNotEmpty && cm.currentChannel.currentTrack.album != 'Album') { txt.write(' - ${cm.currentChannel.currentTrack.album}'); } _copyToClipboard(context, txt.toString()); }, ), IconButton( icon: const Icon(Icons.favorite), tooltip: 'Favorites', onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: (context) => const FavoritesRoute(), ), ); }, ), IconButton( icon: const Icon(Icons.history), tooltip: 'Track history', onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: (context) => const LastSongListRoute(), ), ); }, ), ]; if (MediaQuery.of(context).size.width > 500) { // return the list of IconButtons if screen is large enough return actions; } else { // build a PopupMenuButton from the IconsButtons return <Widget>[ PopupMenuButton<IconButton>(itemBuilder: (context) { return actions.map((e) { return PopupMenuItem<IconButton>( // Navigator inside PopupMenuItem does not work: https://stackoverflow.com/a/69589313/283067 onTap: () async { await Future.delayed(Duration.zero, () { e.onPressed!(); }); }, child: Text(e.tooltip!), ); }).toList(); }) ]; } } Future<void> _copyToClipboard(BuildContext context, String text) async { Clipboard.setData(ClipboardData(text: text)); ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content: Text('Copied to clipboard'), backgroundColor: Colors.black87, behavior: SnackBarBehavior.floating, )); } } class CurrentShowText extends StatelessWidget { const CurrentShowText({super.key}); @override Widget build(BuildContext context) { return Consumer<ChannelManager>(builder: (context, cm, child) { Channel currentChannel = cm.currentChannel; return RichText( softWrap: false, overflow: TextOverflow.clip, text: TextSpan( text: '', // empty just to define the default style of the whole RichText style: DefaultTextStyle.of(context).style, children: <TextSpan>[ TextSpan( text: currentChannel.show.name != 'Show' ? currentChannel.show.name : currentChannel.subchannel.title, style: const TextStyle( fontWeight: FontWeight .w700, // bold is too heavy and cause blur/smudge color: Colors.white), ), TextSpan( text: currentChannel.show.author.isNotEmpty && currentChannel.show.author != 'Author' ? ' - ${currentChannel.show.author}' : '', style: const TextStyle( color: Colors.white, fontWeight: FontWeight.w300, // same idea as above ), ), TextSpan( text: currentChannel.show.airingTime.isNotEmpty && currentChannel.show.airingTime != '00:00 - 00:00' ? '\n${currentChannel.show.airingTime}' : '', style: const TextStyle( color: Colors.white, fontWeight: FontWeight.w300, ), ), ])); }); } } class MyBottomSheetWidget extends StatelessWidget { final double bottomSheetSize; const MyBottomSheetWidget({super.key, required this.bottomSheetSize}); @override Widget build(BuildContext context) { return Consumer<ChannelManager>(builder: (context, cm, child) { String image = cm.currentChannel.show.imageUrl; if (image == '') { image = cm.currentChannel.subchannel.imageUrl; } return BottomSheet( enableDrag: false, builder: (context) { Widget wi; if (image.isEmpty) { wi = SizedBox( width: bottomSheetSize, height: bottomSheetSize, ); } else if (image.startsWith('assets')) { wi = Image.asset(image, height: bottomSheetSize, width: bottomSheetSize); } else { wi = CachedNetworkImage( imageUrl: image, memCacheHeight: bottomSheetSize.toInt(), memCacheWidth: bottomSheetSize.toInt(), httpHeaders: { 'User-Agent': AppConfig.userAgent, }, placeholder: (context, url) => SizedBox( height: bottomSheetSize, width: bottomSheetSize, ), errorWidget: (context, url, error) => SizedBox( height: bottomSheetSize, width: bottomSheetSize, ), ); } return InkWell( onTap: () async { return _buildCurrentShowDialog(context, cm); }, child: Container( height: bottomSheetSize, color: Colors.black87, child: Row( children: [ wi, const SizedBox( width: 15, ), const CurrentShowText(), ], ))); }, onClosing: () {}, ); }); } Future<void> _buildCurrentShowDialog( BuildContext context, ChannelManager cm) { final imageUrl = cm.currentChannel.show.imageUrl; return showDialog<void>( context: context, builder: (context) { return AlertDialog( icon: imageUrl.startsWith('assets') ? Image.asset(imageUrl, cacheHeight: 400, cacheWidth: 400) : CachedNetworkImage( imageUrl: imageUrl, memCacheHeight: 400, memCacheWidth: 400, httpHeaders: { 'User-Agent': AppConfig.userAgent, }, errorWidget: (context, url, error) => Image.asset( defaultImage, cacheHeight: 400, cacheWidth: 400, ), ), title: Text(cm.currentChannel.show.name), content: Text( cm.currentChannel.show.description, overflow: TextOverflow.clip, softWrap: true, ), actions: <Widget>[ TextButton( style: TextButton.styleFrom( textStyle: Theme.of(context).textTheme.labelLarge, foregroundColor: Colors.white, backgroundColor: Colors.deepOrange, ), child: const Text('Dismiss'), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }); } } class MyBottomSheet extends StatelessWidget { const MyBottomSheet({super.key}); @override Widget build(BuildContext context) { return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { if (constraints.maxHeight > 700) { return const MyBottomSheetWidget( bottomSheetSize: AppConfig.bottomSheetSizeLargeScreen); } else { return const MyBottomSheetWidget( bottomSheetSize: AppConfig.bottomSheetSizeSmallScreen); } }); } }
0
mirrored_repositories/last_song
mirrored_repositories/last_song/lib/favorites.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:reorderable_grid/reorderable_grid.dart'; import 'helpers.dart'; import 'dart:async'; import 'package:shared_preferences/shared_preferences.dart'; const String defaultImage = 'assets/img/black-record-vinyl-640x640.png'; class Favorites extends ChangeNotifier { final List<Channel> _favorites = <Channel>[]; Favorites({favorites}) { if (favorites != null) { _favorites.addAll(favorites); } } Favorites.fromChannelList(List<Channel> channels) { _favorites.clear(); for (var c in channels) { if (c.isFavorite) { _favorites.add(c); } } } @override String toString() { return 'Favorites(${_favorites.toString()})'; } Channel operator [](int index) { return _favorites[index]; } List<Channel> toList() { return _favorites; } void set(Favorites favorites) { _favorites.clear(); for (var f in favorites.toList()) { _favorites.add(f); f.isFavorite = true; } notifyListeners(); } void add(Channel c) { _favorites.add(c); c.isFavorite = true; notifyListeners(); } void remove(Channel c) { _favorites.remove(c); c.isFavorite = false; notifyListeners(); } Channel removeAt(int index) { Channel f = _favorites.removeAt(index); f.isFavorite = false; notifyListeners(); return f; } void insert(int index, Channel c) { _favorites.insert(index, c); c.isFavorite = true; notifyListeners(); } void addAll(List<Channel> channels) { _favorites.addAll(channels); for (var c in channels) { c.isFavorite = true; } notifyListeners(); } void clear() { for (var f in _favorites) { f.isFavorite = false; } _favorites.clear(); notifyListeners(); } int indexOf(Channel f) { return _favorites.indexOf(f); } int get length { return _favorites.length; } bool get isEmpty { return _favorites.isEmpty; } bool get isNotEmpty { return _favorites.isNotEmpty; } Iterable<T> map<T>(T Function(Channel) toElement) { return _favorites.map((e) => toElement(e)); } Channel get first { return _favorites[0]; } Future<void> saveFavorites() async { final prefs = await SharedPreferences.getInstance(); prefs.setStringList( 'favorites', _favorites.map((e) => e.subchannel.codename).toList()); } bool contains(Channel c) { return _favorites.contains(c); } static Future<Favorites> loadFavorites(List<Channel> channels) async { final prefs = await SharedPreferences.getInstance(); final fs = prefs.getStringList('favorites'); List<Channel> favorites = <Channel>[]; if (fs != null) { for (var f in fs) { bool found = false; int indx = 0; while (indx < channels.length && !found) { if (channels[indx].subchannel.codename == f) { channels[indx].isFavorite = true; favorites.add(channels[indx]); found = true; } else { indx++; } } } } return Favorites(favorites: favorites); } } class FavoritesRoute extends StatelessWidget { const FavoritesRoute({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.deepOrange, foregroundColor: Colors.white, title: const Text('Favorites'), ), body: Consumer<Favorites>( builder: (context, favorites, child) { return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { if (favorites.isEmpty) { return const Center(child: Text('Nothing to show here')); } if (constraints.maxWidth > 700) { return const FavoritesGrid(); } else { return const FavoritesList(); } }, ); }, ), ); } } class FavoritesGrid extends StatefulWidget { const FavoritesGrid({super.key}); @override State<FavoritesGrid> createState() => _FavoritesGridState(); } class _FavoritesGridState extends State<FavoritesGrid> { @override void initState() { super.initState(); } void _onPressed(Channel f) { final favorites = Provider.of<Favorites>(context, listen: false); int index = favorites.indexOf(f); favorites.remove(f); favorites.saveFavorites(); ScaffoldMessenger.of(context) ..clearSnackBars() ..showSnackBar(SnackBar( backgroundColor: Colors.black87, content: const Text('The favorite has been deleted'), behavior: SnackBarBehavior.floating, action: SnackBarAction( label: "Undelete", onPressed: () { favorites.insert(index, f); favorites.saveFavorites(); }))); } @override Widget build(BuildContext context) { return Consumer<Favorites>(builder: (context, favorites, child) { return Center( child: SizedBox( width: 1200, // 400px image * 3, could be a little bigger but why care ? child: ReorderableGridView.count( crossAxisCount: 3, children: favorites.map((f) { return InkWell( key: ObjectKey(f), child: Card( child: Column( children: [ Expanded( child: Container( padding: const EdgeInsets.fromLTRB(15, 15, 15, 0), // for a grid of 3 columns this gives an image of 313x313. Use 350px for memcache child: f.subchannel.bigImageUrl .startsWith('assets') ? Image.asset(f.subchannel.bigImageUrl, cacheHeight: 350, cacheWidth: 350, fit: BoxFit.fitHeight) : CachedNetworkImage( imageUrl: f.subchannel.bigImageUrl, fit: BoxFit.fitHeight, memCacheHeight: 350, memCacheWidth: 350, httpHeaders: { 'User-Agent': AppConfig.userAgent, }, errorWidget: (context, url, error) => const SizedBox( height: 350, width: 350, ), ))), ListTile( title: Center(child: Text(f.subchannel.title)), subtitle: Center(child: Text(f.radio)), trailing: IconButton( icon: const Icon(Icons.delete), onPressed: () { _onPressed(f); }, ), ), ], ), ), onTap: () { ChannelManager cm = Provider.of<ChannelManager>(context, listen: false); cm.changeChannel(f); cm.fetchCurrentTrack(cancel: true); Navigator.pop(context); }, ); }).toList(), onReorder: (oldIndex, newIndex) { Channel val = favorites.removeAt(oldIndex); favorites.insert(newIndex, val); favorites.saveFavorites(); }, ))); }); } } class FavoritesList extends StatefulWidget { const FavoritesList({super.key}); @override State<FavoritesList> createState() => _FavoritesListState(); } class _FavoritesListState extends State<FavoritesList> { @override void initState() { super.initState(); } void _onDismissed(int index) { final favorites = Provider.of<Favorites>(context, listen: false); Channel oldFavorite = favorites[index]; favorites.removeAt(index); favorites.saveFavorites(); ScaffoldMessenger.of(context) ..clearSnackBars() ..showSnackBar(SnackBar( backgroundColor: Colors.black87, content: const Text('The favorite has been deleted'), behavior: SnackBarBehavior.floating, action: SnackBarAction( label: "Undelete", onPressed: () { favorites.insert(index, oldFavorite); favorites.saveFavorites(); }))); } @override Widget build(BuildContext context) { return Consumer<Favorites>(builder: (context, favorites, child) { return ReorderableListView.builder( itemCount: favorites.length, itemBuilder: (context, index) { if (favorites.isEmpty) { return const SizedBox( height: 0, width: 0, ); } final f = favorites[index]; return Dismissible( key: ObjectKey(f), background: Container(color: Colors.deepOrange), onDismissed: (direction) { _onDismissed(index); }, child: ListTile( key: ObjectKey(f), leading: f.subchannel.imageUrl.startsWith('assets') ? Image.asset( f.subchannel.imageUrl, cacheHeight: 64, cacheWidth: 64, ) : (f.subchannel.imageUrl.isEmpty ? Image.asset( defaultImage, cacheHeight: 64, cacheWidth: 64, ) : Image( image: ResizeImage( CachedNetworkImageProvider(headers: { 'User-Agent': AppConfig.userAgent, }, f.subchannel.imageUrl), height: 64, width: 64))), title: Text(f.subchannel.title), subtitle: Text(f.radio), onTap: () { ChannelManager cm = Provider.of<ChannelManager>(context, listen: false); cm.changeChannel(favorites[index]); cm.fetchCurrentTrack(cancel: true); Navigator.pop(context); })); }, onReorder: (oldIndex, newIndex) { if (oldIndex < newIndex) { newIndex -= 1; } Channel val = favorites.removeAt(oldIndex); favorites.insert(newIndex, val); favorites.saveFavorites(); }, ); }); } }
0
mirrored_repositories/0xVAULT
mirrored_repositories/0xVAULT/lib/main.dart
import 'package:flutter/material.dart'; import 'package:bot_toast/bot_toast.dart'; import './screens/swipe_screen.dart'; /* to fix: - code that completely ignores flutters best practices, like: - not splitting the code into small widgets.... - some shitty logic here n there - animations */ void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( builder: BotToastInit(), navigatorObservers: [BotToastNavigatorObserver()], title: '0xVAULT', theme: ThemeData( // i'm color blind visualDensity: VisualDensity.adaptivePlatformDensity, brightness: Brightness.dark, primaryColor: Colors.grey, accentColor: Color.fromRGBO(224, 123, 224, 1), primaryColorDark: Color.fromRGBO(94, 221, 152, 1), bottomAppBarColor: Color.fromRGBO(22, 23, 32, 1), fontFamily: 'Monda', cardColor: Color.fromRGBO(61, 65, 74, 1), unselectedWidgetColor: Colors.grey, scaffoldBackgroundColor: Color.fromRGBO(42, 45, 54, 1), ), home: SwipeScreen(), ); } }
0
mirrored_repositories/0xVAULT/lib
mirrored_repositories/0xVAULT/lib/widgets/note.dart
import 'package:flutter/material.dart'; class NoteWidget extends StatelessWidget { final title; final text; final created; final modified; final private; NoteWidget({this.title, this.text, this.modified, this.created, this.private}); String displayString(val) { String temp = val.replaceAll('\n', ' '); int count = temp.length; if (count <= 200) return temp; else return temp.substring(0, 200) + '...'; } String displayDate() { Map week = { 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat', 7: 'Sun' }; String time = ''; if (this.modified != '' && this.modified != null) time = this.modified; else time = this.created; return '${week[DateTime.parse(time).weekday]} ${DateTime.parse(time).day}/${DateTime.parse(time).month}/${DateTime.parse(time).year}'; } @override Widget build(BuildContext context) { return ConstrainedBox( constraints: BoxConstraints( minHeight: 40, ), child: Card( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)), child: Padding( padding: EdgeInsets.all(5), child: Column( children: [ Row( children: [ Expanded( child: Center( child: Text( '$title', style: TextStyle( fontFamily: 'Monda', fontSize: 18, height: 1.6, color: Theme.of(context).primaryColorDark, ), ), ), ), ], ), Row( children: [ Expanded( child: Padding( padding: const EdgeInsets.only(top: 1.0), child: this.private ? Padding( padding: EdgeInsets.all(7), child: Text( 'ENCRYPTED', style: TextStyle( fontFamily: 'Monda', fontSize: 16, color: Theme.of(context).primaryColor, ), textAlign: TextAlign.center, ), ) : Text( '${displayString(text)}', style: TextStyle( fontFamily: 'Monda', height: 1.35, ), textAlign: TextAlign.left, ), ), ), ], ), Row(children: [ Expanded( child: Padding( padding: const EdgeInsets.only(top: 6.0), child: Text( displayDate(), style: TextStyle( fontFamily: 'Monda', fontSize: 10, color: Theme.of(context).primaryColorDark, ), textAlign: TextAlign.end, ), ), ) ]) ], ), ), elevation: 1, ), ); } }
0
mirrored_repositories/0xVAULT/lib
mirrored_repositories/0xVAULT/lib/models/config.dart
class Config { int _id; String _gistId; String _accessToken; String _vaultd; String _uniqued; String _pin; Config(this._gistId, this._accessToken, this._vaultd, this._uniqued, this._pin); Config.withId(this._id, this._gistId, this._accessToken, this._vaultd, this._uniqued, this._pin); int get id => _id; String get gistId => _gistId; String get accessToken => _accessToken; String get vaultd => _vaultd; String get uniqued => _uniqued; String get pin => _pin; set gistId(String newGistId) { this._gistId = newGistId; } set accessToken(String newAccessToken) { this._accessToken = newAccessToken; } set vaultd(String newCreated) { this._vaultd = newCreated; } set uniqued(String newModified) { this._uniqued = newModified; } set pin(String newPin) { this._pin = newPin; } Map<String, dynamic> toMap() { var map = Map<String, dynamic>(); if (id != null) { map['id'] = _id; } map['gistId'] = _gistId; map['accessToken'] = _accessToken; map['vaultd'] = _vaultd; map['uniqued'] = _uniqued; map['pin'] = _pin; return map; } Config.fromMapObject(Map<String, dynamic> map) { this._id = map['id']; this._gistId = map['gistId']; this._accessToken = map['accessToken']; this._vaultd = map['vaultd']; this._uniqued = map['uniqued']; this._pin = map['pin']; } }
0
mirrored_repositories/0xVAULT/lib
mirrored_repositories/0xVAULT/lib/models/note.dart
class Note { int _id; String _title; String _text; String _created; String _modified; bool _private; Note(this._title, this._text, this._created, this._modified, this._private); Note.withId(this._id, this._title, this._text, this._created, this._modified, this._private); int get id => _id; String get title => _title; String get text => _text; String get created => _created; String get modified => _modified; bool get private => _private; set title(String newTitle) { this._title = newTitle; } set text(String newText) { this._text = newText; } set created(String newCreated) { this._created = newCreated; } set modified(String newModified) { this._modified = newModified; } set private(bool newPrivate) { this._private = newPrivate; } Map<String, dynamic> toMap() { var map = Map<String, dynamic>(); if (id != null) { map['id'] = _id; } map['title'] = _title; map['text'] = _text; map['created'] = _created; map['modified'] = _modified; map['private'] = _private; return map; } Note.fromMapObject(Map<String, dynamic> map) { this._id = map['id']; this._title = map['title']; this._text = map['text']; this._created = map['created']; this._modified = map['modified']; this._private = map['private']==1?true:false; } }
0
mirrored_repositories/0xVAULT/lib
mirrored_repositories/0xVAULT/lib/utils/database_helper.dart
import 'dart:io'; import 'package:sqflite/sqflite.dart'; import 'dart:async'; import 'package:path_provider/path_provider.dart'; import '../models/note.dart'; import '../models/config.dart'; class DatabaseHelper { static DatabaseHelper _databaseHelper; // Singleton DatabaseHelper static Database _database; // Singleton Database String noteTable = 'note_table'; String colId = 'id'; String colTitle = 'title'; String colText = 'text'; String colCreated = 'created'; String colModified = 'modified'; String colPrivate = 'private'; // configs String configTable = 'config'; // table String gistId = 'gistId'; String accessToken = 'accessToken'; String vaultd = 'vaultd'; String unique = 'uniqued'; String pin = 'pin'; DatabaseHelper._createInstance(); // Named constructor to create instance of DatabaseHelper factory DatabaseHelper() { if (_databaseHelper == null) { _databaseHelper = DatabaseHelper._createInstance(); // This is executed only once, singleton object } return _databaseHelper; } Future<Database> get database async { if (_database == null) { _database = await initializeDatabase(); } return _database; } Future<Database> initializeDatabase() async { // Get the directory path for both Android and iOS to store database. Directory directory = await getApplicationDocumentsDirectory(); String path = directory.path + 'notes.db'; // Open/create the database at a given path var notesDatabase = await openDatabase(path, version: 1, onCreate: _createDb); return notesDatabase; } void _createDb(Database db, int newVersion) async { await db.execute(''' CREATE TABLE $noteTable ( $colId INTEGER PRIMARY KEY AUTOINCREMENT, $colTitle TEXT, $colText TEXT, $colCreated TEXT, $colModified TEXT, $colPrivate BOOLEAN) '''); await db.execute(''' CREATE TABLE $configTable ( id INTEGER, $gistId TEXT, $accessToken TEXT, $vaultd TEXT, $unique TEXT, $pin TEXT) '''); // default settings Config conf = Config.withId(1, 'gistID', 'gistAT', 'vaultd', 'unique', '000000'); await db.insert(configTable, conf.toMap()); } // Fetch Operation: Get all note objects from database Future<List<Map<String, dynamic>>> getNoteMapList() async { Database db = await this.database; // var result = await db.rawQuery('SELECT * FROM $noteTable order by $colTitle ASC'); var result = await db.query(noteTable, orderBy: "CASE $colModified WHEN '' THEN $colCreated ELSE $colModified END DESC"); return result; } // Insert Operation: Insert a note object to database Future<int> insertNote(Note note) async { Database db = await this.database; var result = await db.insert(noteTable, note.toMap()); return result; } // Update Operation: Update a note object and save it to database Future<int> updateNote(Note note) async { var db = await this.database; var result = await db.update(noteTable, note.toMap(), where: '$colId = ?', whereArgs: [note.id]); return result; } Future<int> updateNoteCompleted(Note note) async { var db = await this.database; var result = await db.update(noteTable, note.toMap(), where: '$colId = ?', whereArgs: [note.id]); return result; } // Update Operation: Update the config object and save it to database Future<int> updateConfig(Config conf) async { var db = await this.database; var result = await db.update(configTable, conf.toMap(), where: 'id = 1'); return result; } Future<int> updateConfigCompleted(Config conf) async { var db = await this.database; var result = await db.update(configTable, conf.toMap(), where: 'id = 1'); return result; } // Delete Operation: Delete a note object from database Future<int> deleteNote(int id) async { var db = await this.database; int result = await db.rawDelete('DELETE FROM $noteTable WHERE $colId = $id'); return result; } // Get number of note objects in database Future<int> getCount() async { Database db = await this.database; List<Map<String, dynamic>> x = await db.rawQuery('SELECT COUNT (*) from $noteTable'); int result = Sqflite.firstIntValue(x); return result; } // Get the 'Map List' [ List<Map> ] and convert it to 'note List' [ List<note> ] Future<List<Note>> getNoteList() async { var noteMapList = await getNoteMapList(); // Get 'Map List' from database int count = noteMapList.length; // Count the number of map entries in db table List<Note> noteList = List<Note>(); // For loop to create a 'note List' from a 'Map List' for (int i = 0; i < count; i++) { noteList.add(Note.fromMapObject(noteMapList[i])); } return noteList; } Future<Config> getConfig() async { Database db = await this.database; var configList = await db.query(configTable); // Get 'Map List' from database Config conf = Config.fromMapObject(configList[0]); return conf; } }
0
mirrored_repositories/0xVAULT/lib
mirrored_repositories/0xVAULT/lib/screens/pin_screen.dart
import 'package:flutter/material.dart'; import 'package:pinput/pin_put/pin_put.dart'; import 'package:bot_toast/bot_toast.dart'; class PinScreen extends StatefulWidget { final Function updateView; final String pin; PinScreen(this.updateView, this.pin); @override _PinScreenState createState() => _PinScreenState(); } class _PinScreenState extends State<PinScreen> { final TextEditingController _pinPutController = TextEditingController(); final FocusNode _pinPutFocusNode = FocusNode(); BoxDecoration get _pinPutDecoration { return BoxDecoration( border: Border.all(), borderRadius: BorderRadius.circular(15.0), ); } @override Widget build(BuildContext context) { return Scaffold( body: Builder( builder: (context) { return Center( child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( 'ENTER PIN CODE', style: TextStyle( fontFamily: 'Monda', fontSize: 18, ), ), Center( child: Container( padding: const EdgeInsets.all(10.0), child: PinPut( obscureText: '*', textStyle: TextStyle(color: Theme.of(context).primaryColorDark), fieldsAlignment: MainAxisAlignment.center, eachFieldMargin: EdgeInsets.only(left: 4, right: 4), fieldsCount: widget.pin.length, onSubmit: (String pin) => _validatePinCode(pin, context), focusNode: _pinPutFocusNode, controller: _pinPutController, submittedFieldDecoration: _pinPutDecoration.copyWith( borderRadius: BorderRadius.circular(10.0), border: Border.all( color: Theme.of(context).primaryColor, width: 1, ), ), selectedFieldDecoration: _pinPutDecoration.copyWith( borderRadius: BorderRadius.circular(10.0), border: Border.all( color: Theme.of(context).primaryColor, width: 1, ), ), followingFieldDecoration: _pinPutDecoration.copyWith( borderRadius: BorderRadius.circular(10.0), border: Border.all( color: Theme.of(context).primaryColor, width: 1, ), ), ), ), ), ], ), ), ); }, ), floatingActionButton: FloatingActionButton( elevation: 4, onPressed: null, tooltip: "Locked", child: Icon(Icons.lock), ), floatingActionButtonLocation: FloatingActionButtonLocation.endDocked, bottomNavigationBar: BottomAppBar( shape: CircularNotchedRectangle(), elevation: 4, notchMargin: 4.0, child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ IconButton( icon: Icon(Icons.arrow_back), onPressed: moveToLastScreen, ), Text(' Locked'), ], ), ), ); } void _validatePinCode(String pin, BuildContext context) { if (pin == widget.pin) { BotToast.showText( text: 'Unlocked', animationDuration: Duration(milliseconds: 200), textStyle: TextStyle( fontFamily: 'Monda', ), ); Navigator.of(context).popUntil((route) => route.isFirst); widget.updateView(true); } else { BotToast.showText( text: 'Incorrect Pin', animationDuration: Duration(milliseconds: 200), textStyle: TextStyle( fontFamily: 'Monda', ), ); } } void moveToLastScreen() { Navigator.pop(context, true); } }
0
mirrored_repositories/0xVAULT/lib
mirrored_repositories/0xVAULT/lib/screens/password_screen.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:bot_toast/bot_toast.dart'; import 'package:http/http.dart'; import 'package:crypto/crypto.dart'; import 'package:cryptography/cryptography.dart'; import './kawaii_vault.dart'; import '../models/config.dart'; import '../utils/database_helper.dart'; const Cipher aesGcm = AesGcm(); class PwdScreen extends StatefulWidget { @override _PwdScreenState createState() => _PwdScreenState(); } class _PwdScreenState extends State<PwdScreen> { DatabaseHelper databaseHelper = DatabaseHelper(); TextEditingController _passwordController = TextEditingController(); String _encryptedContent; String _uniqueValue; String uname = ''; String userId = ''; String _plaintext; Config _config; final cipher = aesGcm; @override void dispose() { // Clean up the controller when the widget is disposed. _passwordController.dispose(); super.dispose(); } @override void initState() { super.initState(); getConf(); } @override setState(fn) { if (mounted) { super.setState(fn); } } // because md5 is really *secure* String generateMd5(String input) { return md5.convert(utf8.encode(input)).toString(); } void getConf() async { Config configFuture = await databaseHelper.getConfig(); setState(() { this._config = configFuture; }); getGist(); } void getGist() async { if (_config != null) { String url = 'https://api.github.com/gists/${_config.gistId}'; Map<String, String> header = { 'Authorization': 'token ${_config.accessToken}' }; Response response = await get(url, headers: header); var jsonRes = json.decode(response.body); if (!response.body.toString().contains('Bad credentials')) { setState(() { _uniqueValue = jsonRes['files']['${_config.uniqued}']['content']; _encryptedContent = jsonRes['files']['${_config.vaultd}']['content']; uname = jsonRes['owner']['login']; userId = jsonRes['owner']['id'].toString(); }); } else { BotToast.showText( text: 'Bad credentials', animationDuration: Duration(milliseconds: 200), textStyle: TextStyle( fontFamily: 'Monda', ), ); } } } void decrypt(val1) { getGist(); final secretKey = SecretKey(utf8.encode(generateMd5(val1.text))); final nonce = Nonce(utf8.encode(_uniqueValue)); final decrypted = cipher.decrypt( base64.decode(_encryptedContent), secretKey: secretKey, nonce: nonce, ); decrypted.then((value) { setState(() { _plaintext = utf8.decode(value); }); Navigator.push( context, MaterialPageRoute( builder: (context) => PasswordManager( _config, _plaintext, generateMd5(val1.text), _encryptedContent, _uniqueValue, uname, userId, ), ), ); }).catchError( // error handling 10/10 as you can see (value) => BotToast.showText( text: 'Incorrect Password', animationDuration: Duration(milliseconds: 200), textStyle: TextStyle( fontFamily: 'Monda', ), ), ); } bool isPortrait() { return MediaQuery.of(context).orientation == Orientation.portrait; } @override Widget build(BuildContext context) { bool isPort = isPortrait(); return Scaffold( body: Padding( padding: const EdgeInsets.all(15.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ isPort ? Text( '(づ。◕‿‿◕。)づ', style: TextStyle( fontSize: 20, fontFamily: 'roboto', color: Theme.of(context).primaryColorDark, ), ) : Container(), isPort ? Text( 'Kawaii Vault', style: TextStyle( fontSize: 20, fontFamily: 'Monda', ), ) : Container(), isPort ? Container( padding: EdgeInsets.only(top: 30), ) : Container(), Container( height: 40, child: TextField( controller: _passwordController, maxLines: 1, obscureText: true, decoration: InputDecoration( labelText: 'Password', labelStyle: TextStyle(color: Theme.of(context).primaryColor), focusColor: Theme.of(context).primaryColor, counterText: '', contentPadding: EdgeInsets.only(left: 10, right: 10), focusedBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), ), style: TextStyle( fontFamily: 'Monda', fontSize: 16, color: Theme.of(context).primaryColorDark, ), textAlign: TextAlign.left, ), ), ], ), ), bottomNavigationBar: BottomAppBar( elevation: 4, notchMargin: 4.0, child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ FlatButton( onPressed: () => _passwordController.text = '', child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(5)), ), child: Text( 'Clear', style: TextStyle( fontSize: 15, fontFamily: 'Monda', ), ), ), ), FlatButton( onPressed: () { getConf(); }, child: Text( uname != '' ? 'online - $uname' : 'offline', style: TextStyle(color: Theme.of(context).accentColor), ), ), FlatButton( onPressed: () => decrypt(_passwordController), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(5)), ), child: Text( 'Decrypt', style: TextStyle( fontSize: 15, fontFamily: 'Monda', ), ), ), ), ], ), ), ); } }
0
mirrored_repositories/0xVAULT/lib
mirrored_repositories/0xVAULT/lib/screens/kawaii_vault.dart
import 'dart:convert'; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:cryptography/cryptography.dart'; import 'package:http/http.dart'; import 'package:bot_toast/bot_toast.dart'; import '../models/config.dart'; const Cipher aesGcm = AesGcm(); class PasswordManager extends StatefulWidget { final password; final String encryptedContent; final String uniqueValue; final String uname; final String userId; final String plaintext; final Config _config; PasswordManager(this._config, this.plaintext, this.password, this.encryptedContent, this.uniqueValue, this.uname, this.userId); @override _PasswordManagerState createState() => _PasswordManagerState( password, encryptedContent, uniqueValue, uname, userId, ); } class _PasswordManagerState extends State<PasswordManager> { TextEditingController vaultController = TextEditingController(); String encryptedContent; String uniqueValue; String uname; String userId; String key; bool loading = true; final cipher = aesGcm; final _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890'; Random _rnd = Random(); _PasswordManagerState(this.key, this.encryptedContent, this.uniqueValue, this.uname, this.userId); @override void dispose() { // Clean up the controller when the widget is disposed. vaultController.dispose(); super.dispose(); } @override void initState() { super.initState(); setState(() { loading = false; vaultController.text = widget.plaintext; }); } String getRandomString() { return String.fromCharCodes( Iterable.generate( 12, (_) => _chars.codeUnitAt(_rnd.nextInt(_chars.length)), ), ); } String genPassword() { return String.fromCharCodes( Iterable.generate( 15, (_) => '$_chars\$%^&*()#@!.;lk?_-' .codeUnitAt(_rnd.nextInt('$_chars\$%^&*()#@!.;lk?_-'.length)), ), ); } Future encrypt() async { final secretKey = SecretKey(utf8.encode(key)); final nonce = Nonce(utf8.encode(uniqueValue)); final encrypted = await cipher.encrypt( utf8.encode(vaultController.text), secretKey: secretKey, nonce: nonce, ); setState(() { encryptedContent = base64.encode(encrypted); }); } Future decrypt() async { final secretKey = SecretKey(utf8.encode(key)); final nonce = Nonce(utf8.encode(uniqueValue)); final decrypted = await cipher .decrypt( base64.decode(encryptedContent), secretKey: secretKey, nonce: nonce, ) .catchError( (_) => BotToast.showText( text: 'Incorrect Password', animationDuration: Duration(milliseconds: 200), textStyle: TextStyle( fontFamily: 'Monda', ), ), ); setState(() { vaultController.text = utf8.decode(decrypted); }); } Future getGist() async { String url = 'https://api.github.com/gists/${widget._config.gistId}'; Map<String, String> header = { 'Authorization': 'token ${widget._config.accessToken}' }; Response response = await get(url, headers: header); var jsonRes = json.decode(response.body); setState(() { uniqueValue = jsonRes['files']['${widget._config.uniqued}']['content']; encryptedContent = jsonRes['files']['${widget._config.vaultd}']['content']; uname = jsonRes['owner']['login']; userId = jsonRes['owner']['id'].toString(); }); } Future updateGist() async { String url = 'https://api.github.com/gists/${widget._config.gistId}'; Map<String, String> header = { 'Authorization': 'token ${widget._config.accessToken}' }; Map body = { 'files': { '${widget._config.uniqued}': {'content': '$uniqueValue'}, '${widget._config.vaultd}': {'content': '$encryptedContent'} } }; Response response = await patch(url, headers: header, body: json.encode(body)); var jsonRes = json.decode(response.body); setState(() { uniqueValue = jsonRes['files']['${widget._config.uniqued}']['content']; encryptedContent = jsonRes['files']['${widget._config.vaultd}']['content']; uname = jsonRes['owner']['login']; userId = jsonRes['owner']['id'].toString(); }); } void updateAll() async { setState(() { loading = true; uniqueValue = getRandomString(); }); await encrypt(); await updateGist(); await decrypt(); setState(() { loading = false; }); } @override Widget build(BuildContext context) { return Scaffold( body: Container( child: ListView( children: [ loading ? Container( padding: EdgeInsets.all(30), child: Text( 'Loading', style: TextStyle(fontSize: 20, fontFamily: 'Monda'), textAlign: TextAlign.center, ), ) : Container( padding: EdgeInsets.all(10), child: TextField( keyboardType: TextInputType.multiline, maxLines: null, controller: vaultController, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), hintText: 'Kawaii Vault (>"-")>', hintStyle: TextStyle( fontFamily: 'Monda', fontSize: 20, ), ), style: TextStyle( fontFamily: 'Monda', fontSize: 16, ), ), ), Container(padding: EdgeInsets.all(15)) ], ), ), floatingActionButton: FloatingActionButton( onPressed: updateAll, child: Icon(Icons.save), heroTag: 'save', ), bottomNavigationBar: BottomAppBar( shape: CircularNotchedRectangle(), elevation: 4, notchMargin: 4.0, child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ IconButton( icon: Icon(Icons.arrow_back), onPressed: () => Navigator.of(context).pop(), ), Text( ' In Vault ', style: TextStyle( fontFamily: 'Monda', ), ), IconButton( icon: Icon( Icons.code, ), onPressed: () { String text = vaultController.text; TextSelection textSelection = vaultController.selection; String newText = text.replaceRange( textSelection.start, textSelection.end, genPassword(), ); vaultController.text = newText; vaultController.selection = textSelection.copyWith( baseOffset: textSelection.start + 15, extentOffset: textSelection.start + 15, ); }, ) ]), ), floatingActionButtonLocation: FloatingActionButtonLocation.endDocked, ); } }
0
mirrored_repositories/0xVAULT/lib
mirrored_repositories/0xVAULT/lib/screens/swipe_screen.dart
import 'package:flutter/material.dart'; import './note_list.dart'; import './password_screen.dart'; class SwipeScreen extends StatefulWidget { @override _SwipeScreenState createState() => _SwipeScreenState(); } class _SwipeScreenState extends State<SwipeScreen> { PageController _controller = PageController( initialPage: 0, ); @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return PageView( controller: _controller, children: [ MyHomePage(title: 'I want to sleep and never wake up'), PwdScreen(), ], ); } }
0
mirrored_repositories/0xVAULT/lib
mirrored_repositories/0xVAULT/lib/screens/settings.dart
import 'package:flutter/material.dart'; import 'package:bot_toast/bot_toast.dart'; import '../models/config.dart'; import '../utils/database_helper.dart'; class Settings extends StatefulWidget { final Config _config; Settings(this._config); @override _SettingsState createState() => _SettingsState(_config); } class _SettingsState extends State<Settings> { bool validatePin = false; TextEditingController _pinController = TextEditingController(); TextEditingController _vaultdController = TextEditingController(); TextEditingController _uniquedController = TextEditingController(); TextEditingController _gistIdController = TextEditingController(); TextEditingController _accessTokenController = TextEditingController(); Config _config; _SettingsState(this._config); DatabaseHelper helper = DatabaseHelper(); @override void dispose() { // Clean up the controller when the widget is disposed. this._pinController.dispose(); this._vaultdController.dispose(); this._uniquedController.dispose(); this._gistIdController.dispose(); this._accessTokenController.dispose(); super.dispose(); } @override void initState() { super.initState(); this._pinController.text = _config.pin; this._vaultdController.text = _config.vaultd; this._uniquedController.text = _config.uniqued; this._gistIdController.text = _config.gistId; this._accessTokenController.text = _config.accessToken; } void _validatePin() { if(_pinController.text.length > 0){ setState(() { validatePin = false; }); _saveDialog(); } else{ setState(() { validatePin = true; }); } } void _saveDialog() { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text( 'Some Changes Happened', style: TextStyle(fontWeight: FontWeight.w600), ), content: Text( 'Do you want to save changes?', style: TextStyle(fontFamily: 'Monda', fontWeight: FontWeight.w500), ), actions: [ FlatButton( onPressed: () => Navigator.pop(context), child: Text('No')), FlatButton( onPressed: () { BotToast.showText( text: 'Saved', animationDuration: Duration(milliseconds: 200), textStyle: TextStyle( fontFamily: 'Monda', ), ); Navigator.pop(context, true); _save(); }, child: Text('Yes')), ], ); }); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { moveToLastScreen(); return false; }, child: Scaffold( body: GestureDetector( onTap: () { FocusScope.of(context).requestFocus(new FocusNode()); }, child: ListView( children: [ Container( height: validatePin?68:40, margin: EdgeInsets.only(top: 30, left: 20, right: 20, bottom: 10), child: TextField( controller: _pinController, keyboardType: TextInputType.number, maxLength: 6, maxLines: 1, obscureText: true, decoration: InputDecoration( labelText: 'Pin Code', labelStyle: TextStyle( color: Theme.of(context).primaryColor, ), focusColor: Theme.of(context).primaryColor, counterText: '', contentPadding: EdgeInsets.only(left: 10, right: 10), focusedBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), errorText: validatePin ? 'Can\'t be empty' : null, errorStyle: TextStyle(color: Theme.of(context).accentColor), errorBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), border: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), ), style: TextStyle( fontFamily: 'Monda', fontSize: 16, color: Theme.of(context).primaryColorDark, ), textAlign: TextAlign.left, ), ), Container( height: 40, margin: EdgeInsets.only(top: 30, left: 20, right: 20, bottom: 10), child: TextField( controller: _vaultdController, maxLines: 1, decoration: InputDecoration( labelText: 'Vaultd Filename', labelStyle: TextStyle(color: Theme.of(context).primaryColor), focusColor: Theme.of(context).primaryColor, counterText: '', contentPadding: EdgeInsets.only(left: 10, right: 10), focusedBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), ), style: TextStyle( fontFamily: 'Monda', fontSize: 16, ), textAlign: TextAlign.left, ), ), Container( height: 40, margin: EdgeInsets.only(top: 30, left: 20, right: 20, bottom: 10), child: TextField( controller: _uniquedController, maxLines: 1, decoration: InputDecoration( labelText: 'Unique Filename', labelStyle: TextStyle(color: Theme.of(context).primaryColor), focusColor: Theme.of(context).primaryColor, counterText: '', contentPadding: EdgeInsets.only(left: 10, right: 10), focusedBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), ), style: TextStyle( fontFamily: 'Monda', fontSize: 16, ), textAlign: TextAlign.left, ), ), Container( height: 40, margin: EdgeInsets.only( top: 30, left: 20, right: 20, bottom: 10, ), child: TextField( controller: _gistIdController, maxLines: 1, decoration: InputDecoration( labelText: 'Gist ID', labelStyle: TextStyle(color: Theme.of(context).primaryColor), focusColor: Theme.of(context).primaryColor, counterText: '', contentPadding: EdgeInsets.only(left: 10, right: 10), focusedBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), ), style: TextStyle( fontFamily: 'Monda', fontSize: 16, color: Theme.of(context).primaryColorDark, ), textAlign: TextAlign.left, ), ), Container( height: 40, margin: EdgeInsets.only( top: 30, left: 20, right: 20, bottom: 10, ), child: TextField( controller: _accessTokenController, maxLines: 1, decoration: InputDecoration( labelText: 'Gist Access Token', labelStyle: TextStyle(color: Theme.of(context).primaryColor), focusColor: Theme.of(context).primaryColor, counterText: '', contentPadding: EdgeInsets.only(left: 10, right: 10), focusedBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), ), style: TextStyle( fontFamily: 'Monda', fontSize: 16, color: Theme.of(context).primaryColorDark, ), textAlign: TextAlign.left, ), ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: () => _validatePin(), tooltip: 'Save', child: Icon(Icons.save), ), floatingActionButtonLocation: FloatingActionButtonLocation.endDocked, bottomNavigationBar: BottomAppBar( shape: CircularNotchedRectangle(), elevation: 4, notchMargin: 4.0, child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ IconButton( icon: Icon(Icons.arrow_back), onPressed: moveToLastScreen, ), Text(' Settings'), ], ), ), ), ); } void moveToLastScreen() { Navigator.pop(context, true); } // Save data to database void _save() async { await helper.updateConfig( Config.withId( 1, _gistIdController.text, _accessTokenController.text, _vaultdController.text, _uniquedController.text, _pinController.text, ), ); } }
0
mirrored_repositories/0xVAULT/lib
mirrored_repositories/0xVAULT/lib/screens/note_detail.dart
import 'package:flutter/material.dart'; import 'package:bot_toast/bot_toast.dart'; import '../models/note.dart'; import '../utils/database_helper.dart'; class DetailNote extends StatefulWidget { final Note note; final String title; DetailNote(this.note, this.title); @override _DetailNoteState createState() => _DetailNoteState(this.note); } class _DetailNoteState extends State<DetailNote> { TextEditingController titleController; TextEditingController bodyController; bool validateTitle = false; bool validateBody = false; String modifiedTime; String createdTime; int id; bool privateCheck; Note note; _DetailNoteState(this.note); DatabaseHelper helper = DatabaseHelper(); @override void dispose() { // Clean up the controller when the widget is disposed. titleController.dispose(); bodyController.dispose(); super.dispose(); } @override void initState() { super.initState(); titleController = TextEditingController( text: note.title, ); bodyController = TextEditingController( text: note.text, ); modifiedTime = note.modified; createdTime = note.created; id = note.id; privateCheck = note.private; } String appTitleDecider() { if (note.id == null) { return 'New Note'; } else { return 'Editing Note'; } } List<Widget> indexIsNull() { if (note.id == null) { return [ Column( children: [ SizedBox( child: null, height: 10, ), SizedBox( height: 20, child: Checkbox( value: privateCheck, //checkedValue activeColor: Theme.of(context).primaryColorDark, onChanged: (newValue) { setState(() { privateCheck = newValue; }); }, ), ), Text( 'SECRET', style: TextStyle( fontFamily: 'Monda', fontSize: 13, ), textAlign: TextAlign.center, ), ], ), ]; } else { return [ Column( children: [ SizedBox( child: null, height: 10, ), SizedBox( height: 20, child: Checkbox( activeColor: Theme.of(context).primaryColorDark, value: privateCheck, //checkedValue onChanged: (newValue) { setState(() { privateCheck = newValue; }); }, ), ), Text( 'SECRET', style: TextStyle( fontFamily: 'Monda', fontSize: 13, ), textAlign: TextAlign.center, ), ], ), Text( timeStuff(), style: TextStyle( fontFamily: 'Monda', fontSize: 13, ), textAlign: TextAlign.start, ), ]; } } String timeStuff() { String lol = ''; if (createdTime != null && createdTime != '') lol += 'Created: ${createdTime.substring(0, 16)} \n'; if (modifiedTime != null && modifiedTime != '') lol += 'Modified: ${modifiedTime.substring(0, 16)}'; return lol; } void _deleteDialog() { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text( 'Note Deletion', style: TextStyle(fontWeight: FontWeight.w600), ), content: Text( 'Do you want to delete this note?', style: TextStyle(fontFamily: 'Monda', fontWeight: FontWeight.w500), ), actions: [ FlatButton( onPressed: () => Navigator.pop(context), child: Text('No')), FlatButton( onPressed: () { BotToast.showText( text: 'Deleted', animationDuration: Duration(milliseconds: 200), textStyle: TextStyle( fontFamily: 'Monda', ), ); Navigator.pop(context, true); if (note.id != null) _delete(); }, child: Text('Yes')), ], ); }); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { moveToLastScreen(); return false; }, child: Scaffold( bottomNavigationBar: BottomAppBar( shape: CircularNotchedRectangle(), elevation: 4, notchMargin: 4.0, child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ IconButton( icon: Icon(Icons.arrow_back), onPressed: () => moveToLastScreen(), ), Text( ' ${appTitleDecider()} ', style: TextStyle( fontFamily: 'Monda', ), ), IconButton( icon: Icon( Icons.delete_outline, ), onPressed: () { _deleteDialog(); }, ) ]), ), floatingActionButtonLocation: FloatingActionButtonLocation.endDocked, body: GestureDetector( onTap: () { FocusScope.of(context).requestFocus(new FocusNode()); }, child: ListView( children: [ Container( height: validateTitle?68:40, margin: EdgeInsets.only( top: 30, left: 20, right: 20, bottom: 10, ), padding: EdgeInsets.all(0), child: TextField( controller: titleController, maxLength: 15, maxLines: 1, decoration: InputDecoration( labelText: 'Title', labelStyle: TextStyle( color: Theme.of(context).primaryColor, ), focusColor: Theme.of(context).primaryColor, errorText: validateTitle ? 'Can\'t be empty' : null, errorStyle: TextStyle(color: Theme.of(context).accentColor), errorBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), counterText: '', border: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), contentPadding: EdgeInsets.all(10), focusedBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), ), style: TextStyle( fontFamily: 'Monda', fontSize: 18, color: Theme.of(context).primaryColorDark, ), textAlign: TextAlign.left, ), ), Container( margin: EdgeInsets.only(left: 14, right: 14), child: TextField( keyboardType: TextInputType.multiline, maxLines: null, controller: bodyController, decoration: InputDecoration( enabledBorder: UnderlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), border: UnderlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), focusedErrorBorder: UnderlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), errorBorder: UnderlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).primaryColor, ), ), errorStyle: TextStyle(color: Theme.of(context).accentColor), hintText: 'Note', hintStyle: TextStyle( fontFamily: 'Monda', fontSize: 16, ), errorText: validateBody ? 'Can\'t be empty' : null, ), style: TextStyle( fontFamily: 'Monda', fontSize: 16, ), ), ), Container( margin: EdgeInsets.only( left: 15, right: 15, top: 10, bottom: 60, ), child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: indexIsNull(), ), ), ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: () { if (titleController.text.trim().isEmpty) { setState(() { validateTitle = true; }); } else if (bodyController.text.trim().isEmpty) { setState(() { validateBody = true; }); } else { setState(() { validateTitle = false; validateBody = false; }); note.title = titleController.text; note.text = bodyController.text; note.created = createdTime; note.modified = note.modified; note.private = privateCheck; String now = DateTime.now().toString(); if (note.id == null) { setState(() { createdTime = now; }); note.created = now; } else { setState(() { modifiedTime = now; }); note.modified = now; } _save(); BotToast.showText( text: 'Saved', animationDuration: Duration(milliseconds: 200), textStyle: TextStyle( fontFamily: 'Monda', ), ); } }, tooltip: 'Save', child: Icon(Icons.save), ), ), ); } void moveToLastScreen() { Navigator.pop(context, true); } // Save data to database void _save() async { if (note.id != null) { await helper.updateNote(note); } else { moveToLastScreen(); await helper.insertNote(note); } } void _delete() async { moveToLastScreen(); await helper.deleteNote(note.id); } }
0
mirrored_repositories/0xVAULT/lib
mirrored_repositories/0xVAULT/lib/screens/note_list.dart
import 'package:flutter/material.dart'; import 'package:sqflite/sqflite.dart'; import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; import '../screens/note_detail.dart'; import '../screens/pin_screen.dart'; import '../screens/settings.dart'; import '../widgets/note.dart'; import '../utils/database_helper.dart'; import '../models/note.dart'; import '../models/config.dart'; class MyHomePage extends StatefulWidget { final String title; MyHomePage({Key key, this.title}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { DatabaseHelper databaseHelper = DatabaseHelper(); List<Note> noteList; List<Note> filteredList = []; Config config; bool isUnlocked = false; int count = 0; int horizontalAxis = 2; TextEditingController searchController; bool showSearch = false; @override void dispose() { searchController.dispose(); super.dispose(); } @override void initState() { super.initState(); searchController = TextEditingController(); } void filterNotes(String val) { if (val != null && val != '') { List<Note> newList = List<Note>(); this.noteList.map((e) { // filtering notes that contains the following value if (e.text.toString().contains(val)) { newList.add(e); } }).toList(); setState(() { filteredList = newList; }); } else { setState(() { filteredList = noteList; }); } } // toggles the grid/list view List gridSee() { if (horizontalAxis == 4) { return [Icons.grid_off, 4]; } else { return [Icons.grid_on, 2]; } } Widget searchBar() { return showSearch ? Row( children: [ Expanded( flex: 8, child: Container( height: 40, margin: EdgeInsets.only(left: 5), padding: EdgeInsets.all(0), child: TextField( controller: searchController, onChanged: (String text) => filterNotes(text), maxLines: 1, decoration: InputDecoration( labelText: 'Search', counterText: '', contentPadding: EdgeInsets.only(left: 10, right: 10), focusedBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).accentColor, ), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide( width: 1.0, color: Theme.of(context).accentColor, ), ), ), style: TextStyle( fontFamily: 'Monda', fontSize: 16, ), textAlign: TextAlign.left, ), ), ), Expanded( flex: 1, child: IconButton( icon: Icon( gridSee()[0], size: 20, color: Theme.of(context).accentColor, ), onPressed: () { setState(() { if (horizontalAxis == 2) horizontalAxis = 4; else horizontalAxis = 2; }); }, ), ), ], ) : Container(height: 0.0); } // I have no idea why this function exists List _getTileSize(List _notes) { List val = <StaggeredTile>[StaggeredTile.fit(4), StaggeredTile.fit(4)]; for (int i = 0; i < _notes.length; i++) { val.add(StaggeredTile.fit(horizontalAxis)); } val.add(StaggeredTile.fit(4)); return val; } @override Widget build(BuildContext context) { if (noteList == null) { noteList = List<Note>(); updateListView(); } return Scaffold( body: Container( margin: EdgeInsets.only( top: showSearch ? 10.0 : 0.0, left: 5.0, right: 5.0, ), child: StaggeredGridView.count( primary: false, crossAxisCount: 4, children: <Widget>[ searchBar(), Container( padding: EdgeInsets.all(7), child: filteredList.length == 0 ? Container( padding: EdgeInsets.all(10), child: Center( child: Text('No Notes Found'), ), ) : null), // not the best practice!!! but gotta make use of the spread operator somehow ...(filteredList).map((note) { return InkWell( onTap: () { navigateToDetail(note, 'Edit Note'); }, child: NoteWidget( title: note.title, text: note.text, created: note.created, modified: note.modified, private: note.private, ), ); }), Container( padding: EdgeInsets.all(20), ), ], staggeredTiles: _getTileSize(filteredList), ), ), floatingActionButton: FloatingActionButton( elevation: 4, onPressed: () { navigateToDetail(Note('', '', '', '', false), 'Add Note'); }, tooltip: 'New Note', child: Icon(Icons.add), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, bottomNavigationBar: BottomAppBar( shape: CircularNotchedRectangle(), elevation: 4, notchMargin: 4.0, child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ IconButton( icon: Icon(Icons.settings), onPressed: navigateToSettings, ), IconButton( icon: Icon(Icons.search), onPressed: () { setState(() { showSearch ? showSearch = false : showSearch = true; }); }), ], ), ), ); } // don't judge me for whats below... i'm lazy void navigateToSettings() async { bool result = await Navigator.push( context, MaterialPageRoute( builder: (context) => PinScreen(secretFunc, config.pin), ), ); if (isUnlocked) { result = await Navigator.push( context, MaterialPageRoute( builder: (context) => Settings(config), ), ); isUnlocked = false; } if (result == true) { updateListView(); } } void navigateToDetail(Note noteVal, String title) async { bool result = await Navigator.push( context, MaterialPageRoute( builder: (context) => noteVal.private ? PinScreen(secretFunc, config.pin) : DetailNote(noteVal, title), ), ); if (isUnlocked) { result = await Navigator.push( context, MaterialPageRoute( builder: (context) => DetailNote(noteVal, title), ), ); isUnlocked = false; } if (result == true) { updateListView(); } } void secretFunc(bool val) { isUnlocked = val; } void updateListView() { final Future<Database> dbFuture = databaseHelper.initializeDatabase(); dbFuture.then((database) { Future<List<Note>> noteListFuture = databaseHelper.getNoteList(); noteListFuture.then((noteList) { // confusion 100 setState(() { this.noteList = noteList; this.count = noteList.length; this.filteredList = this.noteList; }); }); Future<Config> configFuture = databaseHelper.getConfig(); configFuture.then((value) { setState(() { this.config = value; }); }); }); } }
0
mirrored_repositories/scrolling_parallax_effect
mirrored_repositories/scrolling_parallax_effect/lib/parallax_flow_delegate.dart
import 'package:flutter/material.dart'; class ParallaxFlowDelegate extends FlowDelegate { ParallaxFlowDelegate({ required this.scrollable, required this.listItemContext, required this.backgroundImageKey, }) : super(repaint: scrollable.position); final ScrollableState scrollable; final BuildContext listItemContext; final GlobalKey backgroundImageKey; @override BoxConstraints getConstraintsForChild(int i, BoxConstraints constraints) { return BoxConstraints.tightFor(width: constraints.maxWidth,); } @override void paintChildren(FlowPaintingContext context) { final scrollableBox = scrollable.context.findRenderObject() as RenderBox; final listItemBox = listItemContext.findRenderObject() as RenderBox; final listItemOffset = listItemBox.localToGlobal(listItemBox.size.centerLeft(Offset.zero), ancestor: scrollableBox); final viewportDimension = scrollable.position.viewportDimension; final scrollFraction = (listItemOffset.dy / viewportDimension).clamp(0.0, 1.0); final verticalAlignment = Alignment(0.0, scrollFraction * 2 - 1); final backgroundSize = (backgroundImageKey.currentContext!.findRenderObject() as RenderBox).size; final listItemSize = context.size; final childRect = verticalAlignment.inscribe(backgroundSize, Offset.zero & listItemSize); context.paintChild( 0, transform: Transform.translate(offset: Offset(0.0, childRect.top)).transform, ); } @override bool shouldRepaint(ParallaxFlowDelegate oldDelegate) { return scrollable != oldDelegate.scrollable || listItemContext != oldDelegate.listItemContext || backgroundImageKey != oldDelegate.backgroundImageKey; } }
0
mirrored_repositories/scrolling_parallax_effect
mirrored_repositories/scrolling_parallax_effect/lib/scrolling_parallax_effect.dart
import 'package:flutter/material.dart'; import 'list_item.dart'; class ScrollingParallaxEffect extends StatelessWidget { const ScrollingParallaxEffect({super.key,}); @override Widget build(BuildContext context) { return SafeArea( child: ListView.builder( itemCount: 31, physics: const BouncingScrollPhysics(), itemBuilder: (context, index) => ListItem( assetImagePath: 'assets/$index.jpg', ), ), ); } }
0
mirrored_repositories/scrolling_parallax_effect
mirrored_repositories/scrolling_parallax_effect/lib/main.dart
import 'package:flutter/material.dart'; import 'package:scrolling_parallax_effect/scrolling_parallax_effect.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( backgroundColor: Color(0xFF12202F), body: Center( child: ScrollingParallaxEffect(), ), ), ); } }
0
mirrored_repositories/scrolling_parallax_effect
mirrored_repositories/scrolling_parallax_effect/lib/list_item.dart
import 'package:flutter/material.dart'; import 'package:scrolling_parallax_effect/parallax_flow_delegate.dart'; class ListItem extends StatelessWidget { ListItem({super.key, required this.assetImagePath,}); final String assetImagePath; final GlobalKey _backgroundImageKey = GlobalKey(); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), child: AspectRatio( aspectRatio: 16 / 9, child: ClipRRect( borderRadius: BorderRadius.circular(16), child: Stack( children: [ _buildParallaxBackground(context), ], ), ), ), ); } Widget _buildParallaxBackground(BuildContext context) { return Flow( delegate: ParallaxFlowDelegate( scrollable: Scrollable.of(context)!, listItemContext: context, backgroundImageKey: _backgroundImageKey, ), children: [ Image.asset( assetImagePath, key: _backgroundImageKey, fit: BoxFit.cover, ), ], ); } }
0
mirrored_repositories/scrolling_parallax_effect
mirrored_repositories/scrolling_parallax_effect/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:scrolling_parallax_effect/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/flutter_location
mirrored_repositories/flutter_location/lib/main.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:location/location.dart'; void main() => runApp(new MyApp()); class MyApp extends StatefulWidget { // This widget is the root of your application. @override State<StatefulWidget> createState() => MyAppState(); } class MyAppState extends State<MyApp> { Map<String, double> currentLocation = new Map(); StreamSubscription<Map<String, double>> locationSubscription; Location location = new Location(); String error; @override void initState() { // TODO: implement initState super.initState(); currentLocation['latitude'] = 0.0; currentLocation['longitude'] = 0.0; initPlatformState(); locationSubscription = location.onLocationChanged().listen((Map<String, double> result) { setState(() { currentLocation = result; }); }); } @override Widget build(BuildContext context) { return new MaterialApp( home: new Scaffold( appBar: AppBar( title: Text('Flutter location'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Lat/Lng: ${currentLocation['latitude']}/${currentLocation['longitude']}', style: TextStyle(fontSize: 20, color: Colors.deepPurple), ) ], ), ), ), ); } void initPlatformState() async { Map<String, double> myLocation; try { myLocation = await location.getLocation(); error = ""; } on PlatformException catch (e) { if (e.code == "PERMISION_DENIED") error = "Permision denied"; else if (e.code == "PERMISION_DENIED_NEVER_ASK") error = "permision denied - please ask user to enable it from the app settings"; myLocation['latitude'] = 0.0; myLocation['longitude'] = 0.0; } setState(() { currentLocation = myLocation; }); } }
0
mirrored_repositories/flutter_location
mirrored_repositories/flutter_location/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:app_location/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/Screenshot-Manager-App
mirrored_repositories/Screenshot-Manager-App/lib/utils.dart
import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter/material.dart'; final imagePostUrl = 'https://screenshot-manager.herokuapp.com/api/test'; final primaryColor = Color(0xFF34495E); final accentColor = Color(0xFF798EA5); final headingTextStyle = TextStyle( color: primaryColor, fontSize: 25, fontWeight: FontWeight.bold, ); class Utility { static String base64String(Uint8List data) { return base64Encode(data); } static Image imageFromBase64String(String base64String) { return Image.memory( base64Decode(base64String), fit: BoxFit.fitWidth, ); } }
0
mirrored_repositories/Screenshot-Manager-App
mirrored_repositories/Screenshot-Manager-App/lib/main.dart
import 'package:flutter/material.dart'; import './screens/home_screen.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'SkreenShot', theme: ThemeData( primaryColor: Color(0xFF34495E), accentColor: Color(0xFF798EA5), canvasColor: Color(0xFFF6F6F6), pageTransitionsTheme: PageTransitionsTheme(builders: { TargetPlatform.android: ZoomPageTransitionsBuilder(), }), ), home: MyHomeScreen(), ); } }
0
mirrored_repositories/Screenshot-Manager-App/lib
mirrored_repositories/Screenshot-Manager-App/lib/widgets/project_widget.dart
import 'package:flutter/material.dart'; import '../models/project.dart'; import '../screens/project_screen.dart'; import '../utils.dart'; class MyProjectWidget extends StatelessWidget { final Project project; MyProjectWidget({this.project}); @override Widget build(BuildContext context) { return Container( height: 100, margin: EdgeInsets.symmetric( vertical: MediaQuery.of(context).size.height * 0.02, horizontal: MediaQuery.of(context).size.width * 0.06, ), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), boxShadow: [ BoxShadow( color: Color(0x25aaa9a9), blurRadius: 10, ) ], ), child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Material( child: InkWell( onTap: () => Navigator.push( context, MaterialPageRoute( builder: (context) => ProjectScreen(project), ), ), child: Row( children: <Widget>[ Flexible( flex: 3, child: Container( // height: 100, padding: EdgeInsets.all(10), child: Align( alignment: Alignment.bottomLeft, child: Text( project.title, softWrap: true, style: TextStyle( fontSize: 19, fontWeight: FontWeight.bold, color: Colors.white), ), ), color: Theme.of(context).primaryColor, ), ), Flexible( flex: 1, child: Container( padding: EdgeInsets.all(5), // height: 100, color: Colors.white, child: Align( alignment: Alignment.center, child: CircleAvatar( backgroundColor: primaryColor, foregroundColor: Colors.white, child: Icon(Icons.navigate_next), ), ), ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/Screenshot-Manager-App/lib
mirrored_repositories/Screenshot-Manager-App/lib/models/local_img.dart
import 'package:flutter/foundation.dart'; import './tag.dart'; class Photo { int id; int projectId; String title; List<Tag> tags; Photo({ this.id, @required this.title, @required this.projectId, // this.tags, }); Map<String, dynamic> toMap() { var map = <String, dynamic>{ "imageid": id, "projectId": projectId, "imagetitle": title, // "tags":tags, }; return map; } Photo.fromMap(Map<String, dynamic> map) { id = map['imageid']; projectId = map['projectId']; title = map['imagetitle']; } }
0
mirrored_repositories/Screenshot-Manager-App/lib
mirrored_repositories/Screenshot-Manager-App/lib/models/tag.dart
class Tag { int tagId; String tagName; String comment; int photoId; int projectId; Coord startCoordinate; Coord endCoordinate; Tag({ this.tagId, this.projectId, this.photoId, this.tagName, this.startCoordinate, this.endCoordinate, this.comment, }); Map<String, dynamic> toMap() { var map = { 'tagId': tagId, 'imageId': photoId, 'tagName': tagName, 'tag_projectId':projectId, 'start_coord': startCoordinate.toString(), 'end_coord': endCoordinate.toString(), 'comment': comment, }; return map; } Tag.fromMap(Map map) { tagId = map['tagId']; projectId = map['tag_projectId']; photoId = map['imageId']; tagName = map['tagName']; startCoordinate = Coord.fromString(map['start_coord']); endCoordinate = Coord.fromString(map['end_coord']); comment = map['comment']; } } class Coord { int x; int y; Coord(this.x, this.y); @override String toString() { String coord = "$x,$y"; return coord; } Coord.fromString(String data){ final coordinates = data.split(","); x = int.parse(coordinates.removeAt(0)); y = int.parse(coordinates.removeAt(coordinates.length-1)); } }
0
mirrored_repositories/Screenshot-Manager-App/lib
mirrored_repositories/Screenshot-Manager-App/lib/models/project.dart
import 'package:screenshot_manager/models/local_img.dart'; class Project { int id; String title; List<Photo> photos; Project({this.id, this.title, this.photos}); Map<String, dynamic> toMap() { var map = <String, dynamic>{ "id": id, "title": title, // "photos": photos.map((photo) => photo.toMap()).toList(), }; return map; } Project.fromMap(Map<String, dynamic> map){ id = map['id']; title = map['title']; // photos = map['photos'] } }
0
mirrored_repositories/Screenshot-Manager-App/lib
mirrored_repositories/Screenshot-Manager-App/lib/services/db_helper.dart
import 'dart:async'; import 'dart:io' as io; import 'package:path/path.dart'; import 'package:path_provider/path_provider.dart'; import 'package:sqflite/sqflite.dart'; import '../models/local_img.dart'; import '../models/project.dart'; import '../models/tag.dart'; class DBHelper { static Database _db; static const String PROJECT_ID = 'id'; static const String PROJECT_TITLE = 'title'; static const String PROJECT_TABLE = 'projects'; static const String IMAGE_TABLE = 'photos'; static const String IMAGE_ID = 'imageid'; static const String IMAGE_PROJECT_ID = 'projectId'; static const String IMAGE_TITLE = 'imagetitle'; static const String TAG_TABLE = 'tags'; static const String TAG_ID = 'tagId'; static const String TAG_IMAGE_ID = 'imageId'; static const String TAG_PROJECT_ID = 'tag_projectId'; static const String TAG_NAME = 'tagName'; static const String TAG_COMMENT = 'comment'; static const String TAG_START_COORD = 'start_coord'; static const String TAG_END_COORD = 'end_coord'; static const String DB_NAME = 'projects.db'; Future<Database> get db async { if (_db != null) { return _db; } _db = await initDB(); return _db; } initDB() async { io.Directory docDirectory = await getApplicationDocumentsDirectory(); String path = join(docDirectory.path + DB_NAME); var db = await openDatabase(path, version: 1, onCreate: _onCreate); return db; } // static Future _onConfigure(Database db) async { // await db.execute('PRAGMA foreign_keys = ON'); // } _onCreate(Database db, int version) async { await db.execute( 'CREATE TABLE $PROJECT_TABLE ($PROJECT_ID INTEGER PRIMARY KEY AUTOINCREMENT, $PROJECT_TITLE TEXT)', ); await db.execute( 'CREATE TABLE $IMAGE_TABLE ($IMAGE_ID INTEGER PRIMARY KEY AUTOINCREMENT, $IMAGE_TITLE TEXT, $IMAGE_PROJECT_ID INTEGER)', ); await db.execute( 'CREATE TABLE $TAG_TABLE ($TAG_ID INTEGER PRIMARY KEY AUTOINCREMENT,$TAG_IMAGE_ID INTEGER, $TAG_PROJECT_ID INTEGER , $TAG_NAME TEXT ,$TAG_COMMENT TEXT, $TAG_START_COORD TEXT, $TAG_END_COORD TEXT)', ); } Future<Project> saveProject(Project project) async { var dbClient = await db; project.id = await dbClient.insert(PROJECT_TABLE, project.toMap()); return project; } Future<Photo> savePhoto(Photo photo) async { var dbClient = await db; photo.id = await dbClient.insert( IMAGE_TABLE, photo.toMap(), ); return photo; } Future<Tag> saveTag(Tag tag) async { var dbClient = await db; tag.tagId = await dbClient.insert(TAG_TABLE, tag.toMap()); return tag; } Future<List<Project>> getProjects() async { var dbClient = await db; List<Map<String, dynamic>> projectMaps = await dbClient .query(PROJECT_TABLE, columns: [PROJECT_ID, PROJECT_TITLE]); List<Project> projects = projectMaps .map( (project) => Project.fromMap(project), ) .toList(); return projects; } Future<List<Photo>> getPhotos(int projectId) async { var dbClient = await db; List<Map<String, dynamic>> photoMaps = await dbClient.query(IMAGE_TABLE, columns: [IMAGE_ID, IMAGE_TITLE], where: '$IMAGE_PROJECT_ID == $projectId'); List<Photo> photos = photoMaps.map((photoMap) { return Photo.fromMap(photoMap); }).toList(); return photos; } Future<List<Tag>> getTags(int photoId) async { var dbClient = await db; List<Map> tagMaps = await dbClient.query( TAG_TABLE, columns: [ TAG_ID, TAG_NAME, TAG_IMAGE_ID, TAG_START_COORD, TAG_END_COORD, TAG_COMMENT, ], where: '$TAG_IMAGE_ID == $photoId', ); List<Tag> tags = tagMaps.map((tag) { return Tag.fromMap(tag); }).toList(); return tags; } Future<int> updateTagComment(int tagId, String comment) async { var dbClient = await db; int i = await dbClient.update( TAG_TABLE, {TAG_COMMENT: comment}, where: '$TAG_ID == $tagId', ); print('comment updated: $i'); return i; } Future<int> deleteProject(int id) async { var dbClient = await db; int deletedTags = await dbClient.delete(TAG_TABLE, where: '$TAG_PROJECT_ID == $id'); int deletedPhotos = await dbClient.delete(IMAGE_TABLE, where: '$IMAGE_PROJECT_ID == $id '); int deletedProject = await dbClient.delete(PROJECT_TABLE, where: '$PROJECT_ID == $id'); print("project with id = $id removed, deleted $deletedPhotos photos and $deletedTags tags"); return deletedProject; } Future<int> deletePhoto(int photoID) async{ var dbClient = await db; int deletedTags = await dbClient.delete(TAG_TABLE, where: '$TAG_IMAGE_ID == $photoID'); int photoDeleted = await dbClient.delete(IMAGE_TABLE, where: '$IMAGE_ID == $photoID'); print('image with id $photoID deleted, $deletedTags tags deleted'); return photoDeleted; } Future close() async { var dbClient = await db; dbClient.close(); } }
0
mirrored_repositories/Screenshot-Manager-App/lib
mirrored_repositories/Screenshot-Manager-App/lib/screens/home_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../models/project.dart'; import '../services/db_helper.dart'; import '../utils.dart'; import '../widgets/project_widget.dart'; class MyHomeScreen extends StatefulWidget { @override _MyHomeScreenState createState() => _MyHomeScreenState(); } class _MyHomeScreenState extends State<MyHomeScreen> { List<Project> myProjects; Future<List<Project>> storedProjects; DBHelper dbHelper; @override void initState() { myProjects = []; dbHelper = DBHelper(); SystemChrome.setSystemUIOverlayStyle( SystemUiOverlayStyle( statusBarColor: primaryColor, statusBarIconBrightness: Brightness.light, statusBarBrightness: Brightness.light, ), ); super.initState(); } TextEditingController titlecontroller = TextEditingController(); _onSubmit() async { final title = titlecontroller.text; if (title.isEmpty) { return; } Project p = Project(title: title); p = await dbHelper.saveProject(p); print("project saved with id = ${p.id}"); } // refreshProjects() { // dbHelper.getProjects().then((projectList) { // setState(() { // myProjects.clear(); // projectList.addAll(projectList); // }); // }); // } addProject() { showModalBottomSheet( isScrollControlled: true, context: context, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)), builder: (ctx) { return StatefulBuilder( builder: (context, sheetSetState) { return SingleChildScrollView( child: Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom), child: Container( padding: EdgeInsets.all(10), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox( height: 20, ), Text( 'Create New Project', style: headingTextStyle.copyWith(fontSize: 18), ), SizedBox( height: 20, ), Row( children: <Widget>[ Container( width: MediaQuery.of(context).size.width * 0.65, child: ClipRRect( borderRadius: BorderRadius.circular(5), child: TextField( controller: titlecontroller, maxLength: 100, onSubmitted: (string) => _onSubmit, decoration: InputDecoration( hintText: 'Name', fillColor: Colors.grey[200], border: InputBorder.none, filled: true, ), ), ), ), Spacer(), Column( children: <Widget>[ Container( height: 45, width: MediaQuery.of(context).size.width * 0.25, child: RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5)), child: Text('Done'), color: primaryColor, textColor: Colors.white, onPressed: () { _onSubmit(); Navigator.of(context).maybePop(); titlecontroller.clear(); }, ), ), SizedBox(height: 20,), ], ), ], ), SizedBox( height: 20, ), SizedBox( height: 20, ), ], ), ), ), ); }, ); }, ); } projectView() { return Padding( padding: const EdgeInsets.all(12.0), child: GridView.count( crossAxisCount: 2, childAspectRatio: 3, mainAxisSpacing: 5, crossAxisSpacing: 5, children: myProjects.map((project) { return Text(project.title); }).toList(), ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( elevation: 0, // backgroundColor: Theme.of(context).canvasColor, title: Text('Screenshot Manager'), actions: <Widget>[ Tooltip( message: 'Add Project', decoration: BoxDecoration( color: Colors.black.withOpacity(0.7), borderRadius: BorderRadius.circular(5), ), child: IconButton( icon: Icon(Icons.add), onPressed: addProject, ), ) ], ), body: FutureBuilder( future: dbHelper.getProjects(), builder: (ctx, snapshot) { if (!snapshot.hasData) { return Column( children: <Widget>[ Container( margin: EdgeInsets.symmetric( horizontal: MediaQuery.of(context).size.width * 0.05), padding: EdgeInsets.only(top: 20, bottom: 15), alignment: Alignment.centerLeft, child: Text( 'My Projects', style: headingTextStyle, ), ), SizedBox( height: MediaQuery.of(context).size.height * 0.38, ), Center( child: CircularProgressIndicator(), ), ], ); } myProjects = snapshot.data; if (myProjects.length == 0) { return Column( children: <Widget>[ Container( margin: EdgeInsets.symmetric( horizontal: MediaQuery.of(context).size.width * 0.05), padding: EdgeInsets.only(top: 20, bottom: 15), alignment: Alignment.centerLeft, child: Text( 'My Projects', style: headingTextStyle, ), ), SizedBox( height: MediaQuery.of(context).size.height * 0.38, ), Align( alignment: Alignment.center, child: Text( 'Tap \'+\' to add a new project', style: TextStyle(color: accentColor), ), ), ], ); } else { return Column( children: <Widget>[ Container( margin: EdgeInsets.symmetric( horizontal: MediaQuery.of(context).size.width * 0.05), padding: EdgeInsets.only(top: 20, bottom: 15), alignment: Alignment.centerLeft, child: Text( 'My Projects', style: headingTextStyle, ), ), Expanded( child: ListView.builder( itemCount: myProjects.length, itemBuilder: (ctx, index) { return Dismissible( key: Key(myProjects[index].id.toString()), background: Container( margin: EdgeInsets.symmetric(vertical: 17), padding: EdgeInsets.all(10), color: Colors.red, child: Align( alignment: Alignment.centerLeft, child: Icon(Icons.delete), ), ), secondaryBackground: Container( margin: EdgeInsets.symmetric(vertical: 17), padding: EdgeInsets.all(10), color: Colors.red, child: Align( alignment: Alignment.centerRight, child: Icon(Icons.delete), ), ), direction: DismissDirection.endToStart, onDismissed: (direction) { dbHelper .deleteProject(myProjects[index].id) .then((_) { myProjects.removeWhere((project) => project.id == myProjects[index].id); if (myProjects.length == 0) { setState(() { dbHelper.getProjects(); }); } }); }, child: MyProjectWidget( project: myProjects[index], ), ); }, ), ), ], ); } }, ), ); } }
0
mirrored_repositories/Screenshot-Manager-App/lib
mirrored_repositories/Screenshot-Manager-App/lib/screens/photo_detail.dart
import 'dart:io'; import 'dart:typed_data'; import 'package:esys_flutter_share/esys_flutter_share.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:path_provider/path_provider.dart'; import '../models/local_img.dart'; import '../models/tag.dart'; import '../services/db_helper.dart'; import '../utils.dart'; import 'dart:ui' as ui; import '../utils.dart'; class PhotoDetailScreen extends StatefulWidget { final Photo photo; PhotoDetailScreen(this.photo); @override _PhotoDetailScreenState createState() => _PhotoDetailScreenState(); } class _PhotoDetailScreenState extends State<PhotoDetailScreen> { static GlobalKey previewContainer = GlobalKey(); List<Tag> tagList; DBHelper dbHelper; @override void initState() { dbHelper = DBHelper(); super.initState(); } @override void dispose() { super.dispose(); } _takeScreenShot() async { try { RenderRepaintBoundary boundary = previewContainer.currentContext.findRenderObject(); ui.Image image = await boundary.toImage(); final directory = (await getExternalStorageDirectory()).path; ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png); Uint8List pngBytes = byteData.buffer.asUint8List(); // print(pngBytes); print("$directory"); // File imgFile = new File('$directory/screenshot.png'); // imgFile.writeAsBytes(pngBytes); String str = ""; for (int i = 0; i < tagList.length; i++) { str += '*${tagList[i].tagName} - ${i + 1}*\n${tagList[i].comment}\n\n'; } Share.file( "Screenshot comments", 'screenshot.png', pngBytes, 'image/png', text: str, ); } catch (e) { print(e.toString()); } } _onSaved(int tagId, String comment) { // print('$tagId: $comment'); dbHelper.updateTagComment(tagId, comment); } showTextBox(int tagId, String comment, String name, int number) { print('tag id is $tagId'); showDialog( context: context, // barrierDismissible: false, child: AlertDialog( actions: <Widget>[ FlatButton( child: Text( 'DISMISS', style: TextStyle( fontWeight: FontWeight.bold, color: primaryColor, ), ), onPressed: () => Navigator.maybePop(context), ), ], shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)), title: Text('Add/Edit Comment for $name ${number + 1}'), content: ClipRRect( borderRadius: BorderRadius.circular(5), child: Container( width: double.infinity, child: TextFormField( initialValue: comment, onChanged: (value) { _onSaved(tagId, value); }, minLines: 1, maxLines: 7, decoration: InputDecoration( border: InputBorder.none, filled: true, alignLabelWithHint: true, fillColor: Colors.grey[200], hintText: 'Comment', ), ), ), ), ), ); } @override Widget build(BuildContext context) { return RepaintBoundary( key: previewContainer, child: Scaffold( floatingActionButton: FloatingActionButton( backgroundColor: primaryColor, child: Icon(Icons.share), onPressed: _takeScreenShot, ), appBar: AppBar( title: Text('Add/Edit Annotation'), centerTitle: true, actions: <Widget>[ IconButton( icon: Icon(Icons.delete), onPressed: () { dbHelper.deletePhoto(widget.photo.id).then((value) { Navigator.of(context).pop(); Fluttertoast.showToast(msg: 'Photo removed'); }); }, ), ], ), body: FutureBuilder( future: dbHelper.getTags(widget.photo.id), builder: (ctx, snapshot) { if (!snapshot.hasData) { return Center( child: CircularProgressIndicator(), ); } tagList = snapshot.data; return SingleChildScrollView( child: Center( child: Column( children: [ SizedBox( height: 20, ), Container( margin: EdgeInsets.symmetric( horizontal: MediaQuery.of(context).size.width * 0.07), child: Wrap( children: <Widget>[ for (int i = 0; i < tagList.length; i++) Padding( padding: const EdgeInsets.symmetric(horizontal: 10.0), child: GestureDetector( onTap: () { showTextBox( tagList[i].tagId, tagList[i].comment, tagList[i].tagName, i, ); }, child: Chip( backgroundColor: primaryColor, label: Text( tagList[i].tagName + ' - ${i + 1}', style: TextStyle(color: Colors.white), ), ), ), ), ], ), ), SizedBox( height: 20, ), Container( width: MediaQuery.of(context).size.width * 0.75, child: Stack( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.circular(10), child: Utility.imageFromBase64String( widget.photo.title, ), ), for (int i = 0; i < tagList.length; i++) Positioned( top: double.parse( '${tagList[i].startCoordinate.y}') * 0.75, child: GestureDetector( onLongPress: () { print("hi"); Fluttertoast.showToast( msg: '${tagList[i].tagName} ${i + 1}'); }, onTap: () { showTextBox( tagList[i].tagId, tagList[i].comment, tagList[i].tagName, i, ); }, child: Container( decoration: BoxDecoration( color: primaryColor.withOpacity(0.3), borderRadius: BorderRadius.circular(5), ), child: Padding( padding: EdgeInsets.zero, child: FittedBox( fit: BoxFit.scaleDown, child: CircleAvatar( backgroundColor: primaryColor.withOpacity(0.5), child: Text( '${i + 1}', style: TextStyle( color: Colors.white, fontSize: 16), ), ), ), ), width: (double.parse( '${tagList[i].endCoordinate.x}') - double.parse( '${tagList[i].startCoordinate.x}')) * 0.75, height: (double.parse( '${tagList[i].endCoordinate.y}') - double.parse( '${tagList[i].startCoordinate.y}')) * 0.75, ), ), ), ], ), ), SizedBox( height: 30, ), ], ), ), ); }, ), ), ); } }
0
mirrored_repositories/Screenshot-Manager-App/lib
mirrored_repositories/Screenshot-Manager-App/lib/screens/project_screen.dart
import 'dart:convert'; import 'dart:io'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:image_picker/image_picker.dart'; import '../models/local_img.dart'; import '../models/project.dart'; import '../models/tag.dart'; import '../services/db_helper.dart'; import '../utils.dart'; import 'photo_detail.dart'; class ProjectScreen extends StatefulWidget { final Project project; ProjectScreen(this.project); @override _ProjectScreenState createState() => _ProjectScreenState(); } class _ProjectScreenState extends State<ProjectScreen> { List<Photo> myPhotos; Future<File> imageFile; Image image; DBHelper dbHelper; bool isLoading = false; @override void initState() { isLoading = false; dbHelper = DBHelper(); myPhotos = []; super.initState(); } @override // ignore: must_call_super void didChangeDependencies() { super.didChangeDependencies(); myPhotos.forEach((element) { precacheImage(MemoryImage(base64Decode(element.title)), context); }); } pickImageFromGallery() { final double deviceHeight = MediaQuery.of(context).size.height; final double deviceWidth = MediaQuery.of(context).size.width; ImagePicker.pickImage( source: ImageSource.gallery, imageQuality: 100, maxHeight: deviceHeight, maxWidth: deviceWidth, ).then((file) async { bool fileProvided = await file.exists(); if (fileProvided) { try { setState(() { isLoading = true; }); String filename = file.path.split("/").last; FormData formData = FormData.fromMap( { 'file': await MultipartFile.fromFile( file.path, filename: filename, ), }, ); Response response = await Dio().post( imagePostUrl, data: formData, onReceiveProgress: (recv, total) { print("recvd: $recv/$total"); }, onSendProgress: (sent, total) { print("sent: $sent/$total"); }, // options: Options(validateStatus: (statusCode) { // if(statusCode !=200){ // Fluttertoast.showToast(msg: "Some error has occured"); // return false; // } // return true; // }), ); print(response.statusCode); print(response.data); if (response.statusCode == 200) { List<Tag> tagList = []; String imgString = Utility.base64String(file.readAsBytesSync()); Map<String, dynamic> responseObject = response.data; responseObject.keys.toList().forEach((key) { final data = responseObject[key]; data.forEach((veryComplexMap) { String tagName = key; Tag tag = Tag( tagName: tagName, startCoordinate: Coord( veryComplexMap['start']['x'], veryComplexMap['start']['y'], ), endCoordinate: Coord( veryComplexMap['end']['x'], veryComplexMap['end']['y'], ), ); tagList.add(tag); }); }); print(tagList); Photo photo = Photo( title: imgString, projectId: widget.project.id, ); photo = await dbHelper.savePhoto(photo); print( "photo saved with id = ${photo.id} and project id = ${photo.projectId}"); tagList.forEach((tag) async { tag.photoId = photo.id; tag.projectId = widget.project.id; tag = await dbHelper.saveTag(tag); print( 'tag saved as ${tag.tagName} for photo ${tag.photoId} with start as ${tag.startCoordinate.toString()} and end as ${tag.endCoordinate.toString()}'); }); refreshPhotos(); } else { Fluttertoast.showToast( msg: "Some error occured while performing OCR. Please try again."); } } on DioError catch (e) { print(e.toString()); Fluttertoast.showToast( msg: "Some error occured while performing OCR. Please try again."); } setState(() { isLoading = false; }); } }); } refreshPhotos() { dbHelper.getPhotos(widget.project.id).then((imgArray) { setState(() { myPhotos.clear(); myPhotos.addAll(imgArray); }); }); } @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( backgroundColor: primaryColor.withOpacity(0.9), child: Icon(Icons.file_upload), tooltip: 'Upload screenshot', onPressed: pickImageFromGallery, ), appBar: AppBar( title: Text(widget.project.title), // centerTitle: true, ), body: FutureBuilder( future: dbHelper.getPhotos(widget.project.id), builder: (ctx, snapshot) { if (!snapshot.hasData) { return Center( child: CircularProgressIndicator(), ); } myPhotos = snapshot.data; myPhotos.sort((b, a) => a.id.compareTo(b.id)); if (myPhotos.length == 0) { return Center( child: (isLoading) ? CircularProgressIndicator() : Container( margin: const EdgeInsets.all(60.0), child: Text( 'No images found\nPress upload button to start adding images', style: TextStyle(color: accentColor), textAlign: TextAlign.center, ), ), ); } else { return (isLoading) ? Center( child: CircularProgressIndicator(), ) : Padding( padding: const EdgeInsets.all(12.0), child: GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: 0.5, mainAxisSpacing: 20, crossAxisSpacing: 15), itemCount: myPhotos.length, itemBuilder: (ctx, index) { return ClipRRect( borderRadius: BorderRadius.circular(8), child: GestureDetector( onTap: () => Navigator.push( context, MaterialPageRoute( builder: (context) => PhotoDetailScreen( myPhotos[index], ), ), ), child: Utility.imageFromBase64String( myPhotos[index].title, ) ?? CircularProgressIndicator(), ), ); }, // crossAxisCount: 2, // childAspectRatio: 0.5, // mainAxisSpacing: 5, // crossAxisSpacing: 2, // children: myPhotos.map((photo) { // return Utility.imageFromBase64String(photo.title); // }).toList(), ), ); } }, ), ); } }
0
mirrored_repositories/Screenshot-Manager-App
mirrored_repositories/Screenshot-Manager-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:screenshot_manager/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/thetechnocafe_flutter_examples/lib
mirrored_repositories/thetechnocafe_flutter_examples/lib/http_example/main.dart
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; void main() { runApp(HttpApp()); } class Post { final int userId; final int id; final String title; Post({ this.userId, this.id, this.title, }); factory Post.fromJSON(Map<String, dynamic> json) { return Post( id: json['id'], userId: json['userId'], title: json['title'], ); } } class HttpApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: HttpExampleWidget(), ); } } class HttpExampleWidget extends StatefulWidget { @override _HttpExampleWidgetState createState() => _HttpExampleWidgetState(); } class _HttpExampleWidgetState extends State<HttpExampleWidget> { List<Post> _posts = []; void _fetchPosts() async { final response = await http.get('https://jsonplaceholder.typicode.com/posts'); final List<Post> parsedResponse = jsonDecode(response.body) .map<Post>((json) => Post.fromJSON(json)) .toList(); setState(() { _posts.clear(); _posts.addAll(parsedResponse); }); } void _createPost() async { final response = await http.post( 'https://jsonplaceholder.typicode.com/posts', body: jsonEncode( { 'title': 'foo', 'body': 'bar', 'userId': 1, }, ), headers: {'Content-Type': "application/json"}, ); final Post parsedResponse = Post.fromJSON(jsonDecode(response.body)); // Use the parsedResponse to diplay the newly created post. } @override void initState() { super.initState(); _fetchPosts(); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: ListView.builder( itemCount: this._posts.length, itemBuilder: (context, index) { final post = this._posts[index]; return ListTile( title: Text(post.title), subtitle: Text('Id: ${post.id} UserId: ${post.userId}'), ); }, ), ), ); } }
0
mirrored_repositories/thetechnocafe_flutter_examples/lib
mirrored_repositories/thetechnocafe_flutter_examples/lib/sqlite_example/main.dart
import 'package:flutter/material.dart'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; void main() => runApp(SQLiteApp()); class SQLiteApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Contacts(), ); } } class Contacts extends StatefulWidget { @override _ContactsState createState() => _ContactsState(); } class Contact { final int id; final String phone; Contact(this.id, this.phone); factory Contact.fromJson(Map<String, dynamic> json) { return Contact(json['id'], json['phone']); } Map<String, dynamic> toJson() { return { "id": this.id, "phone": this.phone, }; } } class _ContactsState extends State<Contacts> { Database _database; final TextEditingController _phoneTextController = TextEditingController(); List<Contact> _contacts = []; @override void initState() { super.initState(); _initDatabase(); } void _initDatabase() async { final databasePath = await getDatabasesPath(); final String path = join(databasePath, "contacts.db"); _database = await openDatabase( path, version: 1, onCreate: (database, version) async { await database.execute( 'CREATE TABLE Contact(id INTEGER PRIMARY KEY AUTOINCREMENT, phone TEXT);'); }, ); _fetchContacts(); } void _fetchContacts() async { final result = await _database.query("Contact"); setState(() { _contacts = result.map<Contact>((contact) => Contact.fromJson(contact)).toList(); }); } void _saveContact() async { final phone = _phoneTextController.text; if (phone.isEmpty) { return; } final contact = Contact(null, phone); _database.insert("Contact", contact.toJson()); _phoneTextController.clear(); _fetchContacts(); } void _deleteContact(int id) async { await _database.delete( "Contact", where: "id = ?", whereArgs: [id], ); _fetchContacts(); } @override void dispose() { super.dispose(); _database.close(); _phoneTextController.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Contacts'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( children: <Widget>[ TextField( controller: _phoneTextController, keyboardType: TextInputType.number, ), RaisedButton( child: Text('Save'), onPressed: () { _saveContact(); }, ), Expanded( child: ListView.builder( itemCount: _contacts.length, itemBuilder: (context, index) { final contact = _contacts[index]; return ListTile( title: Text(contact.phone), onLongPress: () { _deleteContact(contact.id); }, ); }, ), ) ], ), ), ); } }
0
mirrored_repositories/thetechnocafe_flutter_examples
mirrored_repositories/thetechnocafe_flutter_examples/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:thetechnocafe_flutter_examples/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/programming-world-flutter
mirrored_repositories/programming-world-flutter/lib/profile.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_webview_plugin/flutter_webview_plugin.dart'; class Profile extends StatefulWidget { @override _ProfileState createState() => _ProfileState(); } class _ProfileState extends State<Profile> { String url = "https://pw.findjobalerts.com/"; final flutterWebviewPlugin = new FlutterWebviewPlugin(); StreamSubscription<WebViewStateChanged> _onchanged; // here we checked the url state if it loaded or start Load or abort Load @override void initState() { // TODO: implement initState super.initState(); _onchanged = flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged state) { if (mounted) { if(state.type== WebViewState.finishLoad){ // if the full website page loaded print("loaded..."); }else if (state.type== WebViewState.abortLoad){ // if there is a problem with loading the url print("there is a problem..."); } else if(state.type== WebViewState.startLoad){ // if the url started loading print("start loading..."); } } }); } @override void dispose() { // TODO: implement dispose super.dispose(); flutterWebviewPlugin.dispose(); // disposing the webview widget to avoid any leaks } @override Widget build(BuildContext context) { return WebviewScaffold( url: url, withJavascript: true, // run javascript withZoom: false, // if you want the user zoom-in and zoom-out hidden: true , // appCacheEnabled: true, // put it true if you want to show CircularProgressIndicator while waiting for the page to load appBar: AppBar( //title: Text("Coding Materials"), centerTitle: false, elevation: 1, iconTheme: IconThemeData(color: Colors.white), actions: <Widget>[ Container( padding: const EdgeInsets.all(0.0), width: 50.0, alignment: Alignment.centerLeft, child: InkWell( child: Icon(Icons.refresh, size: 30, ), onTap: (){ flutterWebviewPlugin.reload(); }, ),), Container( padding: const EdgeInsets.all(0.0), width: 50.0, child: InkWell( child: Icon(Icons.arrow_back, size: 30, ), onTap: (){ flutterWebviewPlugin.goBack(); // for going back }, ),), Container( padding: const EdgeInsets.all(0.0), width: 50.0, child:InkWell( child: Icon(Icons.arrow_forward, size: 30, ), onTap: (){ flutterWebviewPlugin.goForward(); // for going forward }, ),), ],// make the icons colors inside appbar with white color ), initialChild: Container( // but if you want to add your own waiting widget just add InitialChild color: Colors.white, child: const Center( child: Text('Please Wait...or Tap Reload'), ),) ); } }
0
mirrored_repositories/programming-world-flutter
mirrored_repositories/programming-world-flutter/lib/aftersplash.dart
import './helper/authenticate.dart'; import './helper/helperfunctions.dart'; import './views/chatrooms.dart'; import 'package:flutter/material.dart'; class After extends StatefulWidget { // This widget is the root of your application. @override AfterState createState() => AfterState(); } class AfterState extends State<After> { bool userIsLoggedIn; @override void initState() { getLoggedInState(); super.initState(); } getLoggedInState() async { await HelperFunctions.getUserLoggedInSharedPreference().then((value) { setState(() { userIsLoggedIn = value; }); }); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Programming World', debugShowCheckedModeBanner: false, theme: ThemeData( primaryColor: Color(0xff145C9E), // scaffoldBackgroundColor: Color(0xff000000), accentColor: Color(0xff007EF4), //fontFamily: "OverpassRegular", visualDensity: VisualDensity.adaptivePlatformDensity, ), home: userIsLoggedIn != null ? userIsLoggedIn ? ChatRoom() : Authenticate() : Container( decoration: BoxDecoration( image: DecorationImage( image: AssetImage("images/logo.png"), fit: BoxFit.fill)), child: Center( child: Authenticate(), ), ), ); } }
0
mirrored_repositories/programming-world-flutter
mirrored_repositories/programming-world-flutter/lib/updates.dart
import 'package:flutter/material.dart'; import 'package:flutter_webview_plugin/flutter_webview_plugin.dart'; import 'package:splashscreen/splashscreen.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'home/home_screen.dart'; import 'views/chatrooms.dart'; class Updates extends StatefulWidget { @override _UpdatesState createState() => new _UpdatesState(); } class _UpdatesState extends State<Updates> { @override Widget build(BuildContext context) { return new SplashScreen( seconds: 2, navigateAfterSeconds: AfterSplash(), image: new Image.asset( 'assets/images/icon.png', width: 100, height: 100, ), backgroundColor: Colors.white, photoSize: 100.0, loaderColor: Colors.blue[700], ); } } class AfterSplash extends StatefulWidget { @override _UpdatessState createState() => _UpdatessState(); } class _UpdatessState extends State<AfterSplash> { @override Widget build(BuildContext context) { return WillPopScope( onWillPop: _onBackPressed, child: WebviewScaffold( appBar: AppBar( title: Image.asset( "assets/images/logo.png", height: 40, ), ), // Enter your custom url url: "https://pw.findjobalerts.com/updates/", withJavascript: true, withLocalStorage: true, enableAppScheme: true, primary: true, supportMultipleWindows: true, allowFileURLs: true, withLocalUrl: true, scrollBar: true, appCacheEnabled: true, )); } Future<bool> _onBackPressed() { return Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => ChatRoom()),); } }
0
mirrored_repositories/programming-world-flutter
mirrored_repositories/programming-world-flutter/lib/book.dart
import './book/book_c.dart'; import './book/book_cplusplus.dart'; import './book/book_flutter.dart'; import './book/book_js.dart'; import './book/book_mysql.dart'; import './book/book_php.dart'; import './book/book_python.dart'; import './book/book_react.dart'; import 'package:flutter/material.dart'; import 'package:vertical_card_pager/vertical_card_pager.dart'; import './constant/constant.dart'; import './book/book_java.dart'; class Book extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Programming World', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, fontFamily: 'lol', textTheme: textTheme, ), home: BookPage(), ); } } class BookPage extends StatefulWidget { @override _BookPageState createState() => _BookPageState(); } final List<String> titles = [ "", //0 "", //1 "", //2 "", //3 "", //4 "", //5 "", //6 "", //7 "", //0 ]; final List<Widget> images = [ Hero( tag: "JAVA", child: ClipRRect( borderRadius: BorderRadius.circular(20.0), child: Image.network( "https://pw.findjobalerts.com/wp-content/uploads/2020/09/book_java.jpg", fit: BoxFit.cover, ), ), ), Hero( tag: "FLUTTER", child: ClipRRect( borderRadius: BorderRadius.circular(20.0), child: Image.network( "https://pw.findjobalerts.com/wp-content/uploads/2020/09/book_flutter.jpg", fit: BoxFit.cover, ), ), ), Hero( tag: "PHP", child: ClipRRect( borderRadius: BorderRadius.circular(20.0), child: Image.network( "https://pw.findjobalerts.com/wp-content/uploads/2020/09/book_php.jpg", fit: BoxFit.cover, ), ), ), Hero( tag: "REACT", child: ClipRRect( borderRadius: BorderRadius.circular(20.0), child: Image.network( "https://pw.findjobalerts.com/wp-content/uploads/2020/09/book_react.jpg", fit: BoxFit.cover, ), ), ), Hero( tag: "JS", child: ClipRRect( borderRadius: BorderRadius.circular(20.0), child: Image.network( "https://pw.findjobalerts.com/wp-content/uploads/2020/09/book_js.jpg", fit: BoxFit.cover, ), ), ), Hero( tag: "C", child: ClipRRect( borderRadius: BorderRadius.circular(20.0), child: Image.network( "https://pw.findjobalerts.com/wp-content/uploads/2020/09/book_c.jpg", fit: BoxFit.cover, ), ), ), Hero( tag: "C++", child: ClipRRect( borderRadius: BorderRadius.circular(20.0), child: Image.network( "images/https://pw.findjobalerts.com/wp-content/uploads/2020/09/book_cplusplus.jpg", fit: BoxFit.cover, ), ), ), Hero( tag: "PYTHON", child: ClipRRect( borderRadius: BorderRadius.circular(20.0), child: Image.network( "https://pw.findjobalerts.com/wp-content/uploads/2020/09/book_python.jpg", fit: BoxFit.cover, ), ), ), Hero( tag: "MySQL", child: ClipRRect( borderRadius: BorderRadius.circular(20.0), child: Image.network( "https://pw.findjobalerts.com/wp-content/uploads/2020/09/book_mysql.jpg", fit: BoxFit.cover, ), ), ), ]; class _BookPageState extends State<BookPage> { @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Column( children: <Widget>[ /* Container( width: double.infinity, height: 70, child: Padding( padding: const EdgeInsets.symmetric(vertical: 15.0), child: Center( child: Image.network( "images/logo.png", fit: BoxFit.cover, )), ), ),*/ Expanded( child: Container( child: VerticalCardPager( // textStyle: TextStyle(color : Colors.red), titles: titles, images: images, onPageChanged: (page) { // print(page); }, onSelectedItem: (index) { if (index == 0) { Navigator.push( context, MaterialPageRoute(builder: (context) => new BookJava()), ); } if (index == 1) { Navigator.push( context, MaterialPageRoute( builder: (context) => new BookFlutter()), ); } if (index == 2) { Navigator.push( context, MaterialPageRoute(builder: (context) => new BookPHP()), ); } if (index == 3) { Navigator.push( context, MaterialPageRoute( builder: (context) => new BookReact()), ); } if (index == 4) { Navigator.push( context, MaterialPageRoute(builder: (context) => new BookJS()), ); } if (index == 5) { Navigator.push( context, MaterialPageRoute(builder: (context) => new BookC()), ); } if (index == 6) { Navigator.push( context, MaterialPageRoute( builder: (context) => new BookCplusplus()), ); } if (index == 7) { Navigator.push( context, MaterialPageRoute( builder: (context) => new BookPython()), ); } if (index == 8) { Navigator.push( context, MaterialPageRoute( builder: (context) => new BookMySQL()), ); } }, ), ), ), ], ), ), ); } }
0
mirrored_repositories/programming-world-flutter
mirrored_repositories/programming-world-flutter/lib/main.dart
import 'package:flutter/material.dart'; import 'package:splashscreen/splashscreen.dart'; import 'aftersplash.dart'; void main() { runApp(new MaterialApp( debugShowCheckedModeBanner: false, home: new MyApp(), )); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return SplashScreen( seconds: 3, backgroundColor: Colors.white, loaderColor: Colors.blue, image: Image.asset('images/logo.png'), photoSize: 70.0, navigateAfterSeconds: After(), ); } }
0
mirrored_repositories/programming-world-flutter/lib
mirrored_repositories/programming-world-flutter/lib/java/java.dart
import 'package:flutter/material.dart'; import 'dart:convert'; import 'about_java.dart'; class Java extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'ListViews', home: Scaffold( appBar: AppBar( elevation: 0.0, leading: IconButton( icon: Icon(Icons.arrow_back_ios), color: Colors.grey, iconSize: 35, onPressed: () { // Navigator.push( Navigator.pop(context, true); // context, // MaterialPageRoute(builder: (context) => Nav()), // ); }), backgroundColor: Colors.white, bottom: PreferredSize( child: Padding( padding: const EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 0.0), child: new Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( 'Java Programming', style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: 30, ), ), IconButton( icon: const Icon(Icons.code), iconSize: 35, color: Colors.grey, onPressed: () {}, ), ], ), ), preferredSize: Size(0.0, 80.0), ), ), body: Center( child: FutureBuilder( builder: (context, snapshot) { var showData = json.decode(snapshot.data); return ListView.builder( itemCount: showData.length, itemBuilder: (BuildContext context, int index) { return Card( elevation: 2.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0)), margin: new EdgeInsets.symmetric( horizontal: 25.0, vertical: 15.0), child: InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => About(showData[index])), ); }, child: ListTile( contentPadding: EdgeInsets.symmetric( horizontal: 20.0, vertical: 10.0), leading: CircleAvatar( backgroundImage: NetworkImage(showData[index]['picture']), ), title: Text(showData[index]['name']), trailing: Icon(Icons.arrow_forward_ios), ), ), ); }, ); }, future: DefaultAssetBundle.of(context).loadString("assets/data.json"), ), ), ), ); } } class User { String picture; String name; String bio; User({this.picture, this.name, this.bio}); factory User.fromJson(Map<String, dynamic> json) { return new User( picture: json['picture'] as String, name: json['name'] as String, bio: json['bio'] as String, ); } } class UserList { List<User> users; UserList({this.users}); }
0
mirrored_repositories/programming-world-flutter/lib
mirrored_repositories/programming-world-flutter/lib/java/about_java.dart
import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; class About extends StatelessWidget { final showData; About(this.showData); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( backgroundColor: Color(0xffffffff), appBar: AppBar( elevation: 0.0, backgroundColor: Colors.transparent, leading: IconButton( icon: Icon(Icons.arrow_back_ios), color: Colors.grey, iconSize: 35, onPressed: () { Navigator.pop(context, true); }, ), ), body: Stack( alignment: Alignment.topCenter, children: <Widget>[ Padding( padding: EdgeInsets.symmetric(horizontal: 50, vertical: 10), child: Container( // margin: EdgeInsets.only(bottom: 01), child: ListView( //semanticContainer: true, // child: Padding( // padding: const EdgeInsets.all(30.0), // child: new Column( // mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( height: 100, ), Center( child: Align( alignment: Alignment.topCenter, child: Text( showData['name'], style: TextStyle( color: Colors.grey, fontWeight: FontWeight.bold, fontSize: 30, ), ), ), ), SizedBox( height: 20, ), Center( child: Align( alignment: Alignment.bottomCenter, child: Text( showData['bio'], style: TextStyle( color: Colors.grey, ), ), ), ), ], ), ), // elevation: 5, ), // ), // ), Container( width: 100, height: 100, decoration: ShapeDecoration(shape: CircleBorder(), color: Colors.white), child: Padding( padding: EdgeInsets.all(8), child: DecoratedBox( decoration: ShapeDecoration( shape: CircleBorder(), image: DecorationImage( fit: BoxFit.cover, image: NetworkImage( showData['picture'], ))), ), ), ), ], )), ); } }
0
mirrored_repositories/programming-world-flutter/lib
mirrored_repositories/programming-world-flutter/lib/mysql/about_mysql.dart
import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; class AboutMysql extends StatelessWidget { final showData; AboutMysql(this.showData); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( backgroundColor: Color(0xffffffff), appBar: AppBar( elevation: 0.0, backgroundColor: Colors.transparent, leading: IconButton( icon: Icon(Icons.arrow_back_ios), color: Colors.grey, iconSize: 35, onPressed: () { Navigator.pop(context, true); }, ), ), body: Stack( alignment: Alignment.topCenter, children: <Widget>[ Padding( padding: EdgeInsets.symmetric(horizontal: 50, vertical: 10), child: Container( // margin: EdgeInsets.only(bottom: 01), child: ListView( //semanticContainer: true, // child: Padding( // padding: const EdgeInsets.all(30.0), // child: new Column( // mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( height: 100, ), Center( child: Align( alignment: Alignment.topCenter, child: Text( showData['name'], style: TextStyle( color: Colors.grey, fontWeight: FontWeight.bold, fontSize: 30, ), ), ), ), SizedBox( height: 20, ), Center( child: Align( alignment: Alignment.bottomCenter, child: Text( showData['bio'], style: TextStyle( color: Colors.grey, ), ), ), ), ], ), ), // elevation: 5, ), // ), // ), Container( width: 100, height: 100, decoration: ShapeDecoration(shape: CircleBorder(), color: Colors.white), child: Padding( padding: EdgeInsets.all(8), child: DecoratedBox( decoration: ShapeDecoration( shape: CircleBorder(), image: DecorationImage( fit: BoxFit.cover, image: NetworkImage( showData['picture'], ))), ), ), ), ], )), ); } }
0