repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/Chrona/lib
mirrored_repositories/Chrona/lib/news/news_details.dart
import 'package:chrona_1/news/web_view.dart'; import 'package:flutter/material.dart'; import 'model/news.dart'; class NewsDetails extends StatefulWidget { final Article article; final String title; NewsDetails(this.article, this.title); @override _NewsDetailsState createState() => _NewsDetailsState(); } class _NewsDetailsState extends State<NewsDetails> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), backgroundColor: Colors.black, ), body: ListView( children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.stretch, verticalDirection: VerticalDirection.up, children: <Widget>[ Column( children: <Widget>[ Image.network((widget.article.urlToImage==null)?'images/no_image_available.png':widget.article.urlToImage), Padding( padding: const EdgeInsets.all(8.0), child: Text( widget.article.title, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20.0), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Text( (widget.article.description==null)?"Sorry! but, No Description is currently Available":widget.article.description, style: TextStyle(fontSize: 19.0), ), ) ], ), MaterialButton( height: 50.0, color: Colors.grey, child: Text( "For more news", style: TextStyle(color: Colors.white, fontSize: 18.0), ), onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (BuildContext context) => WebView(widget.article.url,widget.article.source.name))); }, ) ], ), ], )); } }
0
mirrored_repositories/Chrona/lib
mirrored_repositories/Chrona/lib/news/categories.dart
class Categories { String image; String title; String newsType; Categories(String image, String title, String newsType) { this.image = image; this.title = title; this.newsType = newsType; } }
0
mirrored_repositories/Chrona/lib
mirrored_repositories/Chrona/lib/news/strings.dart
class Strings { static String apiKey = "36bbc55c610e417e8b80512b6ea9e7c5"; static String country = "in"; }
0
mirrored_repositories/Chrona/lib/news
mirrored_repositories/Chrona/lib/news/model/news.dart
class Article { Source source; String author; String title; String description; String url; String urlToImage; String publishedAt; String content; Article( {this.source, this.author, this.title, this.description, this.url, this.urlToImage, this.publishedAt, this.content}); factory Article.fromJson(Map<String, dynamic> json) { return Article( source: Source.fromJson(json["source"]), author: json["author"], title: json["title"], description: json["description"], url: json["url"], urlToImage: json["urlToImage"], publishedAt: json["publishedAt"], content: json["content"]); } toJson() { return{ "title":title, "description":description, "url":url, "source":source.name, "urlToImage":urlToImage, "published":publishedAt, "content":content, }; } } class Source { String id; String name; Source({this.id, this.name}); factory Source.fromJson(Map<String, dynamic> json) { return Source( id: json["id"] as String, name: json["name"] as String, ); } }
0
mirrored_repositories/Chrona/lib
mirrored_repositories/Chrona/lib/UserInfo/state.dart
import 'package:firebase_auth/firebase_auth.dart'; class StateModel { bool isLoading; FirebaseUser user; StateModel({ this.isLoading = false, this.user, }); factory StateModel.set(bool val,FirebaseUser firebaseUser) { return StateModel( isLoading: val, user: firebaseUser ); } } class StaticState { static FirebaseUser user; static bool loading=false; }
0
mirrored_repositories/Chrona/lib
mirrored_repositories/Chrona/lib/SignIn/app.dart
import 'package:flutter/material.dart'; import '../Activities/home.dart'; import 'login.dart'; class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Chrona', debugShowCheckedModeBanner: false, theme: ThemeData.light(), darkTheme: ThemeData.dark(), routes: { '/': (context) => HomeScreen(), '/login': (context) => LoginScreen(), }, ); } }
0
mirrored_repositories/Chrona/lib
mirrored_repositories/Chrona/lib/SignIn/auth.dart
import 'package:google_sign_in/google_sign_in.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'login.dart'; Future<GoogleSignInAccount> getSignedInAccount( GoogleSignIn googleSignIn) async { GoogleSignInAccount account = googleSignIn.currentUser; if (account == null) { account = await googleSignIn.signInSilently(); } return account; } Future<FirebaseUser> signIntoFirebase( GoogleSignInAccount googleSignInAccount) async { final GoogleSignIn _googleSignIn = GoogleSignIn(); final FirebaseAuth _auth = FirebaseAuth.instance; final GoogleSignInAccount googleUser = await _googleSignIn.signIn(); final GoogleSignInAuthentication googleAuth = await googleUser.authentication; final AuthCredential credential = GoogleAuthProvider.getCredential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); final FirebaseUser user = (await _auth.signInWithCredential(credential)).user; print("signed in " + user.displayName); return user; }
0
mirrored_repositories/Chrona/lib
mirrored_repositories/Chrona/lib/SignIn/state_widget.dart
import 'dart:async'; import 'package:chrona_1/Activities/home.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:firebase_auth/firebase_auth.dart'; import '../UserInfo/state.dart'; import 'auth.dart'; class StateWidget extends StatefulWidget { final StateModel state; final Widget child; StateWidget({ @required this.child, this.state, }); // Returns data of the nearest widget _StateDataWidget // in the widget tree. static _StateWidgetState of(BuildContext context) { return (context.inheritFromWidgetOfExactType(_StateDataWidget) as _StateDataWidget) .data; } @override _StateWidgetState createState() => new _StateWidgetState(); } class _StateWidgetState extends State<StateWidget> { StateModel state; GoogleSignInAccount googleAccount; final FirebaseDatabase database = FirebaseDatabase.instance; // final GlobalKey<FormState> formKey = GlobalKey<FormState>(); DatabaseReference databaseReference; final GoogleSignIn googleSignIn = new GoogleSignIn(); @override void initState() { print("########initstate#############"); super.initState(); if (widget.state != null) { print("#%#%#%#%#%#%#%#%%##%#%%#%"); StateModel.set(false, state.user); state = widget.state; StaticState.user=widget.state.user; StaticState.loading=false; } else { print("!@@!@!@!@!@!@!@!@!@!@!@!!@!@"); state = new StateModel(isLoading: true); StateModel.set(true,null ); initUser(); } databaseReference = database.reference().child("Users"); } Future<Null> initUser() async { googleAccount = await getSignedInAccount(googleSignIn); if (googleAccount == null) { print("@@@@@@@@@googleaccount@@@@@@@@@@@@@"); setState(() { StaticState.loading=false; state.isLoading = false; }); } else { print("!!!!!!!!!!!!!signinwith google!!!!!!!!!!!!"); await signInWithGoogle(); } } Future<Null> signInWithGoogle() async { if (googleAccount == null) { print("^^^^^^^^^^^future^^^^^^^^^^^"); // Start the sign-in process: googleAccount = await googleSignIn.signIn(); } FirebaseUser firebaseUser = await signIntoFirebase(googleAccount); state.user = firebaseUser; print("################else###########3"); // new StaticState.user=firebaseUser; String s=StaticState.user.email; s=s.substring(0,s.indexOf("@")); databaseReference.child(s).child("info").set({"name":firebaseUser.displayName,"emailId":firebaseUser.email}); setState(() { StaticState.user=firebaseUser; state.isLoading = false; state.user = firebaseUser; StaticState.loading=false; }); } @override Widget build(BuildContext context) { return new _StateDataWidget( data: this, child: widget.child, ); } } class _StateDataWidget extends InheritedWidget { final _StateWidgetState data; _StateDataWidget({ Key key, @required Widget child, @required this.data, }) : super(key: key, child: child); // Rebuild the widgets that inherit from this widget // on every rebuild of _StateDataWidget: @override bool updateShouldNotify(_StateDataWidget old) => true; }
0
mirrored_repositories/Chrona/lib
mirrored_repositories/Chrona/lib/SignIn/login.dart
import 'dart:async'; import 'package:chrona_1/Activities/home.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'state_widget.dart'; import 'package:chrona_1/UserInfo/state.dart'; class LoginScreen extends StatefulWidget { @override _LoginScreenState createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { @override void initState() { super.initState(); Timer(Duration(seconds: 4), () => gotoHome(context)); } @override Widget build(BuildContext context) { return Scaffold( body: Stack( fit: StackFit.expand, children: <Widget>[ Container( decoration: BoxDecoration(color: Colors.black54), ), Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Expanded( flex: 2, child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ CircleAvatar( backgroundColor: Colors.white, radius: 50.0, child: Image(image: AssetImage('images/work.png')), ), Padding( padding: EdgeInsets.only(top: 10.0), ), Text( "Chrona", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 24.0), ) ], ), ), ), Expanded( flex: 1, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "Signing you in...", softWrap: true, textAlign: TextAlign.center, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 18.0, color: Colors.white), ), Padding( padding: EdgeInsets.only(top: 20.0), ), CircularProgressIndicator(), Padding( padding: EdgeInsets.only(top: 20.0), ), Text( "Get the information you need. Anytime. Anywhere.", softWrap: true, textAlign: TextAlign.center, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 18.0, color: Colors.white), ) ], ), ) ], ) ], ), ); } void gotoHome(BuildContext context){ if(StaticState.user==null)StateWidget.of(context).signInWithGoogle() .then((val)=>Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>HomeScreen()))) .catchError((err)=>SystemNavigator.pop()); } }
0
mirrored_repositories/Chrona/lib
mirrored_repositories/Chrona/lib/SharedPreferences/shared_preferences.dart
import 'package:chrona_1/UserInfo/state.dart'; import 'package:shared_preferences/shared_preferences.dart'; class SharedPreferencesTest { final String verification = "hello";//StaticState.user.email.toString(); Future<bool> getverification() async { final SharedPreferences prefs = await SharedPreferences.getInstance(); return prefs.getBool(verification) ; } Future<bool> setVerification(bool value) async { final SharedPreferences prefs = await SharedPreferences.getInstance(); return prefs.setBool(verification, value); } }
0
mirrored_repositories/Flutter-BMI-Calculation-App
mirrored_repositories/Flutter-BMI-Calculation-App/lib/input_page.dart
import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:healthy/resuts_screen.dart'; import 'package:healthy/reusable_card.dart'; import 'constants.dart'; import 'icon_content.dart'; import 'calculator_brain.dart'; enum Gender { male, female } class InputPage extends StatefulWidget { @override _InputPageState createState() => _InputPageState(); } class _InputPageState extends State<InputPage> { Gender selectedGender; int height = 180; int weight = 70; int age = 25; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(centerTitle: true, elevation: 80, title: Text( 'KEEP HEALTHY', style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ), body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Expanded( child: Row( children: <Widget>[ Expanded( child: ReusableCard( onPress: (){ setState(() { selectedGender=Gender.male; }); }, colour: selectedGender == Gender.male ? kactiveCardColor : kinactiveCardColor, cardChild: iconContent( iconType: (FontAwesomeIcons.male), lable: ('MALE'), )), ), Expanded( child: ReusableCard( onPress: (){ setState(() { selectedGender=Gender.female; }); }, colour: selectedGender == Gender.female ? kactiveCardColor : kinactiveCardColor, cardChild: iconContent( iconType: (FontAwesomeIcons.female), lable: ('FEMALE'), )), ), ], )), Expanded( child: ReusableCard( colour: kactiveCardColor, cardChild: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[Text('HEIGHT',style: klableTextStyle,), Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[ Text(height.toString(), style: knumberTextStyle,), Text('cm', style: klableTextStyle,) ], ), SliderTheme( data: SliderTheme.of(context).copyWith( thumbShape: RoundSliderThumbShape( enabledThumbRadius: 12), overlayShape:RoundSliderOverlayShape( overlayRadius: 24, ), ), child: Slider(value: height.toDouble(), activeColor: Colors.pink, inactiveColor: Colors.pink.shade100, min: 120, max: 220, onChanged: (double newValue){ setState(() { height = newValue.toInt(); }); }, ), ) ], ), ), ), Expanded( child: Row( children: <Widget>[ Expanded( child: ReusableCard( colour: kactiveCardColor, cardChild: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('WEIGHT',style: klableTextStyle,), Text(weight.toString(),style: knumberTextStyle,), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RoundIconButton(icon: Icons.add, onPressed: (){ setState(() { weight++; }); }, ), SizedBox( height: 0, width: 10, ), RoundIconButton(icon: Icons.remove, onPressed: (){ setState(() { weight--; }); }, ), ], ) ], ), ), ), Expanded( child: ReusableCard( colour: kactiveCardColor, cardChild: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('AGE',style: klableTextStyle,), Text(age.toString(),style: knumberTextStyle,), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RoundIconButton(icon: Icons.add, onPressed: (){ setState(() { age++; }); }, ), SizedBox( height: 0, width: 10, ), RoundIconButton(icon: Icons.remove, onPressed: (){ setState(() { age--; }); }, ), ], ) ], ), ), ), ], )), ResultButton(buttonTitle: 'CALCULATE',onTap: (){ CalculatorBrain calc = CalculatorBrain(height: height, weight: weight); Navigator.push(context, MaterialPageRoute(builder: (context){ return ResultsScreen( bmiResults: calc.CalculateBMI(), resultText: calc.getResult() , discription: calc.getDiscription(), ); })); },) ], )); } } class ResultButton extends StatelessWidget { ResultButton({@required this.onTap , @required this.buttonTitle}); final Function onTap; final String buttonTitle; @override Widget build(BuildContext context) { return GestureDetector( onTap: onTap, child: Container( alignment:Alignment.center, child: Text(buttonTitle,style: klargebuttonStyle,), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: kbottomContainerColor, ), margin: EdgeInsets.only(bottom: 20, left: 15, right: 15, top: 8), height: kbottomContainerHeight, width: double.infinity, ), ); } } class RoundIconButton extends StatelessWidget { RoundIconButton({@required this.icon, this.onPressed }); final IconData icon; final Function onPressed; @override Widget build(BuildContext context) { return RawMaterialButton( child: Icon(icon,size: 34,), shape: CircleBorder(), fillColor: Color(0x338080ff), constraints: BoxConstraints.tightFor( width: 56, height: 56,), elevation: 10, onPressed: onPressed, ); } }
0
mirrored_repositories/Flutter-BMI-Calculation-App
mirrored_repositories/Flutter-BMI-Calculation-App/lib/calculator_brain.dart
import 'dart:math'; class CalculatorBrain { double _bmi; CalculatorBrain({this.height, this.weight}); final int height; final int weight; String CalculateBMI() { _bmi = weight / pow(height / 100, 2); return _bmi.toStringAsFixed(1); } String getResult() { if (_bmi >= 25) { return 'OVERWEIGHT'; } else if (_bmi > 18.5) { return 'NORMAL'; } else { return 'UNDERWEIGHT'; } } String getDiscription (){ if (_bmi >= 25) { return 'Amm .. You have a higher than normal weight. Try to exercise more.'; } else if (_bmi > 18.5) { return 'Great .. You are normal body weight. Good job!'; } else { return 'What .. You have a lower than normal body weight. You can eat more.'; } } }
0
mirrored_repositories/Flutter-BMI-Calculation-App
mirrored_repositories/Flutter-BMI-Calculation-App/lib/resuts_screen.dart
import 'package:flutter/material.dart'; import 'package:healthy/reusable_card.dart'; import 'constants.dart'; import 'input_page.dart'; class ResultsScreen extends StatelessWidget { ResultsScreen({@required this.bmiResults, @required this.resultText, @required this.discription }); final String bmiResults; final String resultText; final String discription; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('KEEP HEALTHY',style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ),),centerTitle:true, ), body: Column( children: <Widget>[ SizedBox(height: 25,), Text('YOUR RESULTS',style: TextStyle(fontSize: 40,fontWeight: FontWeight.w800),), Expanded(child: ReusableCard( colour: kactiveCardColor, cardChild: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text(resultText, style: TextStyle(color: Colors.green,fontSize: 24, fontWeight: FontWeight.bold),), Text(bmiResults,style: TextStyle(fontSize: 90,fontWeight: FontWeight.w800),), Text(discription, style: klableTextStyle,textAlign: TextAlign.center, ) ], ), ) ), ResultButton(buttonTitle: 'RE-CALCULATE',onTap: (){ Navigator.pop(context); },) ], ), ); } }
0
mirrored_repositories/Flutter-BMI-Calculation-App
mirrored_repositories/Flutter-BMI-Calculation-App/lib/constants.dart
import 'package:flutter/material.dart'; const kactiveCardColor = Color(0xff1d1e33); const kinactiveCardColor = Color(0xff111328); const kbottomContainerHeight=80.0; const kbottomContainerColor=Colors.pink; const klableTextStyle = TextStyle( fontSize: 18, color: Color(0xff8d8e98), ); const knumberTextStyle = TextStyle( fontSize: 50,fontWeight: FontWeight.w900 ); const klargebuttonStyle = TextStyle(fontSize: 26, fontWeight: FontWeight.w700); //textAlign: TextAlign.center,
0
mirrored_repositories/Flutter-BMI-Calculation-App
mirrored_repositories/Flutter-BMI-Calculation-App/lib/main.dart
import 'package:flutter/material.dart'; import 'input_page.dart'; void main() =>runApp(BMICalculator()); class BMICalculator extends StatelessWidget{ @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData.dark().copyWith( primaryColor: Color(0xff0a0e21), scaffoldBackgroundColor: Color(0xff0a0e21), ), home: InputPage(), ); } }
0
mirrored_repositories/Flutter-BMI-Calculation-App
mirrored_repositories/Flutter-BMI-Calculation-App/lib/icon_content.dart
import 'package:flutter/material.dart'; import 'constants.dart'; class iconContent extends StatelessWidget { final IconData iconType; final String lable; iconContent({@required this.iconType, this.lable}); @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon( iconType, size: 80, ), SizedBox( height: 30, ), Text( lable, style: klableTextStyle ) ], ); } }
0
mirrored_repositories/Flutter-BMI-Calculation-App
mirrored_repositories/Flutter-BMI-Calculation-App/lib/reusable_card.dart
import 'package:flutter/material.dart'; class ReusableCard extends StatelessWidget { ReusableCard({@required this.colour, this.cardChild, this.onPress}); final Color colour; final Widget cardChild; final Function onPress; @override Widget build(BuildContext context) { return GestureDetector( onTap: onPress, child: Container( child: cardChild, margin: EdgeInsets.all(12), decoration: BoxDecoration( color: colour, borderRadius: BorderRadius.circular(10) ), ), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/hero_animation.dart
import 'package:anny/animation_list_item.dart'; import 'package:flutter/material.dart'; class MyHero extends StatefulWidget { final String appBarTitle; MyHero({ this.appBarTitle, }); @override _MyHeroState createState() => _MyHeroState(); } class _MyHeroState extends State<MyHero> with SingleTickerProviderStateMixin { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Padding( padding: const EdgeInsets.all(32.0), child: Hero( tag: Hero, child: AnimationListItem( title: 'Hero Animation', ), ), ), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_switcher.dart
import 'dart:math'; import 'package:flutter/material.dart'; class MyAnimationSwitcher extends StatefulWidget { final String appBarTitle; MyAnimationSwitcher({ this.appBarTitle, }); @override _MyAnimationSwitcherState createState() => _MyAnimationSwitcherState(); } class _MyAnimationSwitcherState extends State<MyAnimationSwitcher> with TickerProviderStateMixin { int _counter = 0; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: GestureDetector( onTap: () => setState(() => _counter++), child: Container( color: Colors.white, child: Center( child: Wrap( children: [ AnimatedSwitcher( duration: Duration(milliseconds: 300), child: getWidget(), transitionBuilder: (Widget child, Animation<double> animation) { /// default is FadeTransition return FadeTransition( opacity: animation, child: ScaleTransition( // below is the percentage given to a widget 0.0 - 1.0 scale: Tween<double>(begin: .6, end: .8) .animate(animation), child: child, ), ); }, ), ], ), ), ), ), ); } /// different widgets according to counter value which is unique for every key Widget getWidget() { if (_counter == 0) { return Padding( padding: const EdgeInsets.all(32.0), child: Container( key: ValueKey<int>(_counter), padding: EdgeInsets.all(64), decoration: BoxDecoration( color: Color.fromRGBO( Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1, ), ), ), ); } else if (_counter == 1) { return Container( key: ValueKey<int>(_counter), padding: EdgeInsets.all(64), decoration: BoxDecoration( color: Color.fromRGBO( Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1, ), shape: BoxShape.circle, ), ); } else if (_counter == 2) { return Padding( padding: const EdgeInsets.all(32.0), child: Container( key: ValueKey<int>(_counter), padding: EdgeInsets.all(64), decoration: BoxDecoration( color: Color.fromRGBO( Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1, ), shape: BoxShape.rectangle, ), ), ); } else if (_counter == 3) { return Padding( padding: const EdgeInsets.all(32.0), child: Container( key: ValueKey<int>(_counter), padding: EdgeInsets.all(56), decoration: BoxDecoration( color: Color.fromRGBO( Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1, ), shape: BoxShape.rectangle, borderRadius: BorderRadius.circular( 16, ), ), ), ); } return Padding( padding: const EdgeInsets.all(16.0), child: Text( 'YOU ARE NOW DONE WITH ALL WIDGETS', textAlign: TextAlign.center, style: TextStyle( letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.bold, color: Colors.blue[900], ), ), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_padding.dart
import 'dart:async'; import 'dart:math'; import 'package:flutter/material.dart'; class MyAnimatedPadding extends StatefulWidget { final String appBarTitle; MyAnimatedPadding({ this.appBarTitle, }); @override _MyAnimatedPaddingState createState() => _MyAnimatedPaddingState(); } class _MyAnimatedPaddingState extends State<MyAnimatedPadding> { bool selected = false; Timer timer; @override void initState() { super.initState(); timer = Timer.periodic( Duration(milliseconds: 1500), (Timer t) => changeState()); } @override void dispose() { timer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Container( height: double.infinity, width: double.infinity, child: Column( children: <Widget>[ AnimatedPadding( padding: EdgeInsets.only( top: Random().nextInt(100).toDouble(), bottom: Random().nextInt(100).toDouble(), left: Random().nextInt(100).toDouble(), right: Random().nextInt(100).toDouble(), ), duration: Duration( milliseconds: 800, ), curve: Curves.easeInOut, child: Container( padding: EdgeInsets.all( 64, ), decoration: BoxDecoration( color: Colors.blue[900], borderRadius: BorderRadius.circular(12), ), ), ), ], ), ), ); } void changeState() { setState(() {}); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_physical_model.dart
import 'package:flutter/material.dart'; class MyAnimationPhysicalModel extends StatefulWidget { final String appBarTitle; MyAnimationPhysicalModel({ this.appBarTitle, }); @override _MyAnimationPhysicalModelState createState() => _MyAnimationPhysicalModelState(); } class _MyAnimationPhysicalModelState extends State<MyAnimationPhysicalModel> { bool _first = true; @override void initState() { super.initState(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ AnimatedPhysicalModel( duration: const Duration(milliseconds: 500), curve: Curves.fastOutSlowIn, elevation: _first ? 0 : 6.0, shape: BoxShape.rectangle, shadowColor: Colors.black, color: Colors.white, borderRadius: _first ? const BorderRadius.all(Radius.circular(0)) : const BorderRadius.all(Radius.circular(10)), child: Container( height: 120.0, width: 120.0, color: Colors.blue[50], child: FlutterLogo( size: 60, ), ), ), SizedBox( height: 20, ), RaisedButton( child: const Text('Click Me!'), onPressed: () { setState(() { _first = !_first; }); }, ), ], ), ), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_cross_fade.dart
import 'package:flutter/material.dart'; class MyAnimatedCrossFade extends StatefulWidget { final String appBarTitle; MyAnimatedCrossFade({ this.appBarTitle, }); @override _MyAnimatedCrossFadeState createState() => _MyAnimatedCrossFadeState(); } class _MyAnimatedCrossFadeState extends State<MyAnimatedCrossFade> { bool selected = false; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Center( child: AnimatedCrossFade( crossFadeState: selected ? CrossFadeState.showSecond : CrossFadeState.showFirst, duration: Duration(milliseconds: 2000), firstCurve: Curves.easeOut, secondCurve: Curves.easeIn, sizeCurve: Curves.bounceOut, firstChild: InkWell( splashColor: Colors.transparent, onTap: selected ? null : () { setState(() { selected = !selected; }); }, child: Padding( padding: const EdgeInsets.all(16.0), child: Container( width: MediaQuery.of(context).size.width, height: 64, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular( 8.0, ), border: Border.all( color: Colors.blue[700], width: 1, ), ), child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon( Icons.add, size: 24, color: Colors.blue[900], ), SizedBox( width: 24, ), Text( 'Add to cart', style: TextStyle( color: Colors.blue, letterSpacing: 0.5, fontSize: 20, fontWeight: FontWeight.w400, ), ), ], ), ), ), ), ), secondChild: Padding( padding: const EdgeInsets.all(16.0), child: Container( width: MediaQuery.of(context).size.width, height: 64, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular( 8.0, ), border: Border.all( color: Colors.blue[700], width: 1, ), ), child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon( Icons.done, size: 24, color: Colors.blue[900], ), SizedBox( width: 24, ), Text( 'Checkout to cart', style: TextStyle( color: Colors.blue, letterSpacing: 0.5, fontSize: 20, fontWeight: FontWeight.w400, ), ), ], ), ), ), ), ), ), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/rotation_transition.dart
import 'package:flutter/material.dart'; class MyRotationTransition extends StatefulWidget { final String appBarTitle; const MyRotationTransition({Key key, this.appBarTitle}) : super(key: key); @override _MyRotationTransitionState createState() => _MyRotationTransitionState(); } class _MyRotationTransitionState extends State<MyRotationTransition> with SingleTickerProviderStateMixin { AnimationController _animationController; Animation<double> _animation; @override void initState() { super.initState(); /// creates animation controller with [Duration] 2 seconds and [Ticker Provider] for current context _animationController = AnimationController(duration: Duration(seconds: 2), vsync: this)..repeat(reverse: true); /// sets actual animation _animation = CurvedAnimation(curve: Curves.fastOutSlowIn, parent: _animationController); } @override void dispose() { /// disposes the animation controller _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle(color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600), ), ), body: Center( child: RotationTransition( turns: _animation, child: FlutterLogo(size: 150), ), ), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/decoration_box_transition.dart
import 'package:flutter/material.dart'; class MyDecoratedBoxTransition extends StatefulWidget { final String appBarTitle; MyDecoratedBoxTransition({ this.appBarTitle, }); @override _MyDecoratedBoxTransitionState createState() => _MyDecoratedBoxTransitionState(); } class _MyDecoratedBoxTransitionState extends State<MyDecoratedBoxTransition> with SingleTickerProviderStateMixin { AnimationController _animationController; @override void initState() { super.initState(); _animationController = AnimationController( vsync: this, duration: const Duration(seconds: 1), ) ..addStatusListener((status) { if (status == AnimationStatus.completed) { _animationController.reverse(); } else if (status == AnimationStatus.dismissed) { _animationController.forward(); } }) ..forward(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Container( alignment: Alignment.center, child: DecoratedBoxTransition( decoration: DecorationTween( begin: BoxDecoration( color: Colors.blue[900], borderRadius: BorderRadius.circular(128), ), end: BoxDecoration( color: Colors.pink[900], borderRadius: BorderRadius.horizontal(), ), ).animate(_animationController), child: Container( width: 300, height: 300, ), )), ); } @override void dispose() { _animationController.dispose(); super.dispose(); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_widget.dart
import 'package:flutter/material.dart'; class MyAnimatedWidget extends StatefulWidget { final String appBarTitle; MyAnimatedWidget({ this.appBarTitle, }); @override _MyAnimatedWidgetState createState() => _MyAnimatedWidgetState(); } class _MyAnimatedWidgetState extends State<MyAnimatedWidget> with SingleTickerProviderStateMixin { Animation<double> animation; AnimationController animController; @override void initState() { super.initState(); animController = AnimationController(duration: Duration(milliseconds: 700), vsync: this); animation = Tween<double>(begin: 0, end: 16) .chain(CurveTween(curve: Curves.elasticIn)) .animate(animController) ..addStatusListener((status) { if (status == AnimationStatus.completed) { animController.reverse(); } else if (status == AnimationStatus.dismissed) { animController.forward(); } }); animController.forward(from: 0); } @override void dispose() { animController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Center( child: Wrap( children: [ CustomAnimatedWidget( animation: animation, ), ], ), ), ); } } class CustomAnimatedWidget extends AnimatedWidget { CustomAnimatedWidget({ Key key, @required Animation<double> animation, }) : super(key: key, listenable: animation); @override Widget build(BuildContext context) { final animation = listenable as Animation<double>; return AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget child) { return Container( alignment: Alignment.center, padding: EdgeInsets.only( left: animation.value + 30.0, right: 30.0 - animation.value, ), child: Container( margin: EdgeInsets.symmetric(horizontal: 24.0), padding: EdgeInsets.all(64), decoration: BoxDecoration( shape: BoxShape.rectangle, color: Colors.blue[900], borderRadius: BorderRadius.circular(12), ), ), ); }, ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/home_screen.dart
import 'package:anny/animation_align.dart'; import 'package:anny/animation_builder.dart'; import 'package:anny/animation_container.dart'; import 'package:anny/animation_cross_fade.dart'; import 'package:anny/animation_default_text_style.dart'; import 'package:anny/animation_icon.dart'; import 'package:anny/animation_list.dart'; import 'package:anny/animation_list_item.dart'; import 'package:anny/animation_opacity.dart'; import 'package:anny/animation_padding.dart'; import 'package:anny/animation_physical_model.dart'; import 'package:anny/animation_positioned.dart'; import 'package:anny/animation_switcher.dart'; import 'package:anny/animation_widget.dart'; import 'package:anny/decoration_box_transition.dart'; import 'package:anny/hero_animation.dart'; import 'package:anny/position_transition.dart'; import 'package:anny/rotation_transition.dart'; import 'package:anny/scale_transition.dart'; import 'package:anny/size_transition.dart'; import 'package:anny/slide_transition.dart'; import 'package:flutter/material.dart'; class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( 'Animation'.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: SafeArea( child: SingleChildScrollView( child: Container( padding: EdgeInsets.all( 16, ), child: Column( children: <Widget>[ InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyAnimationBuilder( appBarTitle: 'Animation Builder', ); }), ); }, child: AnimationListItem( title: 'Animation Builder', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyAnimationIcon( appBarTitle: 'Animation Icon', ); }), ); }, child: AnimationListItem( title: 'Animation Icon', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyAnimationSwitcher( appBarTitle: 'Animation Switcher', ); }), ); }, child: AnimationListItem( title: 'Animation Switcher', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyAnimatedPositioned( appBarTitle: 'Animated Position', ); }), ); }, child: AnimationListItem( title: 'Animated Position', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyAnimatedPadding( appBarTitle: 'Animated Padding', ); }), ); }, child: AnimationListItem( title: 'Animated Padding', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyAnimatedContainer( appBarTitle: 'Animated Container', ); }), ); }, child: AnimationListItem( title: 'Animated Container', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyAnimatedOpacity( appBarTitle: 'Animated Opacity', ); }), ); }, child: AnimationListItem( title: 'Animated Opacity', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyAnimatedCrossFade( appBarTitle: 'Animated CrossFade', ); }), ); }, child: AnimationListItem( title: 'Animated CrossFade', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyAnimatedWidget( appBarTitle: 'Animated Widget', ); }), ); }, child: AnimationListItem( title: 'Animated Widget', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyAnimatedDefaultTextStyle( appBarTitle: 'Animated Default TextStyle', ); }), ); }, child: AnimationListItem( title: 'Animated Default TextStyle', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyAnimatedList( appBarTitle: 'Animated List', ); }), ); }, child: AnimationListItem( title: 'Animated List', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyDecoratedBoxTransition( appBarTitle: 'Decorated Box Transition', ); }), ); }, child: AnimationListItem( title: 'Decorated Box Transition', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyHero( appBarTitle: 'Hero Animation', ); }), ); }, child: Hero( tag: Hero, child: AnimationListItem( title: 'Hero Animation', ), ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyPositionedTransition( appBarTitle: 'Position Transition', ); }), ); }, child: AnimationListItem( title: 'Position Transition', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MySlideTransition( appBarTitle: 'Slide Transition', ); }), ); }, child: AnimationListItem( title: 'Slide Transition', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MySizeTransition( appBarTitle: 'Size Transition', ); }), ); }, child: AnimationListItem( title: 'Size Transition', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyScaleTransition( appBarTitle: 'Scale Transition', ); }), ); }, child: AnimationListItem( title: 'Scale Transition', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyAnimationAlign( appBarTitle: 'Animation Align', ); }), ); }, child: AnimationListItem( title: 'Animation Align', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyRotationTransition( appBarTitle: 'Rotation Transition', ); }), ); }, child: AnimationListItem( title: 'Rotation Transition', ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (_) { return MyAnimationPhysicalModel( appBarTitle: 'Physical Model Animation', ); }), ); }, child: AnimationListItem( title: 'Physical Model Animation', ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_align.dart
import 'package:flutter/material.dart'; class MyAnimationAlign extends StatefulWidget { final String appBarTitle; MyAnimationAlign({ this.appBarTitle, }); @override _MyAnimationAlignState createState() => _MyAnimationAlignState(); } class _MyAnimationAlignState extends State<MyAnimationAlign> { AlignmentGeometry _alignment = Alignment.topRight; @override void initState() { super.initState(); } @override void dispose() { super.dispose(); } void _changeAlignment() { setState(() { _alignment = _alignment == Alignment.topRight ? Alignment.bottomLeft : Alignment.topRight; }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Container( height: 120.0, width: 120.0, color: Colors.blue[50], child: AnimatedAlign( alignment: _alignment, curve: Curves.ease, duration: Duration(seconds: 3), child: FlutterLogo( size: 60, ), ), ), FlatButton( onPressed: () { _changeAlignment(); }, child: Text( "Click Me!", ), ) ], ), ), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/scale_transition.dart
import 'package:flutter/material.dart'; class MyScaleTransition extends StatefulWidget { final String appBarTitle; const MyScaleTransition({Key key, this.appBarTitle}) : super(key: key); @override _MyScaleTransitionState createState() => _MyScaleTransitionState(); } class _MyScaleTransitionState extends State<MyScaleTransition> with SingleTickerProviderStateMixin { AnimationController _animationController; Animation<double> _animation; @override void initState() { super.initState(); /// creates animation controller with [Duration] 2 seconds and [Ticker Provider] for current context _animationController = AnimationController(duration: Duration(seconds: 2), vsync: this)..repeat(reverse: true); /// sets actual animation _animation = CurvedAnimation(curve: Curves.fastOutSlowIn, parent: _animationController); } @override void dispose() { /// disposes the animation controller _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle(color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600), ), ), body: Center( child: ScaleTransition( scale: _animation, child: FlutterLogo(size: 150), ), ), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_builder.dart
import 'package:flutter/material.dart'; class MyAnimationBuilder extends StatefulWidget { final String appBarTitle; MyAnimationBuilder({ this.appBarTitle, }); @override _MyAnimationBuilderState createState() => _MyAnimationBuilderState(); } class _MyAnimationBuilderState extends State<MyAnimationBuilder> with TickerProviderStateMixin { Animation _heartbeatAnimation; AnimationController _animationController; @override void initState() { super.initState(); /// initializing AnimationController _animationController = AnimationController( vsync: this, /// duration is the period of time the animation would last duration: Duration( seconds: 1, ), ); /// Tween is to configure an animation to interpolate to a different range or data type /// A CurvedAnimation defines progression as a non-linear curve. _heartbeatAnimation = Tween(begin: 180.0, end: 165.0).animate( CurvedAnimation( curve: Curves.easeOutBack, parent: _animationController, ), ); /// setting listener on animation and /// getting its status continuously everytime when its state changes _animationController.addStatusListener( (AnimationStatus status) { if (status == AnimationStatus.completed) { _animationController.repeat(); } }, ); /// forward starts the animation _animationController.forward(); } @override void dispose() { _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: AnimatedBuilder( animation: _animationController, builder: (BuildContext context, Widget child) { return Center( child: Container( child: Center( child: Icon( Icons.favorite, color: Colors.blue[900], /// size varies from given range in Tween size: _heartbeatAnimation.value, ), ), ), ); }, ), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/size_transition.dart
import 'package:flutter/material.dart'; class MySizeTransition extends StatefulWidget { final String appBarTitle; const MySizeTransition({Key key, this.appBarTitle}) : super(key: key); @override _MySizeTransitionState createState() => _MySizeTransitionState(); } class _MySizeTransitionState extends State<MySizeTransition> with SingleTickerProviderStateMixin { AnimationController _animationController; Animation<double> _animation; @override void initState() { super.initState(); /// creates animation controller with [Duration] 2 seconds and [Ticker Provider] for current context _animationController = AnimationController(duration: Duration(seconds: 2), vsync: this)..repeat(reverse: true); /// sets actual animation _animation = CurvedAnimation(curve: Curves.fastOutSlowIn, parent: _animationController); } @override void dispose() { /// disposes the animation controller _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle(color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600), ), ), body: SizeTransition( sizeFactor: _animation, axis: Axis.vertical, axisAlignment: -1, child: Center( child: FlutterLogo(size: 150), ), ), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_list_item.dart
import 'package:flutter/material.dart'; class AnimationListItem extends StatelessWidget { final String title; AnimationListItem({ this.title, }); @override Widget build(BuildContext context) { return Column( children: [ Container( width: MediaQuery.of(context).size.width, padding: EdgeInsets.all( 16, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( title, style: TextStyle( color: Colors.blue, letterSpacing: 0.5, fontSize: 20, fontWeight: FontWeight.w400, ), ), Icon( Icons.arrow_forward_ios, color: Colors.grey, size: 20, ), ], ), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular( 8.0, ), border: Border.all( color: Colors.blue[700], width: 3, ), ), ), SizedBox( height: 24, ) ], ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/slide_transition.dart
import 'package:flutter/material.dart'; class MySlideTransition extends StatefulWidget { final String appBarTitle; MySlideTransition({ this.appBarTitle, }); @override _MySlideTransitionState createState() => _MySlideTransitionState(); } class _MySlideTransitionState extends State<MySlideTransition> with SingleTickerProviderStateMixin { AnimationController _controller; Animation<Offset> _offsetAnimation; @override void initState() { super.initState(); _controller = AnimationController( duration: const Duration(seconds: 2), vsync: this, )..repeat(reverse: true); _offsetAnimation = Tween<Offset>( begin: Offset.zero, end: const Offset(2.0, 0.0), ).animate(CurvedAnimation( parent: _controller, curve: Curves.elasticIn, )); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Center( child: SlideTransition( position: _offsetAnimation, child: const Padding( padding: EdgeInsets.all(8.0), child: FlutterLogo(size: 150.0), ), ), ), ); } @override void dispose() { _controller.dispose(); super.dispose(); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/position_transition.dart
import 'package:flutter/material.dart'; class MyPositionedTransition extends StatefulWidget { final String appBarTitle; MyPositionedTransition({ this.appBarTitle, }); @override _MyPositionedTransitionState createState() => _MyPositionedTransitionState(); } class _MyPositionedTransitionState extends State<MyPositionedTransition> with SingleTickerProviderStateMixin { AnimationController _animationController; Animation<RelativeRect> _animation; @override void initState() { super.initState(); _animationController = AnimationController( vsync: this, duration: const Duration(milliseconds: 2000), ) ..addStatusListener((status) { if (status == AnimationStatus.completed) { _animationController.reverse(); } else if (status == AnimationStatus.dismissed) { _animationController.forward(); } }) ..forward(); _animation = new RelativeRectTween( begin: new RelativeRect.fromLTRB(64.0, 400.0, 64.0, 100.0), end: new RelativeRect.fromLTRB(150.0, 100.0, 150.0, 400.0), ).animate( CurvedAnimation( parent: _animationController, curve: Curves.easeIn, reverseCurve: Curves.easeOut), ); } @override void dispose() { _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Stack(alignment: Alignment.center, children: <Widget>[ PositionedTransition( rect: _animation, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), color: Colors.blue[900], ), ), ) ]), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_list.dart
import 'package:flutter/material.dart'; class MyAnimatedList extends StatefulWidget { final String appBarTitle; MyAnimatedList({ this.appBarTitle, }); @override _MyAnimatedListState createState() => _MyAnimatedListState(); } class _MyAnimatedListState extends State<MyAnimatedList> { GlobalKey<AnimatedListState> _listKey; List<String> _data; @override void initState() { super.initState(); _listKey = GlobalKey(); _data = ['Horse', 'Cow', 'Camel', 'Sheep', 'Goat']; } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Column( children: <Widget>[ Container( height: MediaQuery.of(context).size.height * 0.7, child: AnimatedList( key: _listKey, shrinkWrap: true, initialItemCount: _data.length, itemBuilder: (context, index, animation) { return _singleItem(_data[index], animation); }, ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ FlatButton( onPressed: () => _addOneItem(), child: Container( padding: const EdgeInsets.all(16.0), child: Text( 'Add One', style: TextStyle(color: Colors.white), ), decoration: BoxDecoration( color: Colors.blue[900], borderRadius: BorderRadius.circular(6), ), ), ), FlatButton( onPressed: () => _addManyItems(), child: Container( padding: const EdgeInsets.all(16.0), child: Text( 'Add many', style: TextStyle(color: Colors.white), ), decoration: BoxDecoration( color: Colors.blue[900], borderRadius: BorderRadius.circular(6), ), ), ), FlatButton( onPressed: () => _removeOneItem(), child: Container( padding: const EdgeInsets.all(16.0), child: Text( 'Remove One', style: TextStyle(color: Colors.white), ), decoration: BoxDecoration( color: Colors.blue[900], borderRadius: BorderRadius.circular(6), ), ), ), ], ) ], ), ); } Widget _singleItem(String item, Animation animation) { return SizeTransition( sizeFactor: animation, child: Padding( padding: const EdgeInsets.all(8.0), child: Container( child: ListTile( title: Text( item, style: TextStyle(fontSize: 24), ), ), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular( 6.0, ), border: Border.all( color: Colors.blue[700], width: 1, ), ), ), ), ); } void _addOneItem() { String item = "Human"; int insertIndex = 2; _data.insert(insertIndex, item); _listKey.currentState.insertItem(insertIndex); } void _removeOneItem() { int removeIndex = 2; String removedItem = _data.removeAt(removeIndex); // This builder is just so that the animation has something // to work with before it disappears from view since the // original has already been deleted. AnimatedListRemovedItemBuilder builder = (context, animation) { // A method to build the Card widget. return _singleItem(removedItem, animation); }; _listKey.currentState.removeItem(removeIndex, builder); } void _addManyItems() { final items = ['Rahul', 'Modi', 'Sonia']; int insertIndex = 2; _data.insertAll(insertIndex, items); // doesn't have insertAll() method. for (int offset = 0; offset < items.length; offset++) { _listKey.currentState.insertItem(insertIndex + offset); } } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_positioned.dart
import 'dart:async'; import 'dart:math'; import 'package:flutter/material.dart'; class MyAnimatedPositioned extends StatefulWidget { final String appBarTitle; MyAnimatedPositioned({ this.appBarTitle, }); @override _MyAnimatedPositionedState createState() => _MyAnimatedPositionedState(); } class _MyAnimatedPositionedState extends State<MyAnimatedPositioned> { bool selected = false; Timer timer; @override void initState() { super.initState(); timer = Timer.periodic( Duration(milliseconds: 1500), (Timer t) => changeState()); } @override void dispose() { timer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Container( height: double.infinity, width: double.infinity, child: Stack( children: <Widget>[ animatedPositionedWidget(context), ], ), ), ); } Widget animatedPositionedWidget(BuildContext context) { return AnimatedPositioned( width: (100.toDouble() + Random().nextInt(300).toDouble()), height: (50.toDouble() + Random().nextInt(400).toDouble()), top: 16 + Random().nextInt(128).toDouble(), duration: Duration(milliseconds: 800), curve: Curves.easeInOutBack, child: Padding( padding: const EdgeInsets.all(16.0), child: Container( padding: EdgeInsets.all(64), decoration: BoxDecoration( color: Colors.blue[900], borderRadius: BorderRadius.circular( 12, ), ), ), ), ); } void changeState() { setState(() {}); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_icon.dart
import 'package:flutter/material.dart'; class MyAnimationIcon extends StatefulWidget { final String appBarTitle; MyAnimationIcon({ this.appBarTitle, }); @override _MyAnimationIconState createState() => _MyAnimationIconState(); } class _MyAnimationIconState extends State<MyAnimationIcon> with TickerProviderStateMixin { AnimationController _animationController; @override void initState() { super.initState(); _animationController = AnimationController( vsync: this, duration: Duration( seconds: 2, ), ); /// setting listener on animation and /// getting its status all time when its state is changes _animationController.addStatusListener((AnimationStatus status) { if (status == AnimationStatus.completed) { _animationController.reverse(); } else if (status == AnimationStatus.dismissed) { Future.delayed(Duration(milliseconds: 500), () { _animationController.forward(); }); } }); /// to start the animation _animationController.forward(); } @override void dispose() { _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: AnimatedBuilder( animation: _animationController, builder: (BuildContext context, Widget child) { return Center( child: Wrap( children: [ Column( children: [ AnimatedIcon( size: 64.0, icon: AnimatedIcons.search_ellipsis, progress: _animationController, color: Colors.blue[900], ), SizedBox( height: 48, ), AnimatedIcon( size: 64.0, icon: AnimatedIcons.close_menu, progress: _animationController, color: Colors.blue[900], ), SizedBox( height: 48, ), AnimatedIcon( size: 64.0, icon: AnimatedIcons.menu_arrow, progress: _animationController, color: Colors.blue[900], ), ], ), ], ), ); }, ), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_container.dart
import 'dart:async'; import 'dart:math'; import 'package:flutter/material.dart'; class MyAnimatedContainer extends StatefulWidget { final String appBarTitle; MyAnimatedContainer({ this.appBarTitle, }); @override _MyAnimatedContainerState createState() => _MyAnimatedContainerState(); } class _MyAnimatedContainerState extends State<MyAnimatedContainer> { bool selected = false; Timer timer; final random = Random(); @override void initState() { super.initState(); timer = Timer.periodic( Duration(milliseconds: 1500), (Timer t) => changeState()); } @override void dispose() { timer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Center( child: AnimatedContainer( width: random.nextInt(300).toDouble(), height: random.nextInt(300).toDouble(), decoration: BoxDecoration( color: Color.fromRGBO( random.nextInt(256), random.nextInt(256), random.nextInt(256), 1, ), borderRadius: BorderRadius.circular( random.nextInt(100).toDouble(), ), ), duration: Duration( milliseconds: 800, ), curve: Curves.easeInOut, ), ), ); } void changeState() { setState(() {}); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_default_text_style.dart
import 'dart:async'; import 'package:flutter/material.dart'; class MyAnimatedDefaultTextStyle extends StatefulWidget { final String appBarTitle; MyAnimatedDefaultTextStyle({ this.appBarTitle, }); @override _MyAnimatedDefaultTextStyleState createState() => _MyAnimatedDefaultTextStyleState(); } class _MyAnimatedDefaultTextStyleState extends State<MyAnimatedDefaultTextStyle> { bool defaultState = false; Timer timer; @override void initState() { super.initState(); timer = Timer.periodic( Duration(milliseconds: 1500), (Timer t) => changeState()); } @override void dispose() { timer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Center( child: Container( height: 120, child: AnimatedDefaultTextStyle( duration: const Duration(milliseconds: 500), style: TextStyle( fontSize: defaultState ? 90 : 60, color: defaultState ? Colors.blue[900] : Colors.red[900], fontWeight: defaultState ? FontWeight.bold : FontWeight.normal, letterSpacing: defaultState ? 1 : 0.1, ), child: Text('Charcha!'), ), ), ), ); } void changeState() { setState(() { defaultState = !defaultState; }); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/main.dart
import 'package:anny/home_screen.dart'; import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Anny', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: HomeScreen(), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_examples/lib/animation_opacity.dart
import 'package:flutter/material.dart'; class MyAnimatedOpacity extends StatefulWidget { final String appBarTitle; MyAnimatedOpacity({ this.appBarTitle, }); @override _MyAnimatedOpacityState createState() => _MyAnimatedOpacityState(); } class _MyAnimatedOpacityState extends State<MyAnimatedOpacity> { bool selected = false; @override void initState() { super.initState(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( centerTitle: true, title: Text( widget.appBarTitle.toUpperCase(), style: TextStyle( color: Colors.white, letterSpacing: 1, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), body: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ InkWell( onTap: () => { setState(() { selected = !selected; }) }, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Checkbox( onChanged: (bool value) { setState(() { selected = value; }); }, value: selected, ), Container( width: MediaQuery.of(context).size.width * 0.85, child: Text( 'Please check this box to get started', style: TextStyle( fontSize: 24, letterSpacing: 1, fontWeight: FontWeight.w600, ), ), ) ], ), ), SizedBox( height: 64, ), Padding( padding: const EdgeInsets.all(16.0), child: AnimatedOpacity( duration: Duration(milliseconds: 500), opacity: selected ? 1 : 0.5, child: Container( height: 64, width: MediaQuery.of(context).size.width, decoration: BoxDecoration( color: Colors.blue[900], borderRadius: BorderRadius.circular(12), ), child: Center( child: AnimatedOpacity( duration: Duration(milliseconds: 800), opacity: selected ? 1 : 0, child: Text( 'Start', style: TextStyle( fontSize: 24, letterSpacing: 1, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ), ), ), ), ], ), ), ); } }
0
mirrored_repositories/flutter-animation_examples
mirrored_repositories/flutter-animation_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:anny/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_music
mirrored_repositories/flutter_music/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:musicplayer/src/models/audioplayer_model.dart'; import 'package:musicplayer/src/pages/music_player_page.dart'; import 'package:musicplayer/src/theme/theme.dart'; import 'package:provider/provider.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setPreferredOrientations( [DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]).then((_) { runApp( MyApp(), ); }); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider( create: (_) => new AudioPlayerModel(), ) ], child: MaterialApp( debugShowCheckedModeBanner: false, title: 'Music Player', theme: miTema, home: MusicPlayerPage(), ), ); } }
0
mirrored_repositories/flutter_music/lib/src
mirrored_repositories/flutter_music/lib/src/widgets/custom_appbar.dart
import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; class CustomAppBar extends StatelessWidget { @override Widget build(BuildContext context) { return SafeArea( child: Container( margin: EdgeInsets.only(top: 30), child: Row( children: <Widget>[ Icon(FontAwesomeIcons.chevronLeft), Spacer(), Icon(FontAwesomeIcons.commentAlt), SizedBox(width: 20), Icon(FontAwesomeIcons.headphonesAlt), SizedBox(width: 20), Icon(FontAwesomeIcons.externalLinkAlt), ], ), ), ); } }
0
mirrored_repositories/flutter_music/lib/src
mirrored_repositories/flutter_music/lib/src/pages/music_player_page.dart
import 'package:animate_do/animate_do.dart'; import 'package:assets_audio_player/assets_audio_player.dart'; import 'package:flutter/material.dart'; import 'package:musicplayer/src/helpers/helpers.dart'; import 'package:musicplayer/src/models/audioplayer_model.dart'; import 'package:musicplayer/src/widgets/custom_appbar.dart'; import 'package:provider/provider.dart'; class MusicPlayerPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Stack( children: <Widget>[ Background(), Column( children: <Widget>[ CustomAppBar(), ImagenDiscoDuracion(), TituloPlay(), Expanded( child: Lyrics(), ), ], ), ], ), ); } } class Background extends StatelessWidget { @override Widget build(BuildContext context) { final screenSize = MediaQuery.of(context).size; return Container( width: double.infinity, height: screenSize.height * 0.8, decoration: BoxDecoration( borderRadius: BorderRadius.only(bottomLeft: Radius.circular(60)), gradient: LinearGradient( begin: Alignment.centerLeft, end: Alignment.center, colors: [ Color(0xff33333E), Color(0xff201E28), ], ), ), ); } } class Lyrics extends StatelessWidget { @override Widget build(BuildContext context) { final lyrics = getLyrics(); return Container( child: ListWheelScrollView( physics: BouncingScrollPhysics(), itemExtent: 42, diameterRatio: 1.5, children: lyrics .map((linea) => Text( linea, style: TextStyle( fontSize: 20, color: Colors.white.withOpacity(0.6), ), )) .toList(), ), ); } } class TituloPlay extends StatefulWidget { @override _TituloPlayState createState() => _TituloPlayState(); } class _TituloPlayState extends State<TituloPlay> with SingleTickerProviderStateMixin { bool isPlaying = false; bool firstTime = true; AnimationController playAnimation; final assetAudioPlayer = new AssetsAudioPlayer(); @override void initState() { // TODO: implement initState playAnimation = AnimationController( vsync: this, duration: Duration(milliseconds: 500), ); super.initState(); } @override void dispose() { // TODO: implement dispose this.playAnimation.dispose(); super.dispose(); } void open() { final audioPlayerModel = Provider.of<AudioPlayerModel>(context, listen: false); assetAudioPlayer.open(Audio('assets/white_old.flac')); assetAudioPlayer.currentPosition.listen((duration) { audioPlayerModel.current = duration; }); assetAudioPlayer.current.listen((playingAudio) { audioPlayerModel.songDuration = playingAudio.audio.duration; }); } @override Widget build(BuildContext context) { return Container( padding: EdgeInsets.symmetric(horizontal: 40), margin: EdgeInsets.only(top: 40), child: Row( children: <Widget>[ Column( children: <Widget>[ Text( 'White Owl', style: TextStyle( fontSize: 30, color: Colors.white.withOpacity(0.8), ), ), Text( 'Josh Garrels', style: TextStyle( fontSize: 15, color: Colors.white.withOpacity(0.5), ), ), ], ), Spacer(), FloatingActionButton( elevation: 0, highlightElevation: 0, backgroundColor: Color(0xffF8CB51), child: AnimatedIcon( icon: AnimatedIcons.play_pause, progress: playAnimation, ), onPressed: () { //TODO: Botón final audioPlayerModel = Provider.of<AudioPlayerModel>(context, listen: false); if (this.isPlaying) { playAnimation.reverse(); this.isPlaying = false; audioPlayerModel.controller.stop(); } else { playAnimation.forward(); this.isPlaying = true; audioPlayerModel.controller.repeat(); } if (firstTime) { this.open(); firstTime = false; } else { assetAudioPlayer.playOrPause(); } }, ) ], ), ); } } class ImagenDiscoDuracion extends StatelessWidget { @override Widget build(BuildContext context) { return Container( child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ //TODO: Disco // SizedBox(width: 20), BarraProgreso(), //TODO: Barra progreso // SizedBox(width: 10), ImagenDisco(), ], ), ); } } class BarraProgreso extends StatelessWidget { @override Widget build(BuildContext context) { final estilo = TextStyle(color: Colors.white.withOpacity(0.4)); final audioPlayerModel = Provider.of<AudioPlayerModel>(context); final porcentaje = audioPlayerModel.porcentaje; return Container( child: Column( children: <Widget>[ Text('${audioPlayerModel.songTotalDuration}', style: estilo), SizedBox(height: 10), Stack( children: <Widget>[ Container( width: 3, height: 230, color: Colors.white.withOpacity(0.1), ), Positioned( bottom: 0, child: Container( width: 3, height: 230 * porcentaje, color: Colors.white.withOpacity(0.8), ), ), ], ), SizedBox(height: 10), Text('${audioPlayerModel.currentSecond}', style: estilo), ], ), ); } } class ImagenDisco extends StatelessWidget { @override Widget build(BuildContext context) { final audioPlayerModel = Provider.of<AudioPlayerModel>(context); return Container( padding: EdgeInsets.all(20), width: 250, height: 250, child: ClipRRect( borderRadius: BorderRadius.circular(200), child: Stack( alignment: Alignment.center, children: <Widget>[ SpinPerfect( duration: Duration(seconds: 10), infinite: true, manualTrigger: true, controller: (animationController) => audioPlayerModel.controller = animationController, child: Image( image: AssetImage('assets/josh.jpg'), ), ), Container( width: 25, height: 25, decoration: BoxDecoration( color: Colors.black38, borderRadius: BorderRadius.circular(100), ), ), Container( width: 18, height: 18, decoration: BoxDecoration( color: Color(0xff1C1C25), borderRadius: BorderRadius.circular(100), ), ), ], ), ), decoration: BoxDecoration( borderRadius: BorderRadius.circular(200), gradient: LinearGradient( begin: Alignment.topLeft, colors: [ Color(0xff484750), Color(0xff1E1C24), ], ), ), ); } }
0
mirrored_repositories/flutter_music/lib/src
mirrored_repositories/flutter_music/lib/src/models/audioplayer_model.dart
import 'package:flutter/material.dart'; class AudioPlayerModel with ChangeNotifier { bool _playing = false; Duration _songDuration = new Duration(microseconds: 0); Duration _current = new Duration(microseconds: 0); String get songTotalDuration => this.printDuration(this._songDuration); String get currentSecond => this.printDuration(this._current); double get porcentaje => (this._songDuration.inSeconds > 0) ? this._current.inSeconds / this._songDuration.inSeconds : 0; AnimationController _controller; set controller(AnimationController valor) { this._controller = valor; } AnimationController get controller => this._controller; bool get playing => this._playing; set playing(bool valor) { this._playing = valor; notifyListeners(); } Duration get songDuration => this._songDuration; set songDuration(Duration valor) { this._songDuration = valor; notifyListeners(); } Duration get current => this._current; set current(Duration valor) { this._current = valor; notifyListeners(); } String printDuration(Duration duration) { String twoDigits(int n) { if (n >= 10) return '$n'; return '0$n'; } String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60)); String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60)); return '$twoDigitMinutes:$twoDigitSeconds'; } }
0
mirrored_repositories/flutter_music/lib/src
mirrored_repositories/flutter_music/lib/src/theme/theme.dart
import 'package:flutter/material.dart'; final miTema = ThemeData.dark().copyWith( scaffoldBackgroundColor: Color(0xff201E28), // scaffoldBackgroundColor: Color(0xfff40404C), iconTheme: IconThemeData(color: Colors.white.withOpacity(0.3)));
0
mirrored_repositories/flutter_music/lib/src
mirrored_repositories/flutter_music/lib/src/helpers/helpers.dart
List<String> getLyrics() { return [ 'When the night comes', 'And you dont know which way to go', 'Through the shadowlands', 'And forgotten paths', 'You will find a road', 'Like an owl you must fly in moonlight with an open eye', 'And use your instinct as your guide', 'To navigate the ways that lays before you', 'You were born to, take the greatest flight', 'Like a serpent and a dove, you will have wisdom born of love', 'And carry visions from above into the places no man dares to follow', 'Every hollow in the dark of night', 'Waiting for the light', 'Take the flame tonight', 'Cause child the time has come for you to go', 'You will never be alone', 'Every dream that you have been shown', 'Will be like living stone', 'Building you into a home', 'A shelter from the storm', 'Like a messenger of peace, the beauty waits to be released', 'Upon the sacred path you keep, leading deeper into the unveiling', 'As your sailing, across the great divide', 'Like a wolf at midnight howls, you use your voice in darkest hours', 'To break the silence and the power,', 'Holding back the others from their glory', 'Every story will be written soon', 'The blood is on the moon', 'Morning will come soon', 'Cause child the time has come for you to go', 'You will never be alone', ' Every dream that you have been shown', 'Will be like living stone', 'Building you into a home', 'A shelter from the storm' ]; }
0
mirrored_repositories/flutter_music
mirrored_repositories/flutter_music/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:musicplayer/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/paulina_knop
mirrored_repositories/paulina_knop/lib/routes.dart
import 'package:flutter/material.dart'; import 'package:paulina_knop/common/blog.dart'; import 'package:paulina_knop/mobile/about_mobile.dart'; import 'package:paulina_knop/mobile/contact_mobile.dart'; import 'package:paulina_knop/mobile/works_mobile.dart'; import 'package:paulina_knop/web/about_web.dart'; import 'package:paulina_knop/web/landing_page_web.dart'; import 'package:paulina_knop/web/works_web.dart'; import 'mobile/landing_page_mobile.dart'; import 'web/contact_web.dart'; class Routes { static Route<dynamic> generateRoute(RouteSettings settings) { switch (settings.name) { case '/': return MaterialPageRoute( settings: settings, builder: (_) => LayoutBuilder(builder: (context, constraints) { if (constraints.maxWidth > 800) { return LandingPageWeb(); } else return LandingPageMobile(); }), ); case '/contact': return MaterialPageRoute( builder: (_) => LayoutBuilder(builder: (context, constraints) { if (constraints.maxWidth > 800) { return ContactWeb(); } else return ContactMobile(); }), settings: settings); case '/about': return MaterialPageRoute( builder: (_) => LayoutBuilder(builder: (context, constraints) { if (constraints.maxWidth > 800) { return AboutWeb(); } else return AboutMobile(); }), settings: settings); case '/blog': return MaterialPageRoute(builder: (_) => Blog(), settings: settings); case '/works': return MaterialPageRoute( builder: (_) => LayoutBuilder(builder: (context, constraints) { if (constraints.maxWidth > 800) { return WorksWeb(); } else return WorksMobile(); }), settings: settings); default: return MaterialPageRoute( settings: settings, builder: (_) => LayoutBuilder(builder: (context, constraints) { if (constraints.maxWidth > 800) { return LandingPageWeb(); } else return LandingPageMobile(); }), ); } } }
0
mirrored_repositories/paulina_knop
mirrored_repositories/paulina_knop/lib/components.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:logger/logger.dart'; import 'package:url_launcher/url_launcher.dart'; //Variables var logger = Logger(); final TextEditingController _firstNameController = TextEditingController(); final TextEditingController _lastNameController = TextEditingController(); final TextEditingController _emailController = TextEditingController(); final TextEditingController _phoneController = TextEditingController(); final TextEditingController _messageController = TextEditingController(); //Classes and methods class TabsWeb extends StatefulWidget { final title; final route; const TabsWeb({Key? key, this.title, this.route}) : super(key: key); @override _TabsWebState createState() => _TabsWebState(); } class _TabsWebState extends State<TabsWeb> { bool isSelected = false; @override Widget build(BuildContext context) { return GestureDetector( onTap: () { Navigator.of(context).pushNamed(widget.route); }, child: MouseRegion( onEnter: (_) { setState(() { isSelected = true; }); // print("Entered"); }, onExit: (_) { setState(() { isSelected = false; }); // print("Exit"); }, child: AnimatedDefaultTextStyle( duration: const Duration(milliseconds: 100), curve: Curves.elasticIn, style: isSelected ? GoogleFonts.roboto( shadows: [ Shadow( color: Colors.black, offset: Offset(0, -8), ), ], fontSize: 25.0, color: Colors.transparent, decoration: TextDecoration.underline, decorationThickness: 2, decorationColor: Colors.tealAccent) : GoogleFonts.roboto(color: Colors.black, fontSize: 20.0), child: Text(widget.title), ), ), ); } } class TabsWebList extends StatefulWidget { const TabsWebList({Key? key}) : super(key: key); @override State<TabsWebList> createState() => _TabsWebListState(); } class _TabsWebListState extends State<TabsWebList> { @override Widget build(BuildContext context) { return Row( children: [ Spacer( flex: 3, ), TabsWeb( title: "Home", route: '/', ), Spacer(), TabsWeb( title: "Works", route: '/works', ), Spacer(), TabsWeb( title: "Blog", route: '/blog', ), Spacer(), TabsWeb( title: "About", route: '/about', ), Spacer(), TabsWeb( title: 'Contact', route: '/contact', ), Spacer() ], ); } } class TabsMobile extends StatefulWidget { final text; final route; const TabsMobile({Key? key, @required this.text, @required this.route}) : super(key: key); @override _TabsMobileState createState() => _TabsMobileState(); } class _TabsMobileState extends State<TabsMobile> { @override Widget build(BuildContext context) { return MaterialButton( elevation: 20.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5.0), ), height: 50.0, minWidth: 200.0, color: Colors.black, child: Text( widget.text, style: GoogleFonts.openSans(fontSize: 20.0, color: Colors.white), ), onPressed: () { Navigator.of(context).pushNamed(widget.route); }, ); } } urlLauncher(String imgPath, String url) { return IconButton( icon: SvgPicture.asset(imgPath, color: Colors.black, width: 35), onPressed: () async { await launchUrl(Uri.parse(url)); }, ); } class DrawersWeb extends StatelessWidget { const DrawersWeb({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Drawer( backgroundColor: Colors.white, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircleAvatar( radius: 72.0, backgroundColor: Colors.tealAccent, child: CircleAvatar( radius: 70.0, backgroundColor: Colors.white, backgroundImage: AssetImage("assets/image.png"), ), ), SizedBox(height: 15.0), SansBold("Paulina Knop", 30.0), SizedBox(height: 15.0), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ urlLauncher("assets/instagram.svg", "https://www.instagram.com/tomcruise/"), urlLauncher( "assets/twitter.svg", "https://www.twitter.com/tomcruise"), urlLauncher("assets/github.svg", "https://github.com/sagnik150699/paulina_knop"), ], ), ], ), ); } } class DrawersMobile extends StatelessWidget { const DrawersMobile({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Drawer( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ DrawerHeader( padding: EdgeInsets.only(bottom: 20.0), child: Container( decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all(width: 2.0, color: Colors.black)), child: Image.asset( 'assets/profile2-circle.png', filterQuality: FilterQuality.high, ), ), ), TabsMobile(text: "Home", route: '/'), SizedBox(height: 20.0), TabsMobile(text: "Works", route: '/works'), SizedBox(height: 20.0), TabsMobile(text: "Blog", route: '/blog'), SizedBox(height: 20.0), TabsMobile(text: "About", route: '/about'), SizedBox(height: 20.0), TabsMobile(text: "Contact", route: '/contact'), SizedBox(height: 40.0), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ urlLauncher("assets/instagram.svg", "https://www.instagram.com/tomcruise/"), urlLauncher( "assets/twitter.svg", "https://www.twitter.com/tomcruise"), urlLauncher("assets/github.svg", "https://github.com/sagnik150699/paulina_knop"), ], ) ], ), ); } } class SansBold extends StatelessWidget { final text; final size; const SansBold(this.text, this.size, {Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Text( text, style: GoogleFonts.openSans(fontSize: size, fontWeight: FontWeight.bold), ); } } class Sans extends StatelessWidget { final text; final size; const Sans(this.text, this.size, {Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Text( text, style: GoogleFonts.openSans(fontSize: size), ); } } class AbelCustom extends StatelessWidget { final text; final size; final color; final fontWeight; const AbelCustom( {Key? key, @required this.text, @required this.size, this.color, this.fontWeight}) : super(key: key); @override Widget build(BuildContext context) { return Text( text, style: GoogleFonts.abel( fontSize: size, color: color == null ? Colors.black : color, fontWeight: fontWeight == null ? FontWeight.normal : fontWeight), ); } } class TextForm extends StatelessWidget { final text; final containerWidth; final hintText; final maxLines; final controller; final validator; const TextForm( {Key? key, @required this.text, @required this.containerWidth, @required this.hintText, this.maxLines, @required this.controller, this.validator}) : super(key: key); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Sans(text, 16.0), SizedBox(height: 5), SizedBox( width: containerWidth, child: TextFormField( validator: validator, controller: controller, maxLines: maxLines == null ? null : maxLines, decoration: InputDecoration( errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), borderRadius: BorderRadius.all(Radius.circular(10.0)), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), borderRadius: BorderRadius.all(Radius.circular(15.0)), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.teal), borderRadius: BorderRadius.all(Radius.circular(10.0)), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.tealAccent, width: 2.0), borderRadius: BorderRadius.all(Radius.circular(15.0)), ), hintText: hintText, hintStyle: GoogleFonts.poppins(fontSize: 14), ), ), ), ], ); } } class AnimatedCard extends StatefulWidget { final imagePath; final text; final fit; final reverse; final height; final width; const AnimatedCard( {Key? key, @required this.imagePath, this.text, this.fit, this.reverse, this.height, this.width}) : super(key: key); @override _AnimatedCardState createState() => _AnimatedCardState(); } class _AnimatedCardState extends State<AnimatedCard> with SingleTickerProviderStateMixin { late AnimationController _controller = AnimationController( vsync: this, duration: const Duration(seconds: 4), )..repeat(reverse: true); late Animation<Offset> _animation = Tween( begin: widget.reverse == true ? Offset(0, 0.08) : Offset.zero, end: widget.reverse == true ? Offset.zero : Offset(0, 0.08), ).animate(_controller); @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return SlideTransition( position: _animation, child: Card( elevation: 30.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15.0), side: BorderSide(color: Colors.tealAccent), ), shadowColor: Colors.tealAccent, child: Padding( padding: const EdgeInsets.all(15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Image.asset( widget.imagePath, height: widget.height == null ? 200.0 : widget.height, width: widget.width == null ? 200.0 : widget.width, fit: widget.fit == null ? null : widget.fit, ), SizedBox(height: 10.0), widget.text == null ? SizedBox() : SansBold(widget.text, 15.0), ], ), ), ), ); } } class AddDataFirestore { CollectionReference response = FirebaseFirestore.instance.collection('messages'); Future addResponse(final firstName, final lastName, final email, final phoneNumber, final message) async { return response.add({ 'first name': firstName, 'last name': lastName, 'email': email, 'phone number': phoneNumber, 'message': message }).then((value) { logger.d("Success"); return true; }).catchError((error) { logger.d(error); return false; }); } } Future DialogError(BuildContext context, String title) { return showDialog( context: context, builder: (BuildContext context) => AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0)), title: SansBold(title, 20.0), )); } class ContactFormWeb extends StatefulWidget { const ContactFormWeb({Key? key}) : super(key: key); @override State<ContactFormWeb> createState() => _ContactFormWebState(); } class _ContactFormWebState extends State<ContactFormWeb> { final formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { var widthDevice = MediaQuery.of(context).size.width; return Form( key: formKey, child: Column( children: [ SizedBox(height: 30.0), SansBold("Contact me", 40.0), SizedBox(height: 20.0), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Column( children: [ TextForm( text: "First Name", containerWidth: 350.0, hintText: "Please type first name", controller: _firstNameController, validator: (text) { if (text.toString().isEmpty) { return "First name is required"; } }, ), SizedBox(height: 15.0), TextForm( text: "Email", containerWidth: 350.0, hintText: "Please type email address", controller: _emailController, validator: (text) { if (text.toString().isEmpty) { return "Email is required"; } }), ], ), Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ TextForm( text: "Last Name", containerWidth: 350.0, hintText: "Please type last name", controller: _lastNameController, ), SizedBox(height: 15.0), TextForm( text: "Phone number", containerWidth: 350.0, hintText: "Please type phone number", controller: _phoneController, ) ], ), ], ), SizedBox(height: 20.0), TextForm( text: "Message", containerWidth: widthDevice / 1.5, hintText: "Please type your message", maxLines: 10, controller: _messageController, validator: (text) { if (text.toString().isEmpty) { return "Message is required"; } }, ), SizedBox(height: 20.0), MaterialButton( onPressed: () async { logger.d(_firstNameController.text); final addData = new AddDataFirestore(); if (formKey.currentState!.validate()) { if (await addData.addResponse( _firstNameController.text, _lastNameController.text, _emailController.text, _phoneController.text, _messageController.text)) { formKey.currentState!.reset(); DialogError(context, "Message sent successfully"); } else { DialogError(context, "Message failed to sent"); } } }, elevation: 20.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0)), height: 60.0, minWidth: 200.0, color: Colors.tealAccent, child: SansBold("Submit", 20.0), ), SizedBox(height: 10.0) ], ), ); } } class ContactFormMobile extends StatefulWidget { const ContactFormMobile({Key? key}) : super(key: key); @override State<ContactFormMobile> createState() => _ContactFormMobileState(); } class _ContactFormMobileState extends State<ContactFormMobile> { final formKey = GlobalKey<FormState>(); // final TextEditingController _firstNameController = TextEditingController(); // final TextEditingController _lastNameController = TextEditingController(); // final TextEditingController _emailController = TextEditingController(); // final TextEditingController _phoneController = TextEditingController(); // final TextEditingController _messageController = TextEditingController(); // final formKey = GlobalKey<FormState>(); // var logger = Logger(); @override Widget build(BuildContext context) { var widthDevice = MediaQuery.of(context).size.width; return Form( key: formKey, child: Wrap( runSpacing: 20.0, spacing: 20.0, alignment: WrapAlignment.center, children: [ SansBold("Contact me", 35.0), TextForm( text: "First name", containerWidth: widthDevice / 1.4, hintText: "Please type first name", controller: _firstNameController, validator: (text) { if (text.toString().isEmpty) { return "First name is required"; } }, ), TextForm( text: "Last name", containerWidth: widthDevice / 1.4, hintText: "Please type last name", controller: _lastNameController, ), TextForm( text: "Phone number", containerWidth: widthDevice / 1.4, hintText: "Please type phone number", controller: _phoneController, ), TextForm( text: "Email", containerWidth: widthDevice / 1.4, hintText: "Please type email address", controller: _emailController, validator: (text) { if (text.toString().isEmpty) { return "Email is required"; } }), TextForm( text: "Message", containerWidth: widthDevice / 1.4, hintText: "Please type your message", maxLines: 10, controller: _messageController, validator: (text) { if (text.toString().isEmpty) { return "Message is required"; } }, ), MaterialButton( onPressed: () async { logger.d(_firstNameController.text); final addData = new AddDataFirestore(); if (formKey.currentState!.validate()) { if (await addData.addResponse( _firstNameController.text, _lastNameController.text, _emailController.text, _phoneController.text, _messageController.text)) { formKey.currentState!.reset(); DialogError(context, "Message sent successfully"); } else { DialogError(context, "Message failed to sent"); } } }, elevation: 20.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), height: 60.0, minWidth: widthDevice / 2.2, color: Colors.tealAccent, child: SansBold("Submit", 20.0), ) ], ), ); } } tealContainer(String text) { return Container( decoration: BoxDecoration( border: Border.all( color: Colors.tealAccent, style: BorderStyle.solid, width: 2.0, ), borderRadius: BorderRadius.circular(5.0)), padding: EdgeInsets.all(7.0), child: Text( text, style: GoogleFonts.openSans(fontSize: 15.0), ), ); }
0
mirrored_repositories/paulina_knop
mirrored_repositories/paulina_knop/lib/firebase_options.dart
// File generated by FlutterFire CLI. // ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb, TargetPlatform; /// Default [FirebaseOptions] for use with your Firebase apps. /// /// Example: /// ```dart /// import 'firebase_options.dart'; /// // ... /// await Firebase.initializeApp( /// options: DefaultFirebaseOptions.currentPlatform, /// ); /// ``` class DefaultFirebaseOptions { static FirebaseOptions get currentPlatform { if (kIsWeb) { return web; } switch (defaultTargetPlatform) { case TargetPlatform.android: return android; case TargetPlatform.iOS: return ios; case TargetPlatform.macOS: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for macos - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); case TargetPlatform.windows: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for windows - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); case TargetPlatform.linux: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for linux - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); default: throw UnsupportedError( 'DefaultFirebaseOptions are not supported for this platform.', ); } } static const FirebaseOptions web = FirebaseOptions( apiKey: 'AIzaSyDV6TiAOypowEIwKiBPd46nYNIHZU2Lw14', appId: '1:555718417628:web:de754578937e1dab4be819', messagingSenderId: '555718417628', projectId: 'portfolio-782e9', authDomain: 'portfolio-782e9.firebaseapp.com', storageBucket: 'portfolio-782e9.appspot.com', measurementId: 'G-DMWX170PZ9', ); static const FirebaseOptions android = FirebaseOptions( apiKey: 'AIzaSyCJemnZV4Seo9n_atjl-FIrGEKa1yf95Ww', appId: '1:555718417628:android:327bc09099557d664be819', messagingSenderId: '555718417628', projectId: 'portfolio-782e9', storageBucket: 'portfolio-782e9.appspot.com', ); static const FirebaseOptions ios = FirebaseOptions( apiKey: 'AIzaSyCwUlLQUxAmcu6-k3onacgaUX_8DrZqwkw', appId: '1:555718417628:ios:b6c3e43ba75d4f8e4be819', messagingSenderId: '555718417628', projectId: 'portfolio-782e9', storageBucket: 'portfolio-782e9.appspot.com', iosClientId: '555718417628-v5r90hccobuaf7jhs6p5ahbpbh28cnk3.apps.googleusercontent.com', iosBundleId: 'com.codingliquids.paulinaKnop', ); }
0
mirrored_repositories/paulina_knop
mirrored_repositories/paulina_knop/lib/main.dart
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:paulina_knop/routes.dart'; import 'package:url_strategy/url_strategy.dart'; import 'firebase_options.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); setPathUrlStrategy(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, onGenerateRoute: (settings) => Routes.generateRoute(settings), initialRoute: '/', ); } }
0
mirrored_repositories/paulina_knop/lib
mirrored_repositories/paulina_knop/lib/mobile/contact_mobile.dart
import 'package:flutter/material.dart'; import '../components.dart'; class ContactMobile extends StatefulWidget { const ContactMobile({Key? key}) : super(key: key); @override State<ContactMobile> createState() => _ContactMobileState(); } class _ContactMobileState extends State<ContactMobile> { @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( extendBodyBehindAppBar: true, backgroundColor: Colors.white, endDrawer: DrawersMobile(), body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( expandedHeight: 400.0, backgroundColor: Colors.white, iconTheme: IconThemeData(size: 35.0, color: Colors.black), flexibleSpace: FlexibleSpaceBar( background: Image.asset( "assets/contact_image.jpg", fit: BoxFit.cover, ), ), ) ]; }, body: SingleChildScrollView( padding: EdgeInsets.symmetric(vertical: 25.0), child: ContactFormMobile(), ), ), ), ); } }
0
mirrored_repositories/paulina_knop/lib
mirrored_repositories/paulina_knop/lib/mobile/works_mobile.dart
import 'package:flutter/material.dart'; import '../components.dart'; class WorksMobile extends StatefulWidget { const WorksMobile({Key? key}) : super(key: key); @override State<WorksMobile> createState() => _WorksMobileState(); } class _WorksMobileState extends State<WorksMobile> { @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( extendBodyBehindAppBar: true, backgroundColor: Colors.white, endDrawer: DrawersMobile(), body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( expandedHeight: 400.0, backgroundColor: Colors.white, iconTheme: IconThemeData(size: 35.0, color: Colors.black), flexibleSpace: FlexibleSpaceBar( background: Image.asset( "assets/works.jpg", fit: BoxFit.cover, ), ), ) ]; }, body: ListView( children: [ Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox(height: 20.0), SansBold("Works", 35.0), SizedBox(height: 20.0), AnimatedCard( imagePath: "assets/portfolio_screenshot.PNG", fit: BoxFit.contain, height: 150.0, width: 300.0, ), SizedBox(height: 30.0), SansBold("Portfolio", 20.0), SizedBox(height: 10.0), Padding( padding: const EdgeInsets.symmetric(horizontal: 20.0), child: Sans( "Deployed on Android, IOS and Web, the portfolio project was truly an achievement. I used Flutter to develop the beautiful and responsive UI and Firebase for the back-end.", 15.0), ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/paulina_knop/lib
mirrored_repositories/paulina_knop/lib/mobile/about_mobile.dart
import 'package:flutter/material.dart'; import '../components.dart'; class AboutMobile extends StatefulWidget { const AboutMobile({Key? key}) : super(key: key); @override State<AboutMobile> createState() => _AboutMobileState(); } class _AboutMobileState extends State<AboutMobile> { @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( extendBodyBehindAppBar: true, backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0.0, iconTheme: IconThemeData(size: 35.0, color: Colors.black), ), endDrawer: DrawersMobile(), body: Padding( padding: const EdgeInsets.symmetric(horizontal: 20.0), child: ListView( children: [ //Introduction, first section CircleAvatar( radius: 117.0, backgroundColor: Colors.tealAccent, child: CircleAvatar( radius: 113.0, backgroundColor: Colors.black, child: CircleAvatar( radius: 110.0, backgroundColor: Colors.white, child: Image.asset( "assets/profile2-circle.png", filterQuality: FilterQuality.high, ), ), ), ), SizedBox(height: 20.0), Padding( padding: EdgeInsets.symmetric(horizontal: 20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ SansBold("About me", 35.0), SizedBox(height: 10.0), Sans( "Hello! I'm Paulina Knop I specialize in flutter development", 15.0), Sans( "I strive to ensure astounding performance with state of ", 15.0), Sans("the art security for Android, Ios, Web, Mac,Linux", 15.0), SizedBox(height: 15.0), Wrap( spacing: 7.0, runSpacing: 7.0, children: [ tealContainer("Flutter"), tealContainer("Firebase"), tealContainer("Android"), tealContainer("Windows"), ], ) ], ), ), SizedBox(height: 40.0), //Web development, second section Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ AnimatedCard( imagePath: "assets/webL.png", width: 200.0, ), SizedBox( height: 30.0, ), SansBold("Web development", 20.0), SizedBox(height: 10.0), ], ), Sans( "I'm here to build your presence online with state of the art web apps", 15.0), //App development, third section Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox( height: 20.0, ), AnimatedCard( imagePath: "assets/app.png", width: 200.0, reverse: true, ), SizedBox( height: 30.0, ), SansBold("App development.", 20.0), SizedBox( height: 10.0, ), ], ), Sans( "Do you need a high-performance, responsive and beautiful app? Don't worry, I've got you covered.", 15.0), //Back end development, forth section Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox( height: 20.0, ), AnimatedCard( imagePath: "assets/firebase.png", width: 200.0, ), SizedBox( height: 30.0, ), SansBold("Back-end development.", 20.0), SizedBox( height: 10.0, ), ], ), Sans( "Do you want your back-end to be highly scalable and secure? Let's have a conversation on how I can help you with that.", 15.0), SizedBox( height: 20.0, ) ], ), ), ), ); } }
0
mirrored_repositories/paulina_knop/lib
mirrored_repositories/paulina_knop/lib/mobile/landing_page_mobile.dart
import 'package:flutter/material.dart'; import 'package:paulina_knop/components.dart'; class LandingPageMobile extends StatefulWidget { const LandingPageMobile({Key? key}) : super(key: key); @override _LandingPageMobileState createState() => _LandingPageMobileState(); } class _LandingPageMobileState extends State<LandingPageMobile> { @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( extendBodyBehindAppBar: true, backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0.0, iconTheme: IconThemeData(size: 35.0, color: Colors.black), ), endDrawer: DrawersMobile(), body: ListView( children: [ //Intro, First section CircleAvatar( radius: 117.0, backgroundColor: Colors.tealAccent, child: CircleAvatar( radius: 113.0, backgroundColor: Colors.black, child: CircleAvatar( radius: 110.0, backgroundColor: Colors.white, backgroundImage: AssetImage("assets/image-circle.png"), ), ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 25.0), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( decoration: BoxDecoration( color: Colors.tealAccent, borderRadius: BorderRadius.only( topLeft: Radius.circular(20.0), topRight: Radius.circular(20.0), bottomRight: Radius.circular(20.0))), padding: EdgeInsets.symmetric( vertical: 10.0, horizontal: 20.0), child: SansBold("Hello I'm", 15.0), ), SansBold("Paulina Knop", 40.0), Sans("Flutter developer", 20.0), ], ), SizedBox(height: 15.0), Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Wrap( direction: Axis.vertical, spacing: 3.0, children: [ Icon(Icons.email), Icon(Icons.call), Icon(Icons.location_pin), ], ), SizedBox(width: 40.0), Wrap( direction: Axis.vertical, spacing: 9.0, children: [ Sans("paulinaknop@gmail.com", 15.0), Sans("+48 942 564 985", 15.0), Sans("13/3, Szczecin, Poland", 15.0), ], ) ], ) ], ), ), SizedBox(height: 90.0), //About me, Second section Padding( padding: EdgeInsets.symmetric(horizontal: 20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ SansBold("About me", 35.0), Sans( "Hello! I'm Paulina Knop I specialize in flutter development", 15.0), Sans( "I strive to ensure astounding performance with state of ", 15.0), Sans("the art security for Android, Ios, Web, Mac,Linux", 15.0), SizedBox(height: 10.0), Wrap( spacing: 7.0, runSpacing: 7.0, children: [ tealContainer("Flutter"), tealContainer("Firebase"), tealContainer("Android"), tealContainer("Windows"), ], ) ], ), ), SizedBox(height: 60.0), //Third section What I do? Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ SansBold("What I do?", 35.0), AnimatedCard( imagePath: "assets/webL.png", text: "Web development", width: 300.0, ), SizedBox(height: 35.0), AnimatedCard( imagePath: "assets/app.png", text: "App development", fit: BoxFit.contain, reverse: true, width: 300.0, ), SizedBox(height: 35.0), AnimatedCard( imagePath: "assets/firebase.png", text: "Back-end development", width: 300.0, ), SizedBox(height: 60.0), //Contact Forth section ContactFormMobile(), SizedBox(height: 20.0), ], ) ], ), ), ); } }
0
mirrored_repositories/paulina_knop/lib
mirrored_repositories/paulina_knop/lib/common/blog.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import '../components.dart'; class Blog extends StatefulWidget { const Blog({Key? key}) : super(key: key); @override State<Blog> createState() => _BlogState(); } class _BlogState extends State<Blog> { // List title = ["Who is Dash?", "Who is Dash 1?"]; // List body = ["Well, we can all read about it in google", "Google it"]; // void article() async { // await FirebaseFirestore.instance // .collection("articles") // .get() // .then((querySnapshot) { // querySnapshot.docs.reversed.forEach((element) { // //print(element.data()['title']); // }); // }); // } // // void streamArticle() async { // var logger = Logger(); // // await for (var snapshot // in FirebaseFirestore.instance.collection('articles').snapshots()) { // for (var title in snapshot.docs.reversed) { // logger.d(title.data()['title']); // } // } // } // @override // void initState() { // streamArticle(); // //article(); // super.initState(); // } @override Widget build(BuildContext context) { bool is_web = MediaQuery.of(context).size.width > 800; return SafeArea( child: Scaffold( extendBodyBehindAppBar: true, backgroundColor: Colors.white, endDrawer: DrawersMobile(), body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( backgroundColor: Colors.white, iconTheme: IconThemeData( size: 35.0, color: Colors.black, ), flexibleSpace: FlexibleSpaceBar( centerTitle: is_web ? false : true, title: Container( decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.circular(3.0), ), padding: EdgeInsets.symmetric(horizontal: is_web ? 7.0 : 4.0), child: AbelCustom( text: "Welcome to my blog", size: is_web ? 30.0 : 24.0, color: Colors.white, fontWeight: FontWeight.bold, ), ), background: Image.asset( "assets/blog.jpg", filterQuality: FilterQuality.high, fit: BoxFit.cover, ), ), expandedHeight: is_web ? 500.0 : 400.0, ) ]; }, body: StreamBuilder<QuerySnapshot>( stream: FirebaseFirestore.instance.collection('articles').snapshots(), builder: (context, snapshot) { if (snapshot.hasData) { return ListView.builder( itemCount: snapshot.data!.docs.length, itemBuilder: (BuildContext context, int index) { DocumentSnapshot documentSnapshot = snapshot.data!.docs[index]; return BlogPost( title: documentSnapshot["title"], body: documentSnapshot["body"], isWeb: is_web, ); }, ); } else return Center( child: CircularProgressIndicator(), ); }, ), ), ), ); } } class BlogPost extends StatefulWidget { final title; final body; final isWeb; const BlogPost( {Key? key, @required this.title, @required this.body, required this.isWeb}) : super(key: key); @override State<BlogPost> createState() => _BlogPostState(); } class _BlogPostState extends State<BlogPost> { bool expand = false; @override Widget build(BuildContext context) { return Padding( padding: widget.isWeb ? EdgeInsets.only(left: 70.0, right: 70.0, top: 40.0) : EdgeInsets.only(left: 20.0, right: 20.0, top: 30.0), child: Container( padding: EdgeInsets.all(10.0), decoration: BoxDecoration( border: Border.all( style: BorderStyle.solid, width: 1.0, color: Colors.black)), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( padding: EdgeInsets.symmetric(horizontal: 5.0), decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.circular(3.0), ), child: AbelCustom( text: widget.title.toString(), size: 25.0, color: Colors.white, ), ), IconButton( onPressed: () { setState(() { expand = !expand; }); }, icon: Icon(Icons.arrow_drop_down_circle_outlined), color: Colors.black, ) ], ), SizedBox(height: 7.0), Text( widget.body.toString(), style: GoogleFonts.openSans(fontSize: 15.0), maxLines: expand == true ? null : 3, overflow: expand == true ? TextOverflow.visible : TextOverflow.ellipsis, ), ], ), ), ); } }
0
mirrored_repositories/paulina_knop/lib
mirrored_repositories/paulina_knop/lib/web/landing_page_web.dart
import 'package:flutter/material.dart'; import 'package:paulina_knop/components.dart'; class LandingPageWeb extends StatefulWidget { const LandingPageWeb({Key? key}) : super(key: key); @override _LandingPageWebState createState() => _LandingPageWebState(); } class _LandingPageWebState extends State<LandingPageWeb> { @override Widget build(BuildContext context) { var heightDevice = MediaQuery.of(context).size.height; var widthDevice = MediaQuery.of(context).size.width; return Scaffold( drawer: DrawersWeb(), backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.white, elevation: 0.0, iconTheme: IconThemeData( size: 25.0, color: Colors.black, ), title: TabsWebList(), ), body: ListView( children: [ //First section Container( height: heightDevice - 56, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( decoration: BoxDecoration( color: Colors.tealAccent, borderRadius: BorderRadius.only( topLeft: Radius.circular(20.0), topRight: Radius.circular(20.0), bottomRight: Radius.circular(20.0), )), padding: EdgeInsets.symmetric( vertical: 10.0, horizontal: 20.0), child: SansBold("Hello I'm", 15.0), ), SizedBox(height: 15.0), SansBold("Paulina Knop", 55.0), Sans("Flutter developer", 30.0), SizedBox(height: 15.0), Row( children: [ Icon(Icons.email), SizedBox(width: 20.0), Sans("paulinaknop@gmail.com", 15.0), ], ), SizedBox(height: 10.0), Row( children: [ Icon(Icons.call), SizedBox(width: 20.0), Sans("+48 942 564 985", 15.0), ], ), SizedBox(height: 10.0), Row( children: [ Icon(Icons.location_pin), SizedBox(width: 20.0), Sans("13/3, Szczecin, Poland", 15.0), ], ), ], ), CircleAvatar( radius: 147.0, backgroundColor: Colors.tealAccent, child: CircleAvatar( radius: 143.0, backgroundColor: Colors.black, child: CircleAvatar( radius: 140.0, backgroundColor: Colors.white, backgroundImage: AssetImage("assets/image-circle.png"), ), ), ), ], ), ), //Second section Container( height: heightDevice / 1.5, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: [ Image.asset("assets/web.jpg", height: widthDevice / 1.9), Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ SansBold("About me", 40.0), SizedBox(height: 15.0), Sans( "Hello! I'm Paulina Knop I specialize in flutter development.", 15.0), Sans( "I strive to ensure astounding performance with state of ", 15.0), Sans( "the art security for Android, Ios, Web, Mac, Linux and Windows", 15.0), SizedBox(height: 10.0), Row( children: [ tealContainer("Flutter"), SizedBox(width: 7.0), tealContainer("Firebase"), SizedBox(width: 7.0), tealContainer("Android"), SizedBox(width: 7.0), tealContainer("IOS"), SizedBox(width: 7.0), tealContainer("Windows"), ], ) ], ), ], ), ), //Third section Container( height: heightDevice / 1.3, child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ SansBold("What I do?", 40.0), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ AnimatedCard( imagePath: "assets/webL.png", text: "Web development", ), AnimatedCard( imagePath: "assets/app.png", text: "App development", fit: BoxFit.contain, reverse: true, ), AnimatedCard( imagePath: "assets/firebase.png", text: "Back-end development", ), ], ) ], ), ), //Forth section SizedBox( height: 15.0, ), ContactFormWeb(), SizedBox(height: 20.0), ], ), ); } }
0
mirrored_repositories/paulina_knop/lib
mirrored_repositories/paulina_knop/lib/web/works_web.dart
import 'package:flutter/material.dart'; import 'package:paulina_knop/components.dart'; class WorksWeb extends StatefulWidget { const WorksWeb({Key? key}) : super(key: key); @override State<WorksWeb> createState() => _WorksWebState(); } class _WorksWebState extends State<WorksWeb> { @override Widget build(BuildContext context) { var widthDevice = MediaQuery.of(context).size.width; return Scaffold( drawer: DrawersWeb(), backgroundColor: Colors.white, body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( expandedHeight: 500.0, backgroundColor: Colors.white, iconTheme: IconThemeData(size: 25.0, color: Colors.black), flexibleSpace: FlexibleSpaceBar( background: Image.asset( "assets/works.jpg", fit: BoxFit.cover, filterQuality: FilterQuality.high, ), ), title: TabsWebList(), ) ]; }, body: ListView( children: [ Column( children: [ SizedBox(height: 30.0), SansBold("Works", 40.0), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ AnimatedCard( imagePath: "assets/portfolio_screenshot.PNG", height: 200.0, width: 300.0, ), SizedBox( width: widthDevice / 3, child: Column( children: [ SansBold("Portfolio", 30.0), SizedBox( height: 15.0, ), Sans( "Deployed on Android, IOS and Web, the portfolio project was truly an achievement. I used Flutter to develop the beautiful and responsive UI and Firebase for the back-end.", 15.0) ], ), ) ], ) ], ) ], ), ), ); } }
0
mirrored_repositories/paulina_knop/lib
mirrored_repositories/paulina_knop/lib/web/about_web.dart
import 'package:flutter/material.dart'; import 'package:paulina_knop/components.dart'; class AboutWeb extends StatefulWidget { const AboutWeb({Key? key}) : super(key: key); @override State<AboutWeb> createState() => _AboutWebState(); } class _AboutWebState extends State<AboutWeb> { @override Widget build(BuildContext context) { var widthDevice = MediaQuery.of(context).size.width; return Scaffold( drawer: DrawersWeb(), backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.white, elevation: 0.0, iconTheme: IconThemeData( size: 25.0, color: Colors.black, ), title: TabsWebList(), ), body: ListView( children: [ //About me, first section SizedBox( height: 500.0, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.center, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ SansBold("About me", 40.0), SizedBox(height: 15.0), Sans( "Hello! I'm Paulina Knop I specialize in flutter development.", 15.0), Sans( "I strive to ensure astounding performance with state of", 15.0), Sans( "the art security for Android, Ios, Web, Mac, Linux and Windows", 15.0), SizedBox(height: 10.0), Row( children: [ tealContainer("Flutter"), SizedBox( width: 7.0, ), tealContainer("Firebase"), SizedBox( width: 7.0, ), tealContainer("Android"), SizedBox( width: 7.0, ), tealContainer("IOS"), SizedBox(width: 7.0), tealContainer("Windows"), ], ), ], ), CircleAvatar( radius: 147.0, backgroundColor: Colors.tealAccent, child: CircleAvatar( radius: 143.0, backgroundColor: Colors.black, child: CircleAvatar( radius: 140.0, backgroundColor: Colors.white, child: Image.asset( "assets/profile2-circle.png", filterQuality: FilterQuality.high, ), ), ), ), ], ), ), //Web development, second section Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ AnimatedCard( imagePath: "assets/webL.png", height: 250.0, width: 250.0, ), SizedBox( width: widthDevice / 3, child: Column( children: [ SansBold("Web development", 30.0), SizedBox(height: 15.0), Sans( "I'm here to build your presence online with state of the art web apps.", 15.0) ], ), ) ], ), SizedBox(height: 20.0), //App development, third section Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ SizedBox( width: widthDevice / 3, child: Column( children: [ SansBold("App development", 30.0), SizedBox(height: 15.0), Sans( "Do you need a high-performance, responsive and beautiful app? Don't worry, I've got you covered.", 15.0), ], ), ), AnimatedCard( imagePath: "assets/app.png", height: 250.0, width: 250.0, reverse: true, ) ], ), SizedBox(height: 20.0), //Back-end development, second section Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ AnimatedCard( imagePath: "assets/firebase.png", height: 250.0, width: 250.0, ), SizedBox( width: widthDevice / 3, child: Column( children: [ SansBold("Back-end development", 30.0), SizedBox( height: 15.0, ), Sans( "Do you want your back-end to be highly scalable and secure? Let's have a conversation on how I can help you with that.", 15.0), ], ), ) ], ), SizedBox(height: 40.0), ], ), ); } }
0
mirrored_repositories/paulina_knop/lib
mirrored_repositories/paulina_knop/lib/web/contact_web.dart
import 'package:flutter/material.dart'; import 'package:paulina_knop/components.dart'; class ContactWeb extends StatefulWidget { const ContactWeb({Key? key}) : super(key: key); @override State<ContactWeb> createState() => _ContactWebState(); } class _ContactWebState extends State<ContactWeb> { @override Widget build(BuildContext context) { return Scaffold( drawer: DrawersWeb(), backgroundColor: Colors.white, body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( expandedHeight: 500.0, backgroundColor: Colors.white, iconTheme: IconThemeData(size: 25.0, color: Colors.black), flexibleSpace: FlexibleSpaceBar( background: Image.asset( "assets/contact_image.jpg", fit: BoxFit.cover, filterQuality: FilterQuality.high, ), ), title: TabsWebList(), ) ]; }, body: SingleChildScrollView( child: ContactFormWeb(), ), ), ); } }
0
mirrored_repositories/paulina_knop
mirrored_repositories/paulina_knop/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:paulina_knop/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/App-Loja-Jogos/portmob
mirrored_repositories/App-Loja-Jogos/portmob/lib/main.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( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. // // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final". final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); } @override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: Column( // Column is also a layout widget. It takes a list of children and // arranges them vertically. By default, it sizes itself to fit its // children horizontally, and tries to be as tall as its parent. // // Invoke "debug painting" (press "p" in the console, choose the // "Toggle Debug Paint" action from the Flutter Inspector in Android // Studio, or the "Toggle Debug Paint" command in Visual Studio Code) // to see the wireframe for each widget. // // Column has various properties to control how it sizes itself and // how it positions its children. Here we use mainAxisAlignment to // center the children vertically; the main axis here is the vertical // axis because Columns are vertical (the cross axis would be // horizontal). mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
0
mirrored_repositories/App-Loja-Jogos/portmob
mirrored_repositories/App-Loja-Jogos/portmob/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:portmob/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/Rewall_flutter
mirrored_repositories/Rewall_flutter/lib/main.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:rewalls/blocs/image_bloc.dart'; import 'package:rewalls/pages/Full_image_page.dart'; import 'package:rewalls/pages/home_page.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider<ImageBloc>.value( value: ImageBloc(), ), ], child: MaterialApp( title: 'Flutter Demo', theme: ThemeData( brightness: Brightness.dark, primarySwatch: Colors.blue, ), debugShowCheckedModeBanner: false, initialRoute: '/', routes: { // When navigating to the "/" route, build the FirstScreen widget. '/': (context) => Homepage(), // When navigating to the "/second" route, build the SecondScreen widget. '/second': (context) => FullImagePage(), }, ), ); } }
0
mirrored_repositories/Rewall_flutter/lib
mirrored_repositories/Rewall_flutter/lib/blocs/image_bloc.dart
import 'package:flutter/material.dart'; import 'package:rewalls/models/single_image_model.dart'; class ImageBloc extends ChangeNotifier { SingleImage _imageSingle; SingleImage get imageSingle => _imageSingle; set imageSingle (SingleImage imageSingle) { _imageSingle = imageSingle; notifyListeners(); } showImageDetail(SingleImage imageData) { imageSingle = imageData; } }
0
mirrored_repositories/Rewall_flutter/lib
mirrored_repositories/Rewall_flutter/lib/blocs/apiCalls.dart
import 'dart:convert'; import 'dart:io'; import 'package:rewalls/models/single_image_model.dart'; import '../keys.dart'; class ApiCall { static Future<List<SingleImage>> loadImages({int page = 1, int perPage = 10}) async { String url = 'https://api.unsplash.com/collections/1065976/photos?page=$page&per_page=$perPage'; // receive image data from unsplash var data = await _getImageData(url); // generate UnsplashImage List from received data List<SingleImage> imageLists = List<SingleImage>.generate(data.length, (index) { return SingleImage.fromJson(data[index]); }); return imageLists; } static dynamic _getImageData(String url) async { // setup http client HttpClient httpClient = HttpClient(); // setup http request HttpClientRequest request = await httpClient.getUrl(Uri.parse(url)); // pass the client_id in the header request.headers .add('Authorization', 'Client-ID ${Keys.UNSPLASH_API_CLIENT_ID}'); // wait for response HttpClientResponse response = await request.close(); // Process the response if (response.statusCode == 200) { // response: OK // decode JSON String json = await response.transform(utf8.decoder).join(); // return decoded json return jsonDecode(json); } else { // something went wrong :( print("Http error: ${response.statusCode}"); // return empty list return []; } } }
0
mirrored_repositories/Rewall_flutter/lib
mirrored_repositories/Rewall_flutter/lib/pages/home_page.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart' show timeDilation; import 'package:flutter_icons/flutter_icons.dart'; import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; import 'package:provider/provider.dart'; import 'package:rewalls/blocs/apiCalls.dart'; import 'package:rewalls/blocs/image_bloc.dart'; import 'package:rewalls/models/single_image_model.dart'; import 'package:rewalls/utils/colorChanger.dart'; class Homepage extends StatefulWidget { @override _HomepageState createState() => _HomepageState(); } class _HomepageState extends State<Homepage> { int perPage = 20, page = 1; List<SingleImage> allImageList = new List(); final items = new List(); StaggeredTile _buildStaggeredTile(SingleImage image, int columnCount) { // calc image aspect ration double aspectRatio = image.height.toDouble() / image.width.toDouble(); // calc columnWidth double columnWidth = MediaQuery.of(context).size.width / columnCount; // not using [StaggeredTile.fit(1)] because during loading StaggeredGrid is really jumpy. return StaggeredTile.extent(1, aspectRatio * columnWidth); } ScrollController _controller = ScrollController(); bool loadingImage = false; @override void initState() { super.initState(); _callApi(); _controller.addListener(() { if (_controller.position.pixels == _controller.position.maxScrollExtent) { _callApi(); } }); } void _callApi() async { try { loadingImage = true; List<SingleImage> allImageLists = await ApiCall.loadImages(page: page, perPage: perPage); List<SingleImage> newList; if (page > 1) { newList = new List.from(allImageList)..addAll(allImageLists); } else { newList = allImageLists; } setState(() { loadingImage = false; allImageList = newList; page++; }); } catch (e) { print(e); loadingImage = false; } } @override void dispose() { super.dispose(); _controller.dispose(); } _listOfImage() { final ImageBloc imageBloc = Provider.of<ImageBloc>(context); return StaggeredGridView.countBuilder( controller: _controller, crossAxisCount: 2, itemCount: allImageList.length, itemBuilder: (BuildContext context, int index) => Padding( padding: const EdgeInsets.all(8.0), child: Container( child: Center( child: Hero( tag: allImageList[index].id, child: Material( child: InkWell( onTap: () { imageBloc.showImageDetail(allImageList[index]); Navigator.pushNamed(context, '/second'); }, child: Stack( children: <Widget>[ CachedNetworkImage( imageBuilder: (context, imageProvider) => Container( decoration: BoxDecoration( boxShadow: [ BoxShadow( color: FlutterColor(allImageList[index].color) .withOpacity(0.3), offset: Offset(3.0, 5.0), blurRadius: 5.0, ) ], borderRadius: BorderRadius.all(Radius.circular(10)), image: DecorationImage( image: imageProvider, fit: BoxFit.cover, ), ), ), placeholder: (context, url) => Container( decoration: BoxDecoration( borderRadius: BorderRadius.horizontal( left: Radius.circular(10.0), right: Radius.circular(10.0)), color: FlutterColor(allImageList[index].color), )), imageUrl: allImageList[index].urls.regular, ), Positioned( bottom: 0, left: 0, right: 0, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.horizontal( left: Radius.circular(10.0), right: Radius.circular(10.0)), gradient: LinearGradient( // Where the linear gradient begins and ends begin: Alignment.bottomCenter, end: Alignment.topCenter, // Add one stop for each color. Stops should increase from 0 to 1 stops: [0.01, 1], colors: [ // Colors are easy thanks to Flutter's Colors class. Colors.black87, Colors.transparent, ], ), ), child: Row( children: <Widget>[ Padding( padding: const EdgeInsets.symmetric( horizontal: 2.0, vertical: 0.0), child: Icon( Ionicons.getIconData("md-heart"), color: Colors.red[700], size: 20, )), Expanded( child: Text( allImageList[index].likes.toString(), overflow: TextOverflow.fade, style: TextStyle(fontWeight: FontWeight.bold), )) ], ), ), ), ], )), ), ), ), ), ), staggeredTileBuilder: (int index) => _buildStaggeredTile(allImageList[index], 2), mainAxisSpacing: 4.0, crossAxisSpacing: 4.0, ); } @override Widget build(BuildContext context) { timeDilation = 1.5; return Scaffold( appBar: AppBar( title: Text('Rewall'), ), body: Padding(padding: const EdgeInsets.all(4.0), child: !loadingImage ? _listOfImage() : LinearProgressIndicator()), ); } }
0
mirrored_repositories/Rewall_flutter/lib
mirrored_repositories/Rewall_flutter/lib/pages/Full_image_page.dart
import 'dart:ui'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_speed_dial/flutter_speed_dial.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:provider/provider.dart'; import 'package:rewalls/blocs/image_bloc.dart'; import 'package:sliding_up_panel/sliding_up_panel.dart'; import 'package:wallpaper/wallpaper.dart'; import 'package:url_launcher/url_launcher.dart'; import '../keys.dart'; class FullImagePage extends StatefulWidget { @override _FullImagePageState createState() => _FullImagePageState(); } class _FullImagePageState extends State<FullImagePage> { // no idea how you named your data class... String home = "Home Screen", lock = "Lock Screen", both = "Both Screen"; bool panelState = false; bool isFirstLoad = true; Stream<String> progressString; double res = 0; bool downloading = false; var result = "Waiting to set wallpaper"; @override void initState() { super.initState(); } _toastMsg(msg) { Fluttertoast.showToast( msg: msg, toastLength: Toast.LENGTH_LONG, gravity: ToastGravity.CENTER, timeInSecForIos: 3, backgroundColor: Colors.black87, textColor: Colors.white, fontSize: 16.0); } void _panelOpen() { setState(() { panelState = true; }); } void _panelClosed() { if (isFirstLoad == true) { isFirstLoad = false; return; } setState(() { panelState = false; }); } _launchURL(urlLink) async { String url = urlLink; if (await canLaunch(url)) { await launch(url); } } BorderRadiusGeometry radius = BorderRadius.only( topLeft: Radius.circular(24.0), topRight: Radius.circular(24.0), ); @override Widget build(BuildContext context) { final ImageBloc imageBloc = Provider.of<ImageBloc>(context); if (imageBloc.imageSingle == null) Navigator.of(context).pop(); return Scaffold( body: SlidingUpPanel( onPanelOpened: _panelOpen, onPanelClosed: _panelClosed, minHeight: 80, panel: Container( decoration: BoxDecoration( borderRadius: radius, color: Colors.black87, ), child: Column( children: <Widget>[ Center( child: Container( child: Icon(panelState == false ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down), ), ), Column( children: <Widget>[ Row( children: <Widget>[ Padding( padding: const EdgeInsets.symmetric( horizontal: 8.0, vertical: 0.0), child: CircleAvatar( backgroundImage: NetworkImage( imageBloc.imageSingle.user.profileImage.medium), ), ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ InkWell( child: Container( padding: EdgeInsets.fromLTRB(0, 0, 0, 8), child: Text(imageBloc.imageSingle.user.name)), onTap: () { _launchURL( imageBloc.imageSingle.user.links.html); }), InkWell( child: Text('Unsplash'), onTap: () { _launchURL('https://unsplash.com'); }), ], ) ], ), Padding( padding: EdgeInsets.fromLTRB(10, 20, 0, 10), child: Row( children: <Widget>[ imageBloc.imageSingle.user.bio != null ? Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: const EdgeInsets.only(bottom: 10.0), child: Text( 'Bio', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold), ), ), Text(imageBloc.imageSingle.user.bio) ], ), ) : Text('') ], ), ) ], ), ], )), body: Stack( children: <Widget>[ Container( child: Stack( children: <Widget>[ CachedNetworkImage( imageBuilder: (context, imageProvider) => Container( decoration: BoxDecoration( image: DecorationImage( image: imageProvider, fit: BoxFit.cover, ), ), ), imageUrl: imageBloc.imageSingle.urls.regular, ), BackdropFilter( filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), child: Container( decoration: BoxDecoration(color: Colors.white.withOpacity(0.0)), ), ), Center( child: Hero( tag: imageBloc.imageSingle.id, child: CachedNetworkImage( imageBuilder: (context, imageProvider) => Container( decoration: BoxDecoration( image: DecorationImage( image: imageProvider, fit: BoxFit.fitWidth, ), ), ), placeholder: (context, url) => CircularProgressIndicator(), imageUrl: imageBloc.imageSingle.urls.regular, ), ), ), ], ), ), Positioned( child: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: Stack( children: <Widget>[ Padding( padding: const EdgeInsets.fromLTRB(4.0, 4.0, 0.0, 0.0), child: Container( width: 40.0, height: 40.0, decoration: new BoxDecoration( color: Colors.black87, shape: BoxShape.circle, border: Border.all( color: Colors.white54, )), ), ), IconButton( icon: Icon(Icons.arrow_back, color: Colors.white), onPressed: () => Navigator.of(context).pop(), ), ], ), ), ), ], ), borderRadius: radius, ), floatingActionButton: SpeedDial( animatedIcon: AnimatedIcons.list_view, curve: Curves.ease, overlayOpacity: 0.3, tooltip: 'Speed Dial', backgroundColor: Colors.black87, foregroundColor: Colors.white, elevation: 16.0, children: [ SpeedDialChild( child: Icon(Icons.stay_primary_portrait), backgroundColor: Colors.black87, foregroundColor: Colors.white, label: 'Both', labelBackgroundColor: Colors.black87, onTap: () { _toastMsg('Downloading...'); progressString = Wallpaper.ImageDownloadProgress( '${imageBloc.imageSingle.links.download}?client_id=${Keys.UNSPLASH_API_CLIENT_ID}'); progressString.listen((data) { setState(() { res = double.parse(data.replaceAll(RegExp('%'), '')); downloading = true; }); print("DataReceived: " + data); }, onDone: () async { both = await Wallpaper.homeScreen(); _toastMsg('Wallpaper set successfully'); setState(() { downloading = false; both = both; }); print("Task Done"); }, onError: (error) { setState(() { downloading = false; }); print("Some Error"); }); }), SpeedDialChild( child: Icon(Icons.screen_lock_portrait), backgroundColor: Colors.black87, foregroundColor: Colors.white, labelBackgroundColor: Colors.black87, label: 'Lock Screen', onTap: () { _toastMsg('Downloading...'); progressString = Wallpaper.ImageDownloadProgress( '${imageBloc.imageSingle.links.download}?client_id=${Keys.UNSPLASH_API_CLIENT_ID}'); progressString.listen((data) { setState(() { res = double.parse(data.replaceAll(RegExp('%'), '')); downloading = true; }); print("DataReceived: " + data); }, onDone: () async { lock = await Wallpaper.homeScreen(); _toastMsg('Lockscreen wallpaper set successfully'); setState(() { downloading = false; lock = lock; }); print("Task Done"); }, onError: (error) { setState(() { downloading = false; }); print("Some Error"); }); }), SpeedDialChild( child: Icon(Icons.add_to_home_screen), label: 'Home Screen', backgroundColor: Colors.black87, foregroundColor: Colors.white, labelBackgroundColor: Colors.black87, onTap: () { _toastMsg('Downloading...'); progressString = Wallpaper.ImageDownloadProgress( '${imageBloc.imageSingle.links.download}?client_id=${Keys.UNSPLASH_API_CLIENT_ID}'); progressString.listen((data) { setState(() { res = double.parse(data.replaceAll(RegExp('%'), '')); downloading = true; }); print("DataReceived: " + data); }, onDone: () async { home = await Wallpaper.homeScreen(); _toastMsg('Homescreen wallpaper set successfully'); setState(() { downloading = false; home = home; }); print("Task Done"); }, onError: (error) { setState(() { downloading = false; }); print("Some Error"); }); }), ], ), ); } }
0
mirrored_repositories/Rewall_flutter/lib
mirrored_repositories/Rewall_flutter/lib/models/single_image_model.dart
// import 'package:flutter/material.dart'; class SingleImage { String id; String createdAt; String updatedAt; int width; int height; String color; int likes; bool likedByUser; String description; User user; List<CurrentUserCollections> currentUserCollections; Urls urls; Links links; SingleImage( {this.id, this.createdAt, this.updatedAt, this.width, this.height, this.color, this.likes, this.likedByUser, this.description, this.user, this.currentUserCollections, this.urls, this.links}); SingleImage.fromJson(Map<String, dynamic> json) { id = json['id']; createdAt = json['created_at']; updatedAt = json['updated_at']; width = json['width']; height = json['height']; color = json['color']; likes = json['likes']; likedByUser = json['liked_by_user']; description = json['description']; user = json['user'] != null ? new User.fromJson(json['user']) : null; if (json['current_user_collections'] != null) { currentUserCollections = new List<CurrentUserCollections>(); json['current_user_collections'].forEach((v) { currentUserCollections.add(new CurrentUserCollections.fromJson(v)); }); } urls = json['urls'] != null ? new Urls.fromJson(json['urls']) : null; links = json['links'] != null ? new Links.fromJson(json['links']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['created_at'] = this.createdAt; data['updated_at'] = this.updatedAt; data['width'] = this.width; data['height'] = this.height; data['color'] = this.color; data['likes'] = this.likes; data['liked_by_user'] = this.likedByUser; data['description'] = this.description; if (this.user != null) { data['user'] = this.user.toJson(); } if (this.currentUserCollections != null) { data['current_user_collections'] = this.currentUserCollections.map((v) => v.toJson()).toList(); } if (this.urls != null) { data['urls'] = this.urls.toJson(); } if (this.links != null) { data['links'] = this.links.toJson(); } return data; } } class User { String id; String username; String name; String portfolioUrl; String bio; String location; int totalLikes; int totalPhotos; int totalCollections; String instagramUsername; String twitterUsername; ProfileImage profileImage; Links links; User( {this.id, this.username, this.name, this.portfolioUrl, this.bio, this.location, this.totalLikes, this.totalPhotos, this.totalCollections, this.instagramUsername, this.twitterUsername, this.profileImage, this.links}); User.fromJson(Map<String, dynamic> json) { id = json['id']; username = json['username']; name = json['name']; portfolioUrl = json['portfolio_url']; bio = json['bio']; location = json['location']; totalLikes = json['total_likes']; totalPhotos = json['total_photos']; totalCollections = json['total_collections']; instagramUsername = json['instagram_username']; twitterUsername = json['twitter_username']; profileImage = json['profile_image'] != null ? new ProfileImage.fromJson(json['profile_image']) : null; links = json['links'] != null ? new Links.fromJson(json['links']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['username'] = this.username; data['name'] = this.name; data['portfolio_url'] = this.portfolioUrl; data['bio'] = this.bio; data['location'] = this.location; data['total_likes'] = this.totalLikes; data['total_photos'] = this.totalPhotos; data['total_collections'] = this.totalCollections; data['instagram_username'] = this.instagramUsername; data['twitter_username'] = this.twitterUsername; if (this.profileImage != null) { data['profile_image'] = this.profileImage.toJson(); } if (this.links != null) { data['links'] = this.links.toJson(); } return data; } } class ProfileImage { String small; String medium; String large; ProfileImage({this.small, this.medium, this.large}); ProfileImage.fromJson(Map<String, dynamic> json) { small = json['small']; medium = json['medium']; large = json['large']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['small'] = this.small; data['medium'] = this.medium; data['large'] = this.large; return data; } } class Links { String self; String html; String photos; String likes; String portfolio; String download; Links({this.self, this.html, this.photos, this.likes, this.portfolio, this.download}); Links.fromJson(Map<String, dynamic> json) { self = json['self']; html = json['html']; photos = json['photos']; likes = json['likes']; portfolio = json['portfolio']; download = json['download']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['self'] = this.self; data['html'] = this.html; data['photos'] = this.photos; data['likes'] = this.likes; data['portfolio'] = this.portfolio; data['download'] = this.download; return data; } } class CurrentUserCollections { int id; String title; String publishedAt; String updatedAt; bool curated; String coverPhoto; String user; CurrentUserCollections( {this.id, this.title, this.publishedAt, this.updatedAt, this.curated, this.coverPhoto, this.user}); CurrentUserCollections.fromJson(Map<String, dynamic> json) { id = json['id']; title = json['title']; publishedAt = json['published_at']; updatedAt = json['updated_at']; curated = json['curated']; coverPhoto = json['cover_photo']; user = json['user']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['title'] = this.title; data['published_at'] = this.publishedAt; data['updated_at'] = this.updatedAt; data['curated'] = this.curated; data['cover_photo'] = this.coverPhoto; data['user'] = this.user; return data; } } class Urls { String raw; String full; String regular; String small; String thumb; Urls({this.raw, this.full, this.regular, this.small, this.thumb}); Urls.fromJson(Map<String, dynamic> json) { raw = json['raw']; full = json['full']; regular = json['regular']; small = json['small']; thumb = json['thumb']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['raw'] = this.raw; data['full'] = this.full; data['regular'] = this.regular; data['small'] = this.small; data['thumb'] = this.thumb; return data; } }
0
mirrored_repositories/Rewall_flutter/lib
mirrored_repositories/Rewall_flutter/lib/utils/colorChanger.dart
import 'package:flutter/material.dart'; class FlutterColor extends Color { static int _getColorFromHex(String flutterColor) { flutterColor = flutterColor.toUpperCase().replaceAll("#", ""); if (flutterColor.length == 6) { flutterColor = "FF" + flutterColor; } return int.parse(flutterColor, radix: 16); } FlutterColor(final String flutterColor) : super(_getColorFromHex(flutterColor)); }
0
mirrored_repositories/Rewall_flutter
mirrored_repositories/Rewall_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:rewalls/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/bytebank
mirrored_repositories/bytebank/lib/main.dart
import 'package:bytebank/screens/transfer_list.dart'; import 'package:flutter/material.dart'; void main() => runApp(ByteBankApp()); class ByteBankApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( primaryColor: Colors.green.shade900, accentColor: Colors.blueAccent.shade700, buttonTheme: ButtonThemeData( buttonColor: Colors.blueAccent.shade700, textTheme: ButtonTextTheme.primary, ), ), home: TransfersList(), ); } }
0
mirrored_repositories/bytebank/lib
mirrored_repositories/bytebank/lib/components/editor.dart
import 'package:flutter/material.dart'; class Editor extends StatelessWidget { final TextEditingController controller; final String labelText; final String hintText; final IconData icon; final int maxLengt; Editor({ this.controller, this.labelText, this.hintText, this.icon, this.maxLengt, }); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.fromLTRB(16.0, 8.00, 16.00, 0.0), child: TextField( controller: controller, keyboardType: TextInputType.number, maxLength: maxLengt, style: TextStyle( fontSize: 18.0, ), decoration: InputDecoration( labelText: labelText, hintText: hintText, icon: icon != null ? Icon(icon) : null, ), ), ); } }
0
mirrored_repositories/bytebank/lib
mirrored_repositories/bytebank/lib/models/transfer.dart
class Transfer { final double amount; final String accountNumber; Transfer( this.amount, this.accountNumber, ); @override String toString() { return 'conta e digito: $accountNumber valor: $amount'; } }
0
mirrored_repositories/bytebank/lib
mirrored_repositories/bytebank/lib/screens/transfer_form.dart
import 'package:bytebank/components/editor.dart'; import 'package:bytebank/models/transfer.dart'; import 'package:flutter/material.dart'; class TransferForm extends StatefulWidget { @override State<StatefulWidget> createState() { return TransferFormState(); } } class TransferFormState extends State<TransferForm> { final TextEditingController _accountNumberController = TextEditingController(); final TextEditingController _amountController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Criando Transferência"), ), body: SingleChildScrollView( child: Column( children: [ Editor( controller: _accountNumberController, labelText: 'Número da conta e digito', hintText: '1234-0', maxLengt: 6, ), Editor( controller: _amountController, labelText: 'Valor', hintText: '0,00', icon: Icons.monetization_on, ), RaisedButton( child: Text("Confirmar"), onPressed: () => _createTransfer(context), ) ], ), ), ); } void _createTransfer(BuildContext context) { final double amount = double.tryParse(_amountController.text); final String accountNumber = _accountNumberController.text; if (amount != null && accountNumber != null) { final transfer = Transfer(amount, accountNumber); Navigator.pop(context, transfer); } } }
0
mirrored_repositories/bytebank/lib
mirrored_repositories/bytebank/lib/screens/transfer_list.dart
import 'package:bytebank/models/transfer.dart'; import 'package:bytebank/screens/transfer_form.dart'; import 'package:flutter/material.dart'; class TransfersList extends StatefulWidget { final List<Transfer> _transfers = List(); @override State<StatefulWidget> createState() { return TransfersListState(); } } class TransfersListState extends State<TransfersList> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Transferências"), ), body: ListView.builder( itemCount: widget._transfers.length, itemBuilder: (context, index) { final transfer = widget._transfers[index]; return TransferItem(transfer); }, ), floatingActionButton: FloatingActionButton( onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return TransferForm(); })).then((transfer) => addTransfer(transfer)); }, child: Icon(Icons.add), ), ); } void addTransfer(Transfer transfer) { if (transfer != null) setState(() => widget._transfers.add(transfer)); } } class TransferItem extends StatelessWidget { final Transfer _transfer; TransferItem(this._transfer); @override Widget build(BuildContext context) { return Card( child: ListTile( leading: Icon(Icons.monetization_on), title: Text(_transfer.amount.toString()), subtitle: Text(_transfer.accountNumber), ), ); } }
0
mirrored_repositories/bytebank
mirrored_repositories/bytebank/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:bytebank/main.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(ByteBankApp()); // 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/flutterfire_cli
mirrored_repositories/flutterfire_cli/lib/firebase_options.dart
// File generated by FlutterFire CLI. // ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb, TargetPlatform; /// Default [FirebaseOptions] for use with your Firebase apps. /// /// Example: /// ```dart /// import 'firebase_options.dart'; /// // ... /// await Firebase.initializeApp( /// options: DefaultFirebaseOptions.currentPlatform, /// ); /// ``` class DefaultFirebaseOptions { static FirebaseOptions get currentPlatform { if (kIsWeb) { throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for web - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); } switch (defaultTargetPlatform) { case TargetPlatform.android: return android; case TargetPlatform.iOS: return ios; case TargetPlatform.macOS: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for macos - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); case TargetPlatform.windows: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for windows - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); case TargetPlatform.linux: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for linux - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); default: throw UnsupportedError( 'DefaultFirebaseOptions are not supported for this platform.', ); } } static const FirebaseOptions android = FirebaseOptions( apiKey: 'AIzaSyC_W0B0F7SmkDncZ7MUI8IxB_uJ15c_tac', appId: '1:19330237707:android:7c305a7bc120c02c860e0e', messagingSenderId: '19330237707', projectId: 'flutterfirecli-d4a8a', storageBucket: 'flutterfirecli-d4a8a.appspot.com', ); static const FirebaseOptions ios = FirebaseOptions( apiKey: 'AIzaSyDKbpD1r5mHvaTfmOGvxEUdz0taegs_rwI', appId: '1:19330237707:ios:30c0e064ec353f6e860e0e', messagingSenderId: '19330237707', projectId: 'flutterfirecli-d4a8a', storageBucket: 'flutterfirecli-d4a8a.appspot.com', iosClientId: '19330237707-22b471q8001drf10jo4neoo0t618ssnq.apps.googleusercontent.com', iosBundleId: 'com.example.flutterfireCli', ); }
0
mirrored_repositories/flutterfire_cli
mirrored_repositories/flutterfire_cli/lib/main.dart
import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter_fire_cli/firebase_options.dart'; Future<void> main() { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } }
0
mirrored_repositories/flutterfire_cli
mirrored_repositories/flutterfire_cli/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:flutterfire_cli/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/enough_mail_app
mirrored_repositories/enough_mail_app/lib/enough_mail_app.dart
export 'package:enough_mail/enough_mail.dart'; export 'src/account/account.dart'; export 'src/app.dart'; export 'src/contact/contact.dart'; export 'src/localization/app_localizations.g.dart'; export 'src/localization/extension.dart'; export 'src/localization/provider.dart'; export 'src/logger.dart'; export 'src/models/compose_data.dart'; export 'src/routes/provider.dart'; export 'src/routes/routes.dart'; export 'src/settings/settings.dart'; export 'src/settings/theme/model.dart'; export 'src/settings/theme/provider.dart'; export 'src/util/localized_dialog_helper.dart';
0
mirrored_repositories/enough_mail_app/lib
mirrored_repositories/enough_mail_app/lib/src/app.dart
import 'dart:async'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'account/provider.dart'; import 'app_lifecycle/provider.dart'; import 'background/provider.dart'; import 'keys/service.dart'; import 'localization/app_localizations.g.dart'; import 'lock/provider.dart'; import 'logger.dart'; import 'mail/service.dart'; import 'models/async_mime_source_factory.dart'; import 'notification/service.dart'; import 'routes/provider.dart'; import 'routes/routes.dart'; import 'scaffold_messenger/service.dart'; import 'screens/screens.dart'; import 'settings/provider.dart'; import 'settings/theme/provider.dart'; import 'share/provider.dart'; // AppStyles appStyles = AppStyles.instance; /// Runs the app class EnoughMailApp extends HookConsumerWidget { /// Creates a new app const EnoughMailApp({ super.key, required this.appName, this.mimeSourceFactory = const AsyncMimeSourceFactory(isOfflineModeSupported: false), }); /// The name of the app final String appName; final AsyncMimeSourceFactory mimeSourceFactory; @override Widget build(BuildContext context, WidgetRef ref) { EmailService.mimeSourceFactory = mimeSourceFactory; useOnAppLifecycleStateChange((previous, current) { logger.d('raw AppLifecycleState changed from $previous to $current'); ref.read(rawAppLifecycleStateProvider.notifier).state = current; }); final themeSettingsData = ref.watch(themeFinderProvider(context: context)); final languageTag = ref.watch(settingsProvider.select((settings) => settings.languageTag)); final routerConfig = ref.watch(routerConfigProvider); ref ..watch(incomingShareProvider) ..watch(backgroundProvider) ..watch(appLockProvider); final app = Theme( data: themeSettingsData.brightness == Brightness.dark ? themeSettingsData.darkTheme : themeSettingsData.lightTheme, child: PlatformSnackApp.router( supportedLocales: AppLocalizations.supportedLocales, localizationsDelegates: AppLocalizations.localizationsDelegates, debugShowCheckedModeBanner: false, title: appName, routerConfig: routerConfig, scaffoldMessengerKey: ScaffoldMessengerService.instance.scaffoldMessengerKey, materialTheme: themeSettingsData.lightTheme, materialDarkTheme: themeSettingsData.darkTheme, materialThemeMode: themeSettingsData.themeMode, cupertinoTheme: themeSettingsData.cupertinoTheme, ), ); if (languageTag == null) { return app; } return Localizations.override( context: context, locale: Locale(languageTag), child: app, ); } } /// Initializes the app class InitializationScreen extends ConsumerStatefulWidget { /// Creates a new [InitializationScreen] const InitializationScreen({super.key}); @override ConsumerState<InitializationScreen> createState() => _InitializationScreenState(); } class _InitializationScreenState extends ConsumerState<InitializationScreen> { @override void initState() { _initApp(); super.initState(); } Future<void> _initApp() async { await ref.read(settingsProvider.notifier).init(); await ref.read(realAccountsProvider.notifier).init(); await ref.read(backgroundProvider.notifier).init(); if (context.mounted) { // TODO(RV): check if the context is really needed for NotificationService await NotificationService.instance.init(context: context); } await KeyService.instance.init(); logger.d('App initialized'); if (context.mounted) { if (ref.read(allAccountsProvider).isEmpty) { context.goNamed(Routes.welcome); } else { context.goNamed(Routes.mail); } } } @override Widget build(BuildContext context) => const SplashScreen(); }
0
mirrored_repositories/enough_mail_app/lib
mirrored_repositories/enough_mail_app/lib/src/logger.dart
import 'package:logger/logger.dart'; /// Global logger final logger = Logger( level: Level.debug, output: ConsoleOutput(), printer: PrettyPrinter(), );
0
mirrored_repositories/enough_mail_app/lib
mirrored_repositories/enough_mail_app/lib/src/user.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:flutter/cupertino.dart'; class User with ChangeNotifier { String? _name; String? get name => _name; set name(String? value) { _name = value; notifyListeners(); } List<MailAccount> accounts = <MailAccount>[]; }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/app_lifecycle/provider.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'provider.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$appIsResumedHash() => r'2b8853b672a6faf4f961d546241be25a23bb8ebe'; /// Easy access to be notified when the app is resumed /// /// Copied from [appIsResumed]. @ProviderFor(appIsResumed) final appIsResumedProvider = Provider<bool>.internal( appIsResumed, name: r'appIsResumedProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$appIsResumedHash, dependencies: null, allTransitiveDependencies: null, ); typedef AppIsResumedRef = ProviderRef<bool>; String _$appIsInactivatedHash() => r'c13bdf5ad0eec6c95c5a85d2fe88ad84f9b3792f'; /// Easy access to be notified when the app is put to the background /// /// Copied from [appIsInactivated]. @ProviderFor(appIsInactivated) final appIsInactivatedProvider = Provider<bool>.internal( appIsInactivated, name: r'appIsInactivatedProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$appIsInactivatedHash, dependencies: null, allTransitiveDependencies: null, ); typedef AppIsInactivatedRef = ProviderRef<bool>; String _$appLifecycleHash() => r'1a695a26a70dd1d815c73f9281063bc8b7ee98f1'; /// Allows to retrieve the current (filtered) app life cycle /// /// Copied from [AppLifecycle]. @ProviderFor(AppLifecycle) final appLifecycleProvider = NotifierProvider<AppLifecycle, AppLifecycleState>.internal( AppLifecycle.new, name: r'appLifecycleProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$appLifecycleHash, dependencies: null, allTransitiveDependencies: null, ); typedef _$AppLifecycle = Notifier<AppLifecycleState>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/app_lifecycle/provider.dart
import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../logger.dart'; part 'provider.g.dart'; /// Allows to retrieve the current (raw) app life cycle final rawAppLifecycleStateProvider = StateProvider<AppLifecycleState>((ref) => AppLifecycleState.resumed); /// Allows to retrieve the current (filtered) app life cycle @Riverpod(keepAlive: true) class AppLifecycle extends _$AppLifecycle { /// Should the next resume event be ignored? var _ignoreNextInActivationCycle = false; var _ignoreTimestamp = DateTime.now(); var _ignoreDuration = const Duration(seconds: 30); @override AppLifecycleState build() { final state = ref.watch(rawAppLifecycleStateProvider); if (_ignoreNextInActivationCycle) { final difference = DateTime.now().difference(_ignoreTimestamp); if (difference > _ignoreDuration) { _ignoreNextInActivationCycle = false; logger.d('too long pause for ignoring next inactivation cycle'); return state; } if (state == AppLifecycleState.resumed) { logger.d('ignored inactivation cycle completed'); _ignoreNextInActivationCycle = false; } return AppLifecycleState.resumed; } logger.d('emitting non-ignored state: $state'); return state; } /// Ignores the next inactivation -> resume event void ignoreNextInactivationCycle({ Duration timeout = const Duration(seconds: 30), }) { _ignoreNextInActivationCycle = true; _ignoreTimestamp = DateTime.now(); _ignoreDuration = timeout; } } /// Easy access to be notified when the app is resumed @Riverpod(keepAlive: true) bool appIsResumed(AppIsResumedRef ref) => ref.watch( appLifecycleProvider .select((value) => value == AppLifecycleState.resumed), ); /// Easy access to be notified when the app is put to the background @Riverpod(keepAlive: true) bool appIsInactivated(AppIsInactivatedRef ref) => ref.watch( appLifecycleProvider .select((value) => value == AppLifecycleState.inactive), );
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/notification/service.dart
import 'dart:convert'; import 'dart:io'; import 'package:enough_mail/enough_mail.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:go_router/go_router.dart'; import '../logger.dart'; import '../models/message.dart' as maily; import '../routes/routes.dart'; import 'model.dart'; class NotificationService { NotificationService._(); static final NotificationService _instance = NotificationService._(); /// Retrieves the instance of the notification service static NotificationService get instance => _instance; static const String _messagePayloadStart = 'msg:'; final _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); Future<NotificationServiceInitResult> init({ BuildContext? context, bool checkForLaunchDetails = true, }) async { // print('init notification service...'); // set up local notifications: // initialize the plugin. app_icon needs to be a added as a drawable // resource to the Android head project if (defaultTargetPlatform == TargetPlatform.windows) { // Windows is not yet supported: return NotificationServiceInitResult.normal; } const android = AndroidInitializationSettings('ic_stat_notification'); final ios = DarwinInitializationSettings( onDidReceiveLocalNotification: _onDidReceiveLocalNotification, ); const macos = DarwinInitializationSettings(); final initSettings = InitializationSettings(android: android, iOS: ios, macOS: macos); await _flutterLocalNotificationsPlugin.initialize( initSettings, onDidReceiveNotificationResponse: _selectNotification, ); if (Platform.isAndroid) { await _flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>() ?.requestNotificationsPermission(); } if (checkForLaunchDetails) { final launchDetails = await _flutterLocalNotificationsPlugin .getNotificationAppLaunchDetails(); if (launchDetails != null && launchDetails.didNotificationLaunchApp) { final response = launchDetails.notificationResponse; if (response != null) { // print( // 'got notification launched details: $launchDetails // with payload ${response.payload}'); if (context != null && context.mounted) { _selectNotification(response, context: context); } return NotificationServiceInitResult.appLaunchedByNotification; } } } return NotificationServiceInitResult.normal; } Future _onDidReceiveLocalNotification( int id, String? title, String? body, String? payload, ) async { if (kDebugMode) { print('iOS onDidReceiveLocalNotification $id $title $body $payload'); } } Future<List<MailNotificationPayload>> getActiveMailNotifications() { /// wait until active notification also return the payload return Future.value([]); // if (!Platform.isAndroid) { // return []; // } // final activeNotifications = await _flutterLocalNotificationsPlugin // .resolvePlatformSpecificImplementation< // AndroidFlutterLocalNotificationsPlugin>() // .getActiveNotifications(); // if (activeNotifications == null || activeNotifications.isEmpty) { // return []; // } // print('active Notifications:'); // for (final n in activeNotifications) { // print( // 'body=${n.body}, title=${n.title}, id=${n.id}, channel=${n.channelId}'); // } // return activeNotifications // .where((notification) => // notification.body.startsWith(_messagePayloadStart)) // .map((notification) => _deserialize(notification.body)) // .toList(); } MailNotificationPayload _deserialize(String payloadText) { final json = jsonDecode(payloadText.substring(_messagePayloadStart.length)); return MailNotificationPayload.fromJson(json); } void _selectNotification( NotificationResponse response, { BuildContext? context, }) { final payloadText = response.payload; if (kDebugMode) { print('select notification: $payloadText'); } final usedContext = context ?? Routes.navigatorKey.currentContext; if (usedContext == null) { logger.e('Unable to show notification: no context found'); return; } if (payloadText != null && payloadText.startsWith(_messagePayloadStart)) { final payload = _deserialize(payloadText); usedContext.pushNamed( Routes.mailDetailsForNotification, extra: payload, ); } } Future sendLocalNotificationForMailMessage(maily.Message message) => sendLocalNotificationForMail( message.mimeMessage, message.source.getMimeSource(message)?.mailClient.account.email ?? message.account.email, ); Future sendLocalNotificationForMail( MimeMessage mimeMessage, String accountEmail, ) { String retrieveFromName() { final mimeFrom = mimeMessage.from; final personalName = mimeFrom != null && mimeFrom.isNotEmpty ? mimeFrom.first.personalName : mimeMessage.sender?.personalName; if (personalName != null && personalName.isNotEmpty) { return personalName; } final email = mimeFrom != null && mimeFrom.isNotEmpty ? mimeFrom.first.email : mimeMessage.sender?.email; if (email != null && email.isNotEmpty) { return email; } return ''; } final notificationId = mimeMessage.guid ?? 0; final from = retrieveFromName(); final subject = mimeMessage.decodeSubject(); final payload = MailNotificationPayload.fromMail(mimeMessage, accountEmail); final payloadText = _messagePayloadStart + jsonEncode(payload.toJson()); return _sendLocalNotification( notificationId, from, subject, payloadText: payloadText, when: mimeMessage.decodeDate(), ); } // int getNotificationIdForMail(MimeMessage mimeMessage, MailClient mailClient) { // return getNotificationIdForUid(mimeMessage.uid!, mailClient.account.email); // } // int getNotificationIdForUid(int uid, String? email) { // return (email?.hashCode ?? 0) + uid; // } Future<void> _sendLocalNotification( int id, String title, String? text, { String? payloadText, DateTime? when, bool channelShowBadge = true, }) async { logger.d('sendLocalNotification: $id: $title $text'); AndroidNotificationDetails? androidPlatformChannelSpecifics; DarwinNotificationDetails? iosPlatformChannelSpecifics; if (Platform.isAndroid) { androidPlatformChannelSpecifics = AndroidNotificationDetails( 'maily', 'Mail', channelDescription: 'Maily', importance: Importance.max, priority: Priority.high, channelShowBadge: channelShowBadge, showWhen: when != null, when: when?.millisecondsSinceEpoch, sound: const RawResourceAndroidNotificationSound('pop'), ); } else if (PlatformInfo.isCupertino) { iosPlatformChannelSpecifics = const DarwinNotificationDetails( presentSound: true, presentBadge: true, ); } final platformChannelSpecifics = NotificationDetails( android: androidPlatformChannelSpecifics, iOS: iosPlatformChannelSpecifics, ); await _flutterLocalNotificationsPlugin .show(id, title, text, platformChannelSpecifics, payload: payloadText); } void cancelNotificationForMessage(maily.Message message) => cancelNotificationForMime(message.mimeMessage); void cancelNotificationForMime(MimeMessage mimeMessage) { final guid = mimeMessage.guid; if (guid != null) { cancelNotification(guid); } } // void cancelNotificationForUid(int uid, MailClient mailClient) { // cancelNotification(getNotificationIdForUid(uid, mailClient.account.email)); // } void cancelNotification(int id) { if (defaultTargetPlatform != TargetPlatform.windows) { _flutterLocalNotificationsPlugin.cancel(id); } } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/notification/model.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'model.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** MailNotificationPayload _$MailNotificationPayloadFromJson( Map<String, dynamic> json) => MailNotificationPayload( guid: json['guid'] as int, uid: json['uid'] as int, sequenceId: json['id'] as int, accountEmail: json['account-email'] as String, subject: json['subject'] as String, size: json['size'] as int, ); Map<String, dynamic> _$MailNotificationPayloadToJson( MailNotificationPayload instance) => <String, dynamic>{ 'guid': instance.guid, 'uid': instance.uid, 'id': instance.sequenceId, 'account-email': instance.accountEmail, 'subject': instance.subject, 'size': instance.size, };
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/notification/model.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:json_annotation/json_annotation.dart'; part 'model.g.dart'; /// The result of the notification service initialization enum NotificationServiceInitResult { /// App was launched by a notification appLaunchedByNotification, /// App was launched normally normal, } /// Details to identify a mail message in a notification @JsonSerializable() class MailNotificationPayload { /// Creates a new payload const MailNotificationPayload({ required this.guid, required this.uid, required this.sequenceId, required this.accountEmail, required this.subject, required this.size, }); /// Creates a new payload from the given [mimeMessage] MailNotificationPayload.fromMail( MimeMessage mimeMessage, this.accountEmail, ) : uid = mimeMessage.uid ?? 0, guid = mimeMessage.guid ?? 0, sequenceId = mimeMessage.sequenceId ?? 0, subject = mimeMessage.decodeSubject() ?? '', size = mimeMessage.size ?? 0; /// Creates a new payload from the given [json] factory MailNotificationPayload.fromJson(Map<String, dynamic> json) => _$MailNotificationPayloadFromJson(json); /// The global unique identifier of the message final int guid; /// The unique identifier of the message final int uid; /// The sequence id of the message @JsonKey(name: 'id') final int sequenceId; /// The email address of the account @JsonKey(name: 'account-email') final String accountEmail; /// The subject of the message final String subject; /// The size of the message final int size; /// Creates JSON from this payoad Map<String, dynamic> toJson() => _$MailNotificationPayloadToJson(this); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/location/view.dart
import 'dart:ui' as ui; import 'package:cached_network_image/cached_network_image.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:latlng/latlng.dart'; import 'package:location/location.dart'; import 'package:map/map.dart' as map; import '../localization/extension.dart'; import '../logger.dart'; import '../routes/routes.dart'; import '../screens/base.dart'; import 'service.dart'; class LocationScreen extends StatefulHookConsumerWidget { const LocationScreen({super.key}); @override ConsumerState<LocationScreen> createState() => _LocationScreenState(); } class _LocationScreenState extends ConsumerState<LocationScreen> { final _repaintBoundaryKey = GlobalKey(); final _defaultLocation = LatLng.degree(53.07516, 8.80777); late map.MapController _controller; Future<LocationData?>? _findLocationFuture; late Offset _dragStart; var _scaleStart = 1.0; @override void initState() { _controller = map.MapController( location: _defaultLocation, ); _findLocationFuture = LocationService.instance.getCurrentLocation().then( (value) { final latitude = value?.latitude; final longitude = value?.longitude; if (latitude != null && longitude != null) { _controller.center = LatLng.degree(latitude, longitude); } return value; }, ); super.initState(); } @override Widget build(BuildContext context) { final localizations = ref.text; return BasePage( title: localizations.attachTypeLocation, appBarActions: [ PlatformIconButton( icon: const Icon(Icons.check), onPressed: _onLocationSelected, ), ], content: FutureBuilder<LocationData?>( future: _findLocationFuture, builder: (context, snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: case ConnectionState.waiting: case ConnectionState.active: return const Center(child: PlatformProgressIndicator()); case ConnectionState.done: final latitude = snapshot.data?.latitude; final longitude = snapshot.data?.longitude; if (latitude != null && longitude != null) { return _buildMap(context, latitude, longitude); } } return const Center(child: PlatformProgressIndicator()); }, ), ); } Future<void> _onLocationSelected() async { final context = _repaintBoundaryKey.currentContext; if (context == null) { final currentContext = Routes.navigatorKey.currentContext; if (currentContext != null) { currentContext.pop(); } return; } final boundary = context.findRenderObject(); if (boundary is! RenderRepaintBoundary) { context.pop(); return; } final image = await boundary.toImage(pixelRatio: 3); final byteData = await image.toByteData(format: ui.ImageByteFormat.png); final pngBytes = byteData?.buffer.asUint8List(); if (context.mounted) { context.pop(pngBytes); } } Widget _buildMap(BuildContext context, double latitude, double longitude) { final size = MediaQuery.of(context).size; return map.MapLayout( controller: _controller, builder: (context, transformer) => GestureDetector( onDoubleTap: _onDoubleTap, onScaleStart: _onScaleStart, onScaleUpdate: (details) => _onScaleUpdate(details, transformer), onScaleEnd: (details) { logger.d( 'Location: ${_controller.center.latitude}, ' '${_controller.center.longitude}', ); }, child: SizedBox( width: size.width, height: size.height, child: RepaintBoundary( key: _repaintBoundaryKey, child: Stack( children: [ map.TileLayer( builder: (context, x, y, z) { final url = 'https://www.google.com/maps/vt/pb=!1m4!1m3!1i$z!2i$x!3i$y!2m3!1e0!2sm!3i420120488!3m7!2sen!5e1105!12m4!1e68!2m2!1sset!2sRoadmap!4e0!5m1!1e0!23i4111425'; return CachedNetworkImage( imageUrl: url, fit: BoxFit.cover, ); }, ), const Center( child: Icon(Icons.close, color: Colors.red), ), Align( alignment: Alignment.bottomRight, child: Padding( padding: const EdgeInsets.all(8), child: PlatformIconButton( icon: const Icon( Icons.location_searching, color: Colors.grey, ), onPressed: _gotoDefault, ), ), ), ], ), ), ), ), ); } void _gotoDefault() { _controller.center = _defaultLocation; setState(() {}); } void _onDoubleTap() { _controller.zoom += 0.5; setState(() {}); } void _onScaleStart(ScaleStartDetails details) { _dragStart = details.focalPoint; _scaleStart = 1.0; } void _onScaleUpdate( ScaleUpdateDetails details, map.MapTransformer transformer, ) { final scaleDiff = details.scale - _scaleStart; _scaleStart = details.scale; if (scaleDiff > 0) { _controller.zoom += 0.02; } else if (scaleDiff < 0) { _controller.zoom -= 0.02; } else { final now = details.focalPoint; final diff = now - _dragStart; _dragStart = now; transformer.drag(diff.dx, diff.dy); } setState(() {}); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/location/service.dart
import 'package:location/location.dart'; /// Allows to query the current location class LocationService { LocationService._(); static final _instance = LocationService._(); /// Returns the singleton instance static LocationService get instance => _instance; Location? _location; bool _serviceEnabled = false; PermissionStatus _permissionStatus = PermissionStatus.denied; /// Retrieves the current location Future<LocationData?> getCurrentLocation() async { final location = _location ?? Location(); _location = location; if (!_serviceEnabled) { _serviceEnabled = await location.requestService(); if (!_serviceEnabled) { return null; } } if (_permissionStatus == PermissionStatus.denied) { _permissionStatus = await location.requestPermission(); if (_permissionStatus != PermissionStatus.granted) { return null; } } return location.getLocation(); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/scaffold_messenger/service.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import '../localization/app_localizations.g.dart'; import '../widgets/cupertino_status_bar.dart'; /// Allows to show snack bars class ScaffoldMessengerService { /// Creates a new [ScaffoldMessengerService] ScaffoldMessengerService._(); static final _instance = ScaffoldMessengerService._(); /// The instance of the [ScaffoldMessengerService] static ScaffoldMessengerService get instance => _instance; /// The key of the scaffold messenger final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>(); final _statusBarStates = <CupertinoStatusBarState>[]; CupertinoStatusBarState? _statusBarState; set statusBarState(CupertinoStatusBarState state) { final current = _statusBarState; if (current != null) { _statusBarStates.add(current); } _statusBarState = state; } void popStatusBarState() { _statusBarState = _statusBarStates.isNotEmpty ? _statusBarStates.removeLast() : null; } SnackBar _buildTextSnackBar( AppLocalizations localizations, String text, { Function()? undo, }) => SnackBar( content: Text(text), action: undo == null ? null : SnackBarAction( label: localizations.actionUndo, onPressed: undo, ), ); void _showSnackBar(SnackBar snackBar) { scaffoldMessengerKey.currentState?.showSnackBar(snackBar); } void showTextSnackBar( AppLocalizations localizations, String text, { Function()? undo, }) { if (PlatformInfo.isCupertino) { final state = _statusBarState; if (state != null) { state.showTextStatus(text, undo: undo); } else { _showSnackBar(_buildTextSnackBar(localizations, text, undo: undo)); } } else { _showSnackBar(_buildTextSnackBar(localizations, text, undo: undo)); } } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/background/provider.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'provider.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$backgroundHash() => r'14e47ad6c285728ca04916d97fff9239be504a3c'; /// Registers the background service to check for emails regularly /// /// Copied from [Background]. @ProviderFor(Background) final backgroundProvider = AsyncNotifierProvider<Background, void>.internal( Background.new, name: r'backgroundProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$backgroundHash, dependencies: null, allTransitiveDependencies: null, ); typedef _$Background = AsyncNotifier<void>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/background/provider.dart
import 'dart:convert'; import 'dart:math'; import 'package:background_fetch/background_fetch.dart'; import 'package:enough_mail/enough_mail.dart'; import 'package:flutter/foundation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../account/provider.dart'; import '../account/storage.dart'; import '../app_lifecycle/provider.dart'; import '../logger.dart'; import '../mail/provider.dart'; import '../mail/service.dart'; import '../notification/service.dart'; import 'model.dart'; part 'provider.g.dart'; /// Registers the background service to check for emails regularly @Riverpod(keepAlive: true) class Background extends _$Background { var _isActive = true; @override Future<void> build() { _isActive = true; ref.onDispose(() { _isActive = false; }); if (!_isSupported) { return Future.value(); } final isInactive = ref.watch(appIsInactivatedProvider); if (isInactive) { return _saveStateOnPause(); } return Future.value(); } /// Is the background provider supported on the current platform? static bool get _isSupported => defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS; /// Configures and registers the background service Future<void> init() async { if (!_isSupported) { return; } await BackgroundFetch.configure( BackgroundFetchConfig( minimumFetchInterval: 15, startOnBoot: true, stopOnTerminate: false, enableHeadless: true, requiresBatteryNotLow: false, requiresCharging: false, requiresStorageNotLow: false, requiresDeviceIdle: false, requiredNetworkType: NetworkType.ANY, ), (String taskId) async { logger.d('running background fetch $taskId'); try { // await locator<MailService>().resume(); await _saveStateOnPause(); } catch (e, s) { logger.e( 'Error: Unable to finish foreground background fetch: $e', error: e, stackTrace: s, ); } BackgroundFetch.finish(taskId); }, ); await BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask); logger.d('Registered background fetch'); } Future<void> _saveStateOnPause() async { logger.d('save state on pause: isActive=$_isActive'); if (!_isActive) { return _checkForNewMail(); } final accounts = ref.read(realAccountsProvider); final mailClients = accounts .map( (account) => ref.read(mailClientSourceProvider(account: account)), ) .toList(); final futures = <Future>[]; final preferences = await SharedPreferences.getInstance(); final jsonText = preferences.getString(_keyInboxUids); final info = BackgroundUpdateInfo.fromJsonText(jsonText); for (final client in mailClients) { futures.add(_addNextUidFor(client, info)); } await Future.wait(futures); logger.d('Updated UIDs, new UIDs found: ${info.containsUpdatedEntries}'); if (info.containsUpdatedEntries) { final stringValue = jsonEncode(info.toJson()); logger.d('nextUids: $stringValue'); await preferences.setString(_keyInboxUids, stringValue); } } Future<void> _addNextUidFor( final MailClient mailClient, final BackgroundUpdateInfo info, ) async { try { var box = mailClient.selectedMailbox; if (box == null || !box.isInbox) { await mailClient.connect(); box = await mailClient.selectInbox(); } final uidNext = box.uidNext; if (uidNext != null) { info.updateForEmail(mailClient.account.email, uidNext); } } catch (e, s) { logger.e( 'Error while getting Inbox.nextUids ' 'for ${mailClient.account.email}: $e', error: e, stackTrace: s, ); } } } const String _keyInboxUids = 'nextUidsInfo'; /// Fetches data in the background when the app is not running Future<void> backgroundFetchHeadlessTask(HeadlessTask task) async { final taskId = task.taskId; logger.d( 'backgroundFetchHeadlessTask with ' 'taskId $taskId, timeout=${task.timeout}', ); if (task.timeout) { BackgroundFetch.finish(taskId); return; } try { await _checkForNewMail(); } catch (e, s) { if (kDebugMode) { print('Error during backgroundFetchHeadlessTask $e $s'); } } finally { BackgroundFetch.finish(taskId); } } Future<void> _checkForNewMail() async { logger.d('background check at ${DateTime.now()}'); final preferences = await SharedPreferences.getInstance(); final inboxUidsText = preferences.getString(_keyInboxUids); if (inboxUidsText == null || inboxUidsText.isEmpty) { logger.w('WARNING: no previous UID infos found, exiting.'); return; } final info = BackgroundUpdateInfo.fromJsonText(inboxUidsText); const storage = AccountStorage(); final accounts = await storage.loadAccounts(); final mailClients = accounts.map( (account) => EmailService.instance .createMailClient(account.mailAccount, account.name, null), ); final notificationService = NotificationService.instance; await notificationService.init(checkForLaunchDetails: false); // final activeMailNotifications = // await notificationService.getActiveMailNotifications(); // print('background: got ' // 'activeMailNotifications=$activeMailNotifications'); final futures = <Future>[]; for (final mailClient in mailClients) { final previousUidNext = info.nextExpectedUidForEmail(mailClient.account.email) ?? 0; futures.add( _loadNewMessage( mailClient, previousUidNext, notificationService, info, // activeMailNotifications // .where((n) => n.accountEmail == accountEmail) // .toList()), ), ); } await Future.wait(futures); if (info.containsUpdatedEntries) { final serialized = jsonEncode(info.toJson()); await preferences.setString(_keyInboxUids, serialized); } } Future<void> _loadNewMessage( MailClient mailClient, int previousUidNext, NotificationService notificationService, BackgroundUpdateInfo info, // List<MailNotificationPayload> activeNotifications, ) async { try { // ignore: avoid_print print('${mailClient.account.name} A: background fetch connecting'); await mailClient.connect(); final inbox = await mailClient.selectInbox(); final uidNext = inbox.uidNext; if (uidNext == previousUidNext || uidNext == null) { // print( // 'no change for ${account.name}, activeNotifications=$activeNotifications'); // check outdated notifications that should be removed because the message is deleted or read elsewhere: // if (activeNotifications.isNotEmpty) { // final uids = activeNotifications.map((n) => n.uid).toList(); // final sequence = // MessageSequence.fromIds(uids as List<int>, isUid: true); // final mimeMessages = await mailClient.fetchMessageSequence(sequence, // fetchPreference: FetchPreference.envelope); // for (final mimeMessage in mimeMessages) { // if (mimeMessage.isSeen) { // notificationService.cancelNotificationForMail( // mimeMessage, mailClient); // } // uids.remove(mimeMessage.uid); // } // // remove notifications for messages that have been deleted: // final email = mailClient.account.email ?? ''; // final mailboxName = mailClient.selectedMailbox?.name ?? ''; // final mailboxValidity = mailClient.selectedMailbox?.uidValidity ?? 0; // for (final uid in uids) { // final guid = MimeMessage.calculateGuid( // email: email, // mailboxName: mailboxName, // mailboxUidValidity: mailboxValidity, // messageUid: uid, // ); // notificationService.cancelNotification(guid); // } // } } else { if (kDebugMode) { print( 'new uidNext=$uidNext, previous=$previousUidNext ' 'for ${mailClient.account.name} uidValidity=${inbox.uidValidity}', ); } final sequence = MessageSequence.fromRangeToLast( // special care when uidnext of the account was not known before: // do not load _all_ messages previousUidNext == 0 ? max(previousUidNext, uidNext - 10) : previousUidNext, isUidSequence: true, ); info.updateForEmail(mailClient.account.email, uidNext); final mimeMessages = await mailClient.fetchMessageSequence( sequence, fetchPreference: FetchPreference.envelope, ); for (final mimeMessage in mimeMessages) { if (!mimeMessage.isSeen) { await notificationService.sendLocalNotificationForMail( mimeMessage, mailClient.account.email, ); } } } await mailClient.disconnect(); } catch (e, s) { logger.e( 'Unable to process background operation ' 'for ${mailClient.account.name}: $e', error: e, stackTrace: s, ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/background/model.dart
import 'dart:convert'; /// Contains information about a known message UIDs for each email account class BackgroundUpdateInfo { /// Creates info for the background update BackgroundUpdateInfo({required Map<String, int> uidsByEmail}) : _uidsByEmail = uidsByEmail; /// Creates info from the given [json] factory BackgroundUpdateInfo.fromJson(Map<String, dynamic> json) { final uidsJsonText = json['uidsByEmail']; final uidsByEmail = uidsJsonText is String ? (jsonDecode(uidsJsonText) as Map<String, dynamic>).map( (key, value) => MapEntry(key, value as int), ) : <String, int>{}; return BackgroundUpdateInfo(uidsByEmail: uidsByEmail); } /// Creates info from the given [jsonText] factory BackgroundUpdateInfo.fromJsonText(String? jsonText) => jsonText == null ? BackgroundUpdateInfo(uidsByEmail: <String, int>{}) : BackgroundUpdateInfo.fromJson(jsonDecode(jsonText)); /// Converts this info to JSON Map<String, dynamic> toJson() => <String, dynamic>{ 'uidsByEmail': jsonEncode(_uidsByEmail), }; final Map<String, int> _uidsByEmail; var _isDirty = false; /// Has this information been updated since the last persistence? bool get containsUpdatedEntries => _isDirty; /// Updates the entry for the given [email] void updateForEmail(String email, int nextExpectedUid) { final uidsByEmail = _uidsByEmail; if (uidsByEmail[email] != nextExpectedUid) { uidsByEmail[email] = nextExpectedUid; _isDirty = true; } } /// Retrieves the next expected uid int? nextExpectedUidForEmail(String email) => _uidsByEmail[email]; }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/signature.dart
import 'dart:async'; import 'package:enough_html_editor/enough_html_editor.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:url_launcher/url_launcher.dart' as launcher; import '../account/model.dart'; import '../account/provider.dart'; import '../localization/extension.dart'; import '../settings/provider.dart'; import '../settings/theme/icon_service.dart'; import '../util/modal_bottom_sheet_helper.dart'; class SignatureWidget extends HookConsumerWidget { const SignatureWidget({super.key, this.account}); final RealAccount? account; @override Widget build(BuildContext context, WidgetRef ref) { final account = this.account; final signatureState = useState<String?>( account?.getSignatureHtml(ref.text.localeName) ?? ref.read(settingsProvider.notifier).getSignatureHtmlGlobal(), ); final signature = signatureState.value; Future<void> showEditor() async { final localizations = ref.text; final iconService = IconService.instance; HtmlEditorApi? editorApi; final result = await ModelBottomSheetHelper.showModalBottomSheet<bool>( context, account?.name ?? localizations.signatureSettingsTitle, PackagedHtmlEditor( initialContent: signature ?? ref.read(settingsProvider.notifier).getSignatureHtmlGlobal(), excludeDocumentLevelControls: true, onCreated: (api) => editorApi = api, ), appBarActions: [ if (signature != null) DensePlatformIconButton( icon: Icon(iconService.messageActionDelete), onPressed: () async { signatureState.value = null; context.pop(false); if (account != null) { account.signatureHtml = null; unawaited(ref.read(realAccountsProvider.notifier).save()); } else { final settings = ref.read(settingsProvider); final notifier = ref.read(settingsProvider.notifier); signatureState.value = notifier.getSignatureHtmlGlobal(); await notifier.update( settings.withoutSignatures(), ); } }, ), DensePlatformIconButton( icon: Icon(CommonPlatformIcons.ok), onPressed: () => context.pop(true), ), ], ); final usedEditorApi = editorApi; if ((result ?? false) && usedEditorApi != null) { final newSignature = await usedEditorApi.getText(); signatureState.value = newSignature; if (account == null) { final settings = ref.read(settingsProvider); await ref.read(settingsProvider.notifier).update( settings.copyWith(signatureHtml: newSignature), ); } else { account.signatureHtml = newSignature; unawaited(ref.read(realAccountsProvider.notifier).save()); } } } if (signature == null) { return PlatformListTile( leading: const Icon(Icons.add), title: Text( ref.text.signatureSettingsAddForAccount(account?.name ?? ''), ), onTap: showEditor, ); } return Stack( children: [ HtmlWidget( signature, onTapUrl: (url) => launcher.launchUrl(Uri.parse(url)), ), Align( alignment: Alignment.topRight, child: PlatformIconButton( icon: const Icon(Icons.edit), onPressed: showEditor, ), ), ], ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/editor_extensions.dart
import 'package:community_material_icon/community_material_icon.dart'; import 'package:enough_ascii_art/enough_ascii_art.dart'; import 'package:enough_html_editor/enough_html_editor.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../localization/extension.dart'; import '../util/localized_dialog_helper.dart'; /// A button to open the art extension dialog. class EditorArtExtensionButton extends ConsumerWidget { /// Creates a new [EditorArtExtensionButton]. const EditorArtExtensionButton({super.key, required this.editorApi}); /// The editor API. final HtmlEditorApi editorApi; @override Widget build(BuildContext context, WidgetRef ref) => PlatformIconButton( icon: const Icon(CommunityMaterialIcons.format_font), onPressed: () => showArtExtensionDialog(ref, editorApi), ); /// Shows the art extension dialog. static void showArtExtensionDialog( WidgetRef ref, HtmlEditorApi editorApi, ) { //final localizations = ref.text; LocalizedDialogHelper.showWidgetDialog( ref, _EditorArtExtensionWidget(editorApi: editorApi), defaultActions: DialogActions.cancel, ); } } class _EditorArtExtensionWidget extends StatefulHookConsumerWidget { const _EditorArtExtensionWidget({required this.editorApi}); final HtmlEditorApi editorApi; @override ConsumerState<_EditorArtExtensionWidget> createState() => _EditorArtExtensionWidgetState(); } class _EditorArtExtensionWidgetState extends ConsumerState<_EditorArtExtensionWidget> { final _inputController = TextEditingController(); final _textsByUnicodeFont = <UnicodeFont, String>{}; @override void initState() { super.initState(); widget.editorApi.getSelectedText().then((value) { _updateTexts(value); _inputController.text = value ?? ''; }); } @override Widget build(BuildContext context) { final localizations = ref.text; final captions = { UnicodeFont.serifBold: localizations.fontSerifBold, UnicodeFont.serifItalic: localizations.fontSerifItalic, UnicodeFont.serifBoldItalic: localizations.fontSerifBoldItalic, UnicodeFont.sans: localizations.fontSans, UnicodeFont.sansBold: localizations.fontSansBold, UnicodeFont.sansItalic: localizations.fontSansItalic, UnicodeFont.sansBoldItalic: localizations.fontSansBoldItalic, UnicodeFont.script: localizations.fontScript, UnicodeFont.scriptBold: localizations.fontScriptBold, UnicodeFont.fraktur: localizations.fontFraktur, UnicodeFont.frakturBold: localizations.fontFrakturBold, UnicodeFont.monospace: localizations.fontMonospace, // cSpell: disable UnicodeFont.fullwidth: localizations.fontFullwidth, UnicodeFont.doublestruck: localizations.fontDoublestruck, // cSpell: enable UnicodeFont.capitalized: localizations.fontCapitalized, UnicodeFont.circled: localizations.fontCircled, UnicodeFont.parenthesized: localizations.fontParenthesized, UnicodeFont.underlinedSingle: localizations.fontUnderlinedSingle, UnicodeFont.underlinedDouble: localizations.fontUnderlinedDouble, // cSpell: disable UnicodeFont.strikethroughSingle: localizations.fontStrikethroughSingle, // cSpell: enable }; final captionStyle = Theme.of(context).textTheme.bodySmall; return SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(bottom: 8), child: DecoratedPlatformTextField( controller: _inputController, onChanged: _updateTexts, decoration: InputDecoration( labelText: localizations.editorArtInputLabel, hintText: localizations.editorArtInputHint, ), ), ), for (final unicodeFont in UnicodeFont.values) if (unicodeFont != UnicodeFont.normal) ...[ Text( captions[unicodeFont] ?? '', style: captionStyle, ), PlatformTextButton( child: Text( _textsByUnicodeFont[unicodeFont] ?? localizations.editorArtWaitingForInputHint, ), onPressed: () { final text = _textsByUnicodeFont[unicodeFont]; if (text != null && text.isNotEmpty) { widget.editorApi.insertText(text); } context.pop(); }, ), const Divider(), ], ], ), ); } void _updateTexts(final String? input) { for (final unicodeFont in UnicodeFont.values) { if (unicodeFont != UnicodeFont.normal) { _textsByUnicodeFont[unicodeFont] = UnicodeFontConverter.encode(input ?? 'hello world', unicodeFont); } } setState(() {}); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/attachment_compose_bar.dart
import 'package:enough_giphy_flutter/enough_giphy_flutter.dart'; import 'package:enough_icalendar/enough_icalendar.dart'; import 'package:enough_mail/enough_mail.dart'; import 'package:enough_media/enough_media.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:http/http.dart' as http; import '../app_lifecycle/provider.dart'; import '../keys/service.dart'; import '../localization/app_localizations.g.dart'; import '../localization/extension.dart'; import '../models/compose_data.dart'; import '../models/message.dart'; import '../routes/routes.dart'; import '../settings/theme/icon_service.dart'; import '../util/localized_dialog_helper.dart'; import 'ical_composer.dart'; import 'icon_text.dart'; class _AttachmentMediaProviderFactory { static MediaProvider fromAttachmentInfo(AttachmentInfo info) => MemoryMediaProvider( info.name ?? '', info.mediaType.text, info.data ?? Uint8List(0), ); } /// Allows to add attachments to a [ComposeData] class AttachmentComposeBar extends StatefulWidget { /// Creates a new [AttachmentComposeBar] const AttachmentComposeBar({ super.key, required this.composeData, this.isDownloading = false, }); /// The associated [ComposeData] final ComposeData composeData; /// Set to true if the attachments are currently downloading final bool isDownloading; @override State<AttachmentComposeBar> createState() => _AttachmentComposeBarState(); } class _AttachmentComposeBarState extends State<AttachmentComposeBar> { late List<AttachmentInfo> _attachments; @override void initState() { _attachments = widget.composeData.messageBuilder.attachments; super.initState(); } @override Widget build(BuildContext context) => Wrap( children: [ for (final attachment in _attachments) _ComposeAttachment( parentMessage: widget.composeData.originalMessage, attachment: attachment, onRemove: removeAttachment, ), if (widget.isDownloading) const PlatformProgressIndicator(), AddAttachmentPopupButton( composeData: widget.composeData, update: () => setState(() {}), ), ], ); void removeAttachment(AttachmentInfo attachment) { widget.composeData.messageBuilder.removeAttachment(attachment); setState(() { _attachments.remove(attachment); }); } } class AddAttachmentPopupButton extends ConsumerWidget { const AddAttachmentPopupButton({ super.key, required this.composeData, required this.update, }); final ComposeData composeData; final Function() update; @override Widget build(BuildContext context, WidgetRef ref) { void ignoreNextResume() => ref .read(appLifecycleProvider.notifier) .ignoreNextInactivationCycle(timeout: const Duration(seconds: 120)); final localizations = ref.text; final iconService = IconService.instance; const brightness = Brightness.light; // TODO(RV): implement brightness access // themeService.brightness(context); return PlatformPopupMenuButton<int>( icon: Icon(CommonPlatformIcons.add), itemBuilder: (context) => [ PlatformPopupMenuItem( value: 0, child: IconText( icon: Icon(iconService.mediaFile), label: Text(localizations.attachTypeFile), brightness: brightness, ), ), PlatformPopupMenuItem( value: 1, child: IconText( icon: Icon(iconService.mediaPhoto), label: Text(localizations.attachTypePhoto), brightness: brightness, ), ), PlatformPopupMenuItem( value: 2, child: IconText( icon: Icon(iconService.mediaVideo), label: Text(localizations.attachTypeVideo), brightness: brightness, ), ), PlatformPopupMenuItem( value: 3, child: IconText( icon: Icon(iconService.mediaAudio), label: Text(localizations.attachTypeAudio), brightness: brightness, ), ), PlatformPopupMenuItem( value: 4, child: IconText( icon: Icon(iconService.location), label: Text(localizations.attachTypeLocation), brightness: brightness, ), ), if (KeyService.instance.hasGiphy) PlatformPopupMenuItem( value: 5, child: IconText( icon: Icon(iconService.mediaGif), label: Text(localizations.attachTypeGif), brightness: brightness, ), ), PlatformPopupMenuItem( value: 6, child: IconText( icon: Icon(iconService.appointment), label: Text(localizations.attachTypeAppointment), brightness: brightness, ), ), ], onSelected: (value) async { var changed = false; switch (value) { case 0: // any file ignoreNextResume(); changed = await _addAttachmentFile(); break; case 1: // photo file ignoreNextResume(); changed = await _addAttachmentFile( fileType: FileType.image, ); break; case 2: // video file ignoreNextResume(); changed = await _addAttachmentFile( fileType: FileType.video, ); break; case 3: // audio file ignoreNextResume(); changed = await _addAttachmentFile( fileType: FileType.audio, ); break; case 4: // location if (context.mounted) { final result = await context.pushNamed<Uint8List>(Routes.locationPicker); if (result != null) { composeData.messageBuilder.addBinary( result, MediaSubtype.imagePng.mediaType, filename: 'location.jpg', ); changed = true; } } break; case 5: // gif / sticker / emoji file if (context.mounted) { changed = await addAttachmentGif(ref, localizations); } break; case 6: // appointment if (context.mounted) { changed = await addAttachmentAppointment(context, ref, localizations); } break; } if (changed) { update(); } }, ); } Future<bool> _addAttachmentFile({ FileType fileType = FileType.any, }) async { final result = await FilePicker.platform .pickFiles(type: fileType, allowMultiple: true, withData: true); if (result == null) { return false; } for (final file in result.files) { final path = file.path; final bytes = file.bytes; if (path == null || bytes == null) { continue; } final lastDotIndex = path.lastIndexOf('.'); MediaType mediaType; if (lastDotIndex == -1 || lastDotIndex == path.length - 1) { mediaType = MediaType.fromSubtype(MediaSubtype.applicationOctetStream); } else { final ext = path.substring(lastDotIndex + 1); mediaType = MediaType.guessFromFileExtension(ext); } composeData.messageBuilder .addBinary(bytes, mediaType, filename: file.name); } return true; } Future<bool> addAttachmentGif( WidgetRef ref, AppLocalizations localizations, ) async { final giphy = KeyService.instance.giphy; if (giphy == null) { await LocalizedDialogHelper.showTextDialog( ref, localizations.errorTitle, 'No GIPHY API key found. Please check set up instructions.', ); return false; } final gif = await Giphy.getGif( context: ref.context, apiKey: giphy, // searchLabelText: searchSticker // ? localizations.attachTypeStickerSearch // : localizations.attachTypeGifSearch, lang: localizations.localeName, keepState: true, showPreview: true, // sticker: searchSticker, // showPreviewPage: false, ); final contentUrl = gif?.recommendedMobileSend.url; if (gif == null || contentUrl == null) { return false; } final response = await http.get(Uri.parse(contentUrl)); if (response.statusCode != 200) { return false; } final data = response.bodyBytes; composeData.messageBuilder.addBinary( data, MediaType.fromSubtype(MediaSubtype.imageGif), filename: '${gif.title}.gif', ); return true; } Future<bool> addAttachmentAppointment( BuildContext context, WidgetRef ref, AppLocalizations localizations, ) async { final appointment = await IcalComposer.createOrEditAppointment(context, ref); if (appointment != null) { // idea: add some sort of finalizer that updates the appointment // at the end to set the organizer and the attendees final text = appointment.toString(); final attachmentBuilder = composeData.messageBuilder.addText( text, mediaType: MediaType.fromText('application/ics'), disposition: ContentDispositionHeader.from( ContentDisposition.attachment, filename: 'invite.ics', ), ); attachmentBuilder.contentType?.setParameter('method', 'REQUEST'); final finalizer = _AppointmentFinalizer(appointment, attachmentBuilder); composeData.addFinalizer(finalizer.finalize); } return (appointment != null); } } class _AppointmentFinalizer { _AppointmentFinalizer(this.appointment, this.attachmentBuilder); final VCalendar appointment; final PartBuilder attachmentBuilder; void finalize(MessageBuilder messageBuilder) { final event = appointment.event; if (event == null) { return; } void addAttendee({ required String email, required String? name, bool rsvp = true, ParticipantStatus? participantStatus, }) { final attendeeProperty = AttendeeProperty.create( attendeeEmail: email, commonName: name, rsvp: rsvp, participantStatus: participantStatus, ); if (attendeeProperty != null) { event.addAttendee(attendeeProperty); } } final from = messageBuilder.from; if (from != null && from.isNotEmpty) { final organizer = from.first; event.organizer = OrganizerProperty.create( email: organizer.email, commonName: organizer.personalName, ); addAttendee( email: organizer.email, name: organizer.personalName, rsvp: false, participantStatus: ParticipantStatus.accepted, ); } final recipients = <MailAddress>[]; void addRecipients(List<MailAddress>? addresses) { if (addresses != null) { recipients.addAll(addresses); } } addRecipients(messageBuilder.to); addRecipients(messageBuilder.cc); for (final mailAddress in recipients) { addAttendee(email: mailAddress.email, name: mailAddress.personalName); } attachmentBuilder.text = appointment.toString(); } } class _ComposeAttachment extends ConsumerWidget { const _ComposeAttachment({ required this.parentMessage, required this.attachment, required this.onRemove, }); final Message? parentMessage; final AttachmentInfo attachment; final void Function(AttachmentInfo attachment) onRemove; @override Widget build(BuildContext context, WidgetRef ref) { final localizations = ref.text; final parentMessage = this.parentMessage; return Padding( padding: const EdgeInsets.only(right: 8), child: ClipRRect( borderRadius: BorderRadius.circular(8), child: PreviewMediaWidget( mediaProvider: _AttachmentMediaProviderFactory.fromAttachmentInfo(attachment), width: 60, height: 60, showInteractiveDelegate: (interactiveMedia) async { final attachmentData = attachment.data; if (attachment.mediaType.sub == MediaSubtype.messageRfc822 && parentMessage != null && attachmentData != null) { final mime = MimeMessage.parseFromData(attachmentData); final message = Message.embedded(mime, parentMessage); return context.pushNamed( Routes.mailDetails, extra: message, ); } final attachmentText = attachment.part.text; if (attachmentText != null && (attachment.mediaType.sub == MediaSubtype.applicationIcs || attachment.mediaType.sub == MediaSubtype.textCalendar)) { final appointment = VComponent.parse(attachmentText) as VCalendar; final update = await IcalComposer.createOrEditAppointment( context, ref, appointment: appointment, ); if (update != null) { attachment.part.text = update.toString(); } return Future.value(); } return context.pushNamed( Routes.interactiveMedia, extra: interactiveMedia, ); }, contextMenuEntries: [ PopupMenuItem<String>( value: 'remove', child: Text( localizations.composeRemoveAttachmentAction( attachment.name ?? '', ), ), ), ], onContextMenuSelected: (provider, value) => onRemove(attachment), ), ), ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/message_stack.dart
import 'dart:math'; import 'package:enough_mail/enough_mail.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../localization/extension.dart'; import '../models/message.dart'; import '../models/message_source.dart'; import '../scaffold_messenger/service.dart'; import 'mail_address_chip.dart'; enum _DragAction { noted, later, delete, reply } /// A stack of messages that can be processed. class MessageStack extends StatefulHookConsumerWidget { /// Creates a new [MessageStack] widget. const MessageStack({super.key, required this.messageSource}); /// The message source from which the messages are taken. final MessageSource messageSource; @override ConsumerState<MessageStack> createState() => _MessageStackState(); } class _MessageStackState extends ConsumerState<MessageStack> { static final _random = Random(); int _currentMessageIndex = 0; Message? _currentMessage; double? _currentAngle; final List<Message> _nextMessages = []; final List<double> _nextAngles = []; double createAngle() => (_random.nextInt(200) - 100.0) / 4000; @override void initState() { // _currentMessage = widget.messageSource!.getMessageAt(0); // _currentAngle = createAngle(); // for (var i = 1; i < math.min(3, widget.messageSource!.size); i++) { // _nextMessages.add(widget.messageSource!.getMessageAt(i)); // _nextAngles.add(createAngle()); // } super.initState(); } void moveToNextMessage() { setState(() { _currentMessageIndex++; if (_nextMessages.isEmpty) { _currentMessage = null; } else { _currentMessage = _nextMessages.first; _currentAngle = _nextAngles.first; _nextMessages.removeAt(0); _nextAngles.removeAt(0); if (widget.messageSource.size > _currentMessageIndex + 3) { // _nextMessages.add( // widget.messageSource!.getMessageAt(_currentMessageIndex + 3)); _nextAngles.add(createAngle()); } } }); } void moveToPreviousMessage() { final currentMessage = _currentMessage; if (currentMessage != null && _currentMessageIndex > 0) { setState(() { _nextMessages.insert(0, currentMessage); _nextAngles.insert(0, createAngle()); _currentMessageIndex--; // _currentMessage = // widget.messageSource!.getMessageAt(_currentMessageIndex); }); } } @override Widget build(BuildContext context) { final quickReplies = ['OK', 'Thank you!', '👍', '😊']; final dateTime = _currentMessage?.mimeMessage.decodeDate(); final dayName = dateTime == null ? '' : ref.formatDay(dateTime); final currentMessage = _currentMessage; return Stack( alignment: Alignment.center, fit: StackFit.expand, children: [ // center: stack of messages for (var i = _nextMessages.length; --i >= 0;) Padding( padding: const EdgeInsets.all(30), child: MessageCard( message: _nextMessages[i], angle: _nextAngles[i], ), ), // top right: day of message Align( alignment: Alignment.topRight, child: Padding( padding: const EdgeInsets.all(8), child: Text( dayName, style: Theme.of(context).textTheme.bodySmall, ), ), ), // right: delete Align( alignment: Alignment.centerRight, child: _MessageDragTarget( action: _DragAction.delete, onComplete: acceptDragOperation, width: 100, height: 200, ), ), // top: noted (read) Align( alignment: Alignment.topCenter, child: _MessageDragTarget( action: _DragAction.noted, onComplete: acceptDragOperation, width: 200, height: 100, ), ), // left: later Align( alignment: Alignment.centerLeft, child: _MessageDragTarget( action: _DragAction.later, onComplete: acceptDragOperation, width: 100, height: 200, ), ), // bottom: quick replies Align( alignment: Alignment.bottomCenter, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ...quickReplies.map( (reply) => _MessageDragTarget( data: reply, action: _DragAction.reply, onComplete: acceptDragOperation, width: 50, height: 100, ), ), ], ), ), // bottom left: back Align( alignment: Alignment.bottomLeft, child: Padding( padding: const EdgeInsets.all(8), child: PlatformIconButton( icon: const Icon(Icons.arrow_back), onPressed: _currentMessageIndex == 0 ? null : moveToPreviousMessage, ), ), ), // center: first / current message if (currentMessage != null) Padding( padding: const EdgeInsets.all(30), child: _MessageDraggable( message: currentMessage, angle: _currentAngle ?? 0, ), ) else const Padding( padding: EdgeInsets.all(30), child: Center(child: Text('All messages processed, well done!')), ), ], ); } Future<void> acceptDragOperation( Message message, _DragAction action, { Object? data, }) async { moveToNextMessage(); //print('drag operation: $action'); String? snack; late Future<void> Function() undo; switch (action) { case _DragAction.noted: if (!message.isSeen) { await message.source.markAsSeen(message, true); snack = 'mark as read'; } break; case _DragAction.later: // nothing to do, just move on? break; case _DragAction.delete: // TODO(RV): remove from message source await message.source.storeMessageFlags( [message], [MessageFlags.deleted], ); snack = 'deleted'; undo = () => message.source.storeMessageFlags( [message], [MessageFlags.deleted], action: StoreAction.remove, ); // TODO(RV): add re-integration into message source break; case _DragAction.reply: // TODO(RV): implement quick reply snack = 'replied with $data'; break; } if (snack != null) { if (context.mounted) { // TODO(RV): allow undo when marking as deleted ScaffoldMessengerService.instance.showTextSnackBar( ref.text, snack, undo: () async { // bring back message: setState(() { _currentMessage = message; _currentMessageIndex = message.sourceIndex; }); await undo(); }, ); } } } } class _MessageDragTarget extends StatefulWidget { const _MessageDragTarget({ required this.action, required this.onComplete, this.data, this.width, this.height, }); final _DragAction action; final Object? data; final Function(Message message, _DragAction action, {Object? data}) onComplete; final double? width; final double? height; @override State<_MessageDragTarget> createState() => _MessageDragTargetState(); } class _MessageDragTargetState extends State<_MessageDragTarget> { late double width; late double height; Color? color; late String text; double? _originalWidth; double? _originalHeight; Color? _originalColor; @override void initState() { width = widget.width ?? 100; height = widget.height ?? 100; switch (widget.action) { case _DragAction.noted: color = Colors.green[300]; text = 'Noted'; break; case _DragAction.later: color = Colors.yellow[300]; text = 'Later'; break; case _DragAction.delete: color = Colors.red[300]; text = 'Delete'; break; case _DragAction.reply: color = Colors.yellow[300]; text = widget.data?.toString() ?? 'Reply'; break; } _originalWidth = width; _originalHeight = height; _originalColor = color; super.initState(); } void startAccepting() { final originalWidth = _originalWidth; if (originalWidth != null && width == originalWidth) { setState(() { width = originalWidth * 1.2; height = (_originalHeight ?? originalWidth) * 1.2; color = Color.lerp(_originalColor, Colors.black, 0.3); }); } } void endAccepting() { setState(() { width = _originalWidth ?? 100; height = _originalHeight ?? 100; color = _originalColor; }); } @override Widget build(BuildContext context) => DragTarget<Message>( builder: (context, candidateData, rejectedData) => Padding( padding: const EdgeInsets.all(8), child: AnimatedContainer( decoration: BoxDecoration( color: color, borderRadius: BorderRadius.circular(width / 5), ), width: width, height: height, alignment: Alignment.centerLeft, duration: const Duration(milliseconds: 200), curve: Curves.bounceOut, child: Center(child: Text(text)), ), ), onWillAccept: (data) { startAccepting(); return true; }, onAccept: (data) async { endAccepting(); widget.onComplete(data, widget.action, data: widget.data); }, onLeave: (data) => endAccepting(), ); } class _MessageDraggable extends StatefulWidget { const _MessageDraggable({ required this.message, required this.angle, }); final Message message; final double angle; @override State<_MessageDraggable> createState() => _MessageDraggableState(); } class _MessageDraggableState extends State<_MessageDraggable> with TickerProviderStateMixin { late AnimationController _animationController; late Animation<double> _scaleAnimation; @override void initState() { _animationController = AnimationController( vsync: this, duration: const Duration(milliseconds: 400), ); _scaleAnimation = CurvedAnimation( curve: Curves.easeInOut, parent: Tween<double>(begin: 1, end: 0.5).animate(_animationController), ); super.initState(); } @override void dispose() { _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) => LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) => Draggable<Message>( data: widget.message, feedback: ConstrainedBox( constraints: constraints, child: ScaleTransition( scale: _scaleAnimation, child: FadeTransition( opacity: _scaleAnimation, child: MessageCard( message: widget.message, angle: widget.angle, ), ), ), ), childWhenDragging: Container(), maxSimultaneousDrags: 1, onDragStarted: () { _animationController ..reset() ..forward(); }, child: MessageCard(message: widget.message, angle: widget.angle), ), ); } class MessageCard extends StatefulWidget { const MessageCard({super.key, required this.message, required this.angle}); final Message message; final double angle; @override State<MessageCard> createState() => _MessageCardState(); } class _MessageCardState extends State<MessageCard> { @override void initState() { widget.message.addListener(_update); super.initState(); } @override void dispose() { widget.message.removeListener(_update); super.dispose(); } void _update() { setState(() {}); } @override Widget build(BuildContext context) => Transform.rotate( angle: widget.angle, child: Card( elevation: 18, child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(8), child: widget.message.mimeMessage.isEmpty ? const Text('...') : buildMessageContents(), ), ), ), ); Widget buildMessageContents() { final mime = widget.message.mimeMessage; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(mime.decodeSubject() ?? ''), Row( children: [ const Text('From '), for (final address in mime.from ?? const []) MailAddressChip(mailAddress: address), ], ), if (mime.to?.isNotEmpty ?? false) Wrap( children: [ const Text('To '), for (final address in mime.to ?? const []) MailAddressChip(mailAddress: address), ], ), if (mime.cc?.isNotEmpty ?? false) Wrap( children: [ const Text('CC '), for (final address in mime.cc ?? const []) MailAddressChip(mailAddress: address), ], ), buildContent(), ], ); } Widget buildContent() { // TODO(RV): do not download or display the content // when the widget is not exposed, unless the content is there already if (!widget.message.mimeMessage.isDownloaded) { return FutureBuilder( future: downloadMessageContents(widget.message), builder: (context, snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: case ConnectionState.waiting: case ConnectionState.active: return const Center(child: PlatformProgressIndicator()); case ConnectionState.done: if (snapshot.hasError) { return const Text('Unable to download message'); } break; } return buildMessageContent(context); }, ); } return buildMessageContent(context); } Future<Message> downloadMessageContents(Message message) async { try { final mime = await message.source.fetchMessageContents(message); if (mime.isNewsletter || mime.hasAttachments()) { setState(() {}); } } on MailException catch (e) { if (kDebugMode) { print('unable to download message contents: $e'); } } return message; } Widget buildMessageContent(BuildContext context) { // var html = widget.message.decodeAndStripHtml(); // if (html != null && false) { // String contentBase64 = base64Encode(const Utf8Encoder().convert(html)); // return WebView( // key: ValueKey(widget.message), // javascriptMode: JavascriptMode.disabled, // gestureRecognizers: null, // initialUrl: 'data:text/html;base64,$contentBase64', // onWebViewCreated: (controller) { // //_webViewController = controller; // //controller. // print('created webview'); // }, // onPageFinished: (url) { // print('finished loading page'); // TODO(RV): inject JS to query size? // }, // ); // } // if (html != null && html.indexOf(' colspan=') == -1) { // Html( // data: html, // onLinkTap: (url) => urlLauncher.launch(url), // ); // } final text = widget.message.mimeMessage.decodeTextPlainPart(); if (text != null) { return SelectableText(text); } // TODO(RV): add other content, attachments, etc return Text( 'Unsupported content: ${widget.message.mimeMessage.mediaType.text}', ); } }
0