repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/Flutter-Practice-Projects/Sliver App Bar ,Collapsing Toolbar
mirrored_repositories/Flutter-Practice-Projects/Sliver App Bar ,Collapsing Toolbar/lib/main.dart
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( body: CustomScrollView( slivers: [ SliverAppBar( expandedHeight: 200, floating: false, pinned: true, flexibleSpace: FlexibleSpaceBar( title: Text("Sliver app bar"), background: Image.network( "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1024px-Image_created_with_a_mobile_phone.png", fit: BoxFit.cover, ), ), ), SliverFillRemaining( child: Center( child: Column( 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), ), ); } }
0
mirrored_repositories/Flutter-Practice-Projects/Sliver App Bar ,Collapsing Toolbar
mirrored_repositories/Flutter-Practice-Projects/Sliver App Bar ,Collapsing Toolbar/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:project001/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/Onboarding_Ui_Flutter
mirrored_repositories/Onboarding_Ui_Flutter/lib/onboarding_screen.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class OnBoardScreen extends StatelessWidget { const OnBoardScreen({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ SizedBox(height: 40), Container( width: MediaQuery.of(context).size.width * 0.80, child: Image.asset("assets/img_src_1.jpg")), SizedBox(height: 20), Text( "Plan your trip", style: GoogleFonts.roboto(fontSize: 20), textAlign: TextAlign.center, ), SizedBox(height: 40), Text( "Travel around the world to know \n and get to know people", style: GoogleFonts.roboto(fontSize: 20), textAlign: TextAlign.center, ), ], ); } } class OnBoardScreen1 extends StatelessWidget { const OnBoardScreen1({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ SizedBox(height: 40), Container( width: MediaQuery.of(context).size.width * 0.80, child: Image.asset("assets/img_src_2.jpg")), SizedBox(height: 20), Text( "Select a date", style: GoogleFonts.roboto(fontSize: 20), textAlign: TextAlign.center, ), SizedBox(height: 40), Text( "Select a date, Book your ticket, Choose \n your travel partner", style: GoogleFonts.roboto(fontSize: 20), textAlign: TextAlign.center, ), ], ); } } class OnBoardScreen2 extends StatelessWidget { const OnBoardScreen2({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ SizedBox(height: 40), Container( width: MediaQuery.of(context).size.width * 0.80, child: Image.asset("assets/img_src_3.jpg")), SizedBox(height: 20), Text( "Enjoy your trip", style: GoogleFonts.roboto(fontSize: 20), textAlign: TextAlign.center, ), SizedBox(height: 40), Text( "Enjoy your holiday , Enjoy your ride \n with your loved ones", style: GoogleFonts.roboto(fontSize: 20), textAlign: TextAlign.center, ), ], ); } }
0
mirrored_repositories/Onboarding_Ui_Flutter
mirrored_repositories/Onboarding_Ui_Flutter/lib/main.dart
import 'package:flutter/material.dart'; import 'package:onboarding_ui/onboarding_ui.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { const MyApp({Key key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Travel UI', home: OnBoardingUI(), ); } }
0
mirrored_repositories/Onboarding_Ui_Flutter
mirrored_repositories/Onboarding_Ui_Flutter/lib/onboarding_ui.dart
import 'package:flutter/material.dart'; import 'package:onboarding_ui/onboarding_screen.dart'; class OnBoardingUI extends StatefulWidget { @override _OnBoardingUIState createState() => _OnBoardingUIState(); } class _OnBoardingUIState extends State<OnBoardingUI> { final int _numPages = 3; final PageController _pageController = PageController(initialPage: 0); int _currentPage = 0; List<Widget> _buildIndicator() { List<Widget> list = []; for (int i = 0; i < _numPages; i++) { list.add(i == _currentPage ? _indicator(true) : _indicator(false)); } return list; } Widget _indicator(bool isActive) { return AnimatedContainer( duration: Duration(milliseconds: 150), margin: EdgeInsets.symmetric(horizontal: 8.0), height: 10.0, width: 10.0, decoration: BoxDecoration( color: isActive ? Colors.red : Colors.black, borderRadius: BorderRadius.all(Radius.circular(12)), ), ); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: Column( children: <Widget>[ Expanded( child: PageView( controller: _pageController, physics: ClampingScrollPhysics(), onPageChanged: (int page) { setState(() { _currentPage = page; }); }, children: <Widget>[ OnBoardScreen(), OnBoardScreen1(), OnBoardScreen2(), ], ), ), Align( alignment: Alignment.bottomCenter, child: Padding( padding: const EdgeInsets.all(20.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ FlatButton( onPressed: () { _pageController.animateToPage(2, duration: Duration( milliseconds: 500, ), curve: Curves.easeInToLinear); }, child: Text("Skip", style: TextStyle(color: Colors.grey, fontSize: 16))), Row( mainAxisAlignment: MainAxisAlignment.center, children: _buildIndicator()), FlatButton( onPressed: () { _pageController.nextPage( duration: Duration( milliseconds: 500, ), curve: Curves.easeInToLinear, ); }, child: Text("Next", style: TextStyle(color: Colors.red, fontSize: 16))) ], ), ), ), ], ), ), ); } }
0
mirrored_repositories/Flutter-Blog-App-Firebase
mirrored_repositories/Flutter-Blog-App-Firebase/lib/ProfilePage.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:transparent_image/transparent_image.dart'; String username, userid, useremail, userphotourl; class ProfilePage extends StatefulWidget { ProfilePageState createState() => new ProfilePageState(); } class ProfilePageState extends State<ProfilePage> { bool loggedIn = false; Future<Null> _function() async { SharedPreferences prefs; prefs = await SharedPreferences.getInstance(); this.setState(() { if (prefs.getString("username") != null) { loggedIn = true; username = prefs.getString("username"); userid = prefs.getString("userid"); useremail = prefs.getString("useremail"); userphotourl = prefs.getString("userphotourl"); } else { loggedIn = false; } }); } @override Widget build(BuildContext context) { // print(username); // print(userid); // print(useremail); // print(userphotourl); return new MaterialApp( home: new Scaffold( appBar: new AppBar( title: new Text("Profile"), ), body: new Container( alignment: Alignment.center, child: new Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisSize: MainAxisSize.min, children: <Widget>[ new Padding( padding: const EdgeInsets.all(16.0), child: new FadeInImage.memoryNetwork( placeholder: kTransparentImage, image: userphotourl, height: 150.0, width: 150.0, fadeInDuration: const Duration(milliseconds: 1000), alignment: Alignment.topCenter, fit: BoxFit.contain, ), ), new Padding( padding: const EdgeInsets.fromLTRB(0.0, 16.0, 0.0, 8.0), child: new Text( username, style: new TextStyle( fontSize: 22.0, fontWeight: FontWeight.bold), ), ), new Text( useremail, style: new TextStyle(fontSize: 18.0,color: Colors.blueAccent), ), ], ), ), ), ); } @override void initState() { super.initState(); this._function(); } }
0
mirrored_repositories/Flutter-Blog-App-Firebase
mirrored_repositories/Flutter-Blog-App-Firebase/lib/ChatRow.dart
import 'package:flutter/material.dart'; import 'package:firebase_database/firebase_database.dart'; @override class ChatRow extends StatelessWidget { final DataSnapshot snapshot; ChatRow(this.snapshot); @override Widget build(BuildContext context) { return new Container( margin: const EdgeInsets.symmetric(vertical: 10.0), child: new Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Container( margin: const EdgeInsets.only(right: 16.0), child: new CircleAvatar( backgroundImage: new NetworkImage(snapshot.value['profileUrl'])), ), new Expanded( child: new Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Text(snapshot.value['messageUser'], style: Theme.of(context).textTheme.subhead), new Container( margin: const EdgeInsets.only(top: 5.0), child: new Text(snapshot.value['messageText']), ), ], ), ), ], ), ); } }
0
mirrored_repositories/Flutter-Blog-App-Firebase
mirrored_repositories/Flutter-Blog-App-Firebase/lib/BlogRow.dart
import 'package:flutter/material.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:transparent_image/transparent_image.dart'; @override class BlogRow extends StatelessWidget { final DataSnapshot snapshot; BlogRow(this.snapshot); bool _liked = false; @override Widget build(BuildContext context) { // var size = MediaQuery.of(context).size; // final double itemHeight = (size.height - kToolbarHeight - 24) / 2.2; // final double itemWidth = size.width; return new Container( child: new InkWell( child: new Card( elevation: 2.5, child: new Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new FadeInImage.memoryNetwork( placeholder: kTransparentImage, image: snapshot.value['IMAGE'], alignment: Alignment.topCenter, fit: BoxFit.contain, ), // new Image.network(snapshot.value['IMAGE']), new Padding( padding: const EdgeInsets.fromLTRB(8.0, 8.0, 0.0, 0.0), child: new Text( snapshot.value['Title'], style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0), ), ), new Padding( padding: const EdgeInsets.fromLTRB(8.0, 8.0, 0.0, 0.0), child: new Text( snapshot.value['DESCRIPTION'], style: new TextStyle( fontWeight: FontWeight.normal, fontSize: 16.0), ), ), new Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ new Text(snapshot.value['username'], style: new TextStyle(color: Colors.blueAccent)), new IconButton( icon: _liked ? new Icon( Icons.favorite, color: Colors.blueAccent, ) : new Icon( Icons.favorite_border, color: Colors.blueAccent, ), onPressed: () { Scaffold.of(context).showSnackBar(new SnackBar( content: new Text("Coming Soon!"), )); }), ], ), ], ), ), onTap: (){ Scaffold.of(context).showSnackBar(new SnackBar( content: new Text("Clicked on Blog "+snapshot.value['Title']), )); }, ), ); } }
0
mirrored_repositories/Flutter-Blog-App-Firebase
mirrored_repositories/Flutter-Blog-App-Firebase/lib/PostBlogPage.dart
import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_blog_app/HomePage.dart'; import 'package:flutter_blog_app/main.dart'; import 'package:image_picker/image_picker.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; final googleSignIn = new GoogleSignIn(); final analytics = new FirebaseAnalytics(); final auth = FirebaseAuth.instance; final reference = FirebaseDatabase.instance.reference().child('Blogs'); Future<Null> _ensureLoggedIn() async { GoogleSignInAccount user = googleSignIn.currentUser; if (user == null) user = await googleSignIn.signInSilently(); if (user == null) { user = await googleSignIn.signIn(); analytics.logLogin(); } if (await auth.currentUser() == null) { GoogleSignInAuthentication credentials = await googleSignIn.currentUser.authentication; await auth.signInWithGoogle( idToken: credentials.idToken, accessToken: credentials.accessToken, ); } } class PostBlogPage extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( routes: <String, WidgetBuilder>{ "/home": (BuildContext context) => new HomePage(), }, home: new Scaffold( appBar: new AppBar( title: new Text('Post Blog..'), ), body: new _PostPage()), ); } } class _PostPage extends StatefulWidget { @override _PostPageState createState() => new _PostPageState(); } class _PostPageState extends State<_PostPage> { File _image; final TextEditingController _title = new TextEditingController(); final TextEditingController _desc = new TextEditingController(); bool _isTitle = false; bool _isDesc = false; bool _isImage = false; bool _isLoading = false; Future getImage() async { var image = await ImagePicker.pickImage(source: ImageSource.gallery); setState(() { _image = image; }); } @override Widget build(BuildContext context) { return new Container( child: new SingleChildScrollView( scrollDirection: Axis.vertical, reverse: true, child: new Container( child: new Column( children: <Widget>[ new Padding( padding: const EdgeInsets.only(top: 24.0), child: _isLoading ? new CircularProgressIndicator() : null, ), new Padding(padding: const EdgeInsets.only(top: 24.0)), new InkWell( child: _image == null ? new Image.asset( 'assets/img/img-placeholder.jpg', height: 200.0, width: 300.0, fit: BoxFit.fill, ) : new Image.file( _image, height: 200.0, width: 300.0, ), onTap: () { getImage(); _isImage = true; }, ), new Padding( padding: const EdgeInsets.all(20.0), child: new TextField( controller: _title, style: new TextStyle( color: Colors.black, fontSize: 18.0, ), onChanged: (String text) { setState(() { _isTitle = text.length > 0; }); }, decoration: new InputDecoration.collapsed( hintText: "Title", border: new UnderlineInputBorder( borderSide: const BorderSide( color: Colors.blueAccent, style: BorderStyle.solid, width: 5.0), ), ), ), ), new Padding( padding: const EdgeInsets.all(20.0), child: new TextField( controller: _desc, style: new TextStyle(color: Colors.black, fontSize: 18.0), onChanged: (String text) { setState(() { _isDesc = text.length > 0; }); }, decoration: new InputDecoration.collapsed( hintText: "Description", border: new UnderlineInputBorder( borderSide: const BorderSide( color: Colors.blueAccent, style: BorderStyle.solid, width: 5.0), ), ), ), ), new Padding( padding: const EdgeInsets.all(8.0), child: new RaisedButton( padding: const EdgeInsets.only( left: 45.0, right: 45.0, top: 15.0, bottom: 15.0), color: Colors.blueAccent, elevation: 2.0, child: new Text( "Post", style: new TextStyle(color: Colors.white), ), onPressed: _isTitle && _isDesc && _isImage && !_isLoading ? () => _handleSubmitted(_title.text, _desc.text, _image) : null, ), ) ], ), ), ), ); } Future<Null> _handleSubmitted(String title, String desc, File img) async { setState(() { _isLoading = true; }); await _ensureLoggedIn(); StorageReference ref = FirebaseStorage.instance.ref().child("Blog_Images/" + new DateTime.now().millisecondsSinceEpoch.toString()); //new StorageUploadTask uploadTask = ref.put(img); //new Uri downloadUrl = (await uploadTask.future).downloadUrl; _addBlog(title, desc, downloadUrl.toString()); } void _addBlog(String title, String description, String imageUrl) { // print(googleSignIn.currentUser.displayName); // print(googleSignIn.currentUser.id); // print(title); // print(imageUrl); // print(description); reference.push().set({ 'IMAGE': imageUrl, 'Title': title, 'DESCRIPTION': description, 'uid': googleSignIn.currentUser.id, 'username': googleSignIn.currentUser.displayName }); // Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(builder: (Builder))) // Navigator.of(context).pushAndRemoveUntil( // new MaterialPageRoute( // builder: (BuildContext context) => new HomePage()), // (Route route) => route == null); // print("success"); analytics.logEvent(name: 'post_blog'); setState(() { _isLoading = false; _title.clear(); _desc.clear(); _isTitle = false; _isDesc = false; _isImage = false; _image = null; }); Scaffold.of(context).showSnackBar(new SnackBar( content: new Text("Posted Successfully!"), )); } }
0
mirrored_repositories/Flutter-Blog-App-Firebase
mirrored_repositories/Flutter-Blog-App-Firebase/lib/ChatPage.dart
import 'dart:async'; import 'package:firebase_database/ui/firebase_animated_list.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_blog_app/ChatRow.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; String username, userid, useremail, userphotourl; final analytics = new FirebaseAnalytics(); final reference = FirebaseDatabase.instance.reference().child('chat'); class ChatPage extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp(title: "Chat", home: new ChatScreen()); } } class ChatScreen extends StatefulWidget { @override ChatScreenState createState() => new ChatScreenState(); } class ChatScreenState extends State<ChatScreen> { bool loggedIn = false; TextEditingController _textEditingController = new TextEditingController(); bool _isComposing = false; Future<Null> _function() async { SharedPreferences prefs; prefs = await SharedPreferences.getInstance(); this.setState(() { if (prefs.getString("username") != null) { loggedIn = true; username = prefs.getString("username"); userid = prefs.getString("userid"); useremail = prefs.getString("useremail"); userphotourl = prefs.getString("userphotourl"); } else { loggedIn = false; } }); } Future<Null> _handleClick(String message) async { _textEditingController.clear(); setState(() { _isComposing = false; }); _sendMessage(message); } void _sendMessage(String message) { reference.push().set({ "messageTime": new DateTime.now().millisecondsSinceEpoch.toString(), "messageText": message, "messageUser": useremail, "profileUrl": userphotourl }); analytics.logEvent(name: 'send_message'); } @override void initState() { super.initState(); _function(); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("Chat"), elevation: Theme.of(context).platform == TargetPlatform.iOS ? 0.0 : 4.0, ), body: new Column( children: <Widget>[ new Flexible( child: new FirebaseAnimatedList( query: reference, sort: (a, b) => b.key.compareTo(a.key), padding: new EdgeInsets.all(8.0), reverse: true, itemBuilder: (_, DataSnapshot snapshot, Animation<double> animation, int index) { return new ChatRow(snapshot); }, )), new Divider(height: 1.0), new Container( decoration: new BoxDecoration(color: Theme.of(context).cardColor), child: new IconTheme( data: new IconThemeData(color: Theme.of(context).accentColor), child: new Container( margin: const EdgeInsets.symmetric(horizontal: 8.0), child: new Row(children: <Widget>[ new Flexible( child: new TextField( controller: _textEditingController, onChanged: (String text) { setState(() { _isComposing = text.length > 0; }); }, decoration: new InputDecoration.collapsed( hintText: "Send a message"), ), ), new Container( margin: new EdgeInsets.symmetric(horizontal: 4.0), child: new IconButton( icon: new Icon(Icons.send), onPressed: _isComposing ? () => _handleClick(_textEditingController.text) : null)), ]), decoration: Theme.of(context).platform == TargetPlatform.iOS ? new BoxDecoration( border: new Border( top: new BorderSide(color: Colors.grey[200]))) : null), ), ), ], ), ); } }
0
mirrored_repositories/Flutter-Blog-App-Firebase
mirrored_repositories/Flutter-Blog-App-Firebase/lib/HomePage.dart
import 'dart:async'; import 'package:firebase_database/ui/firebase_animated_list.dart'; import 'package:flutter_blog_app/BlogRow.dart'; import 'package:flutter_blog_app/ChatPage.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:flutter_blog_app/PostBlogPage.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter/material.dart'; import 'package:flutter_blog_app/ProfilePage.dart'; final googleSignIn = new GoogleSignIn(); final analytics = new FirebaseAnalytics(); final auth = FirebaseAuth.instance; final reference = FirebaseDatabase.instance.reference().child('Blogs'); String temp; enum _DesignAppMenuItems { profile, logout } class HomePage extends StatefulWidget { @override HomePageState createState() => new HomePageState(); } class HomePageState extends State<HomePage> { bool loggedIn = false; bool _googleLoginProgress = false; SharedPreferences prefs; Future<Null> _function() async { SharedPreferences prefs; prefs = await SharedPreferences.getInstance(); this.setState(() { if (prefs.getString("username") != null) { loggedIn = true; } else { loggedIn = false; } }); } Future<Null> checkStatusOfUser() async { await _ensureLoggedIn(); } Future<Null> _ensureLoggedIn() async { SharedPreferences prefs; prefs = await SharedPreferences.getInstance(); GoogleSignInAccount user = googleSignIn.currentUser; try { if (user == null) user = await googleSignIn.signInSilently(); if (user == null) { user = await googleSignIn.signIn(); analytics.logLogin(); } if (await auth.currentUser() == null) { GoogleSignInAuthentication credentials = await googleSignIn.currentUser.authentication; await auth.signInWithGoogle( idToken: credentials.idToken, accessToken: credentials.accessToken, ); } prefs.setString("username", user.displayName); prefs.setString("userid", user.id); prefs.setString("useremail", user.email); prefs.setString("userphotourl", user.photoUrl); analytics.logLogin(); final userRef = FirebaseDatabase.instance.reference().child('Users'); userRef .child(user.id) .set({"name": user.displayName, "image": user.photoUrl}); this.setState(() { loggedIn = true; _googleLoginProgress = false; }); } catch (error) { print(error); } } Future<Null> logoutUser() async { //logout user SharedPreferences prefs; prefs = await SharedPreferences.getInstance(); await googleSignIn.signOut(); prefs.clear(); prefs.commit(); this.setState(() { loggedIn = false; }); } @override Widget build(BuildContext context) { Scaffold homeScaffold = new Scaffold( appBar: new AppBar( title: new Text("Simple Blog App"), actions: <Widget>[ new Builder(builder: (context) { return new IconButton( icon: new Icon(Icons.add), onPressed: () { // Navigator.of(context).push( // new MaterialPageRoute( // builder: (BuildContext context) => // new PostBlogPage()), // ); Navigator.of(context).pushNamed("/post"); }); }), new Builder(builder: (context) { return new PopupMenuButton<_DesignAppMenuItems>( onSelected: (_DesignAppMenuItems value) { _handleStockMenu(context, value); }, itemBuilder: (BuildContext context) => <PopupMenuItem<_DesignAppMenuItems>>[ new PopupMenuItem<_DesignAppMenuItems>( value: _DesignAppMenuItems.profile, child: const Text('PROFILE')), new PopupMenuItem<_DesignAppMenuItems>( value: _DesignAppMenuItems.logout, child: const Text('LOG OUT')), ]); }) ], ), body: new Container( child: new Stack(alignment: Alignment.bottomRight, children: <Widget>[ new FirebaseAnimatedList( query: reference, sort: (a, b) => b.key.compareTo(a.key), padding: new EdgeInsets.all(8.0), reverse: false, itemBuilder: (_, DataSnapshot snapshot, Animation<double> animation, int index) { return new BlogRow(snapshot); }, ), new Divider(height: 1.0), new Builder( builder: (BuildContext context) { return new Padding( padding: const EdgeInsets.fromLTRB(0.0, 0.0, 12.0, 12.0), child: new FloatingActionButton( onPressed: () { Navigator.of(context).pushNamed("/chat"); }, child: new Icon(Icons.chat), ), ); }, ) ]), )); Scaffold loginScaffold = new Scaffold( appBar: new AppBar( title: new Text("Login"), ), body: new Center( child: _googleLoginProgress ? new CircularProgressIndicator() : new InkWell( child: new Image.asset("assets/img/signin.png",width: 200.0,), onTap: () { setState(() { _googleLoginProgress = true; }); checkStatusOfUser(); }, ), ), ); return new MaterialApp( title: "SimpleBlogApp", routes: <String, WidgetBuilder>{ "/profile": (BuildContext context) => new ProfilePage(), "/post": (BuildContext context) => new PostBlogPage(), "/chat": (BuildContext context) => new ChatPage(), }, home: loggedIn ? homeScaffold : loginScaffold); } @override void initState() { super.initState(); this._function(); } void _handleStockMenu(BuildContext context, _DesignAppMenuItems value) { switch (value) { case _DesignAppMenuItems.profile: // print('Profile'); Navigator.of(context).pushNamed("/profile"); break; case _DesignAppMenuItems.logout: logoutUser(); break; } } }
0
mirrored_repositories/Flutter-Blog-App-Firebase
mirrored_repositories/Flutter-Blog-App-Firebase/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_blog_app/HomePage.dart'; void main() => runApp(new HomePage());
0
mirrored_repositories/Flutter-Blog-App-Firebase
mirrored_repositories/Flutter-Blog-App-Firebase/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_blog_app/HomePage.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_blog_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(new HomePage()); // 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/DiceRollApp
mirrored_repositories/DiceRollApp/lib/gradient_container.dart
import 'package:flutter/material.dart'; import 'package:first_app/styled_text.dart'; import 'package:first_app/dice_roller.dart'; var startAlignment = Alignment.topLeft; var endAlignment = Alignment.bottomRight; class GradientContainer extends StatelessWidget { const GradientContainer(this.color1, this.color2, {super.key}); GradientContainer.purple() : color1 = Colors.deepOrange, color2 = Color.fromARGB(251, 252, 226, 142); final Color color1; final Color color2; @override Widget build(context) { return Container( decoration: BoxDecoration( gradient: LinearGradient( colors: [color1, color2], begin: startAlignment, end: endAlignment, ), ), child: Center( child: DiceRoller(), ), ); } }
0
mirrored_repositories/DiceRollApp
mirrored_repositories/DiceRollApp/lib/styled_text.dart
import 'package:flutter/material.dart'; class StyledText extends StatelessWidget { const StyledText(this.text, {super.key}); final String text; @override Widget build(BuildContext context) { return const Text( 'Read India Celebration', style: TextStyle( color: Colors.white, fontSize: 24, ), ); } }
0
mirrored_repositories/DiceRollApp
mirrored_repositories/DiceRollApp/lib/main.dart
import 'package:flutter/material.dart'; import 'package:first_app/gradient_container.dart'; void main() { runApp( const MaterialApp( home: Scaffold( body: GradientContainer( Color.fromARGB(255, 207, 48, 0), Color.fromARGB(220, 252, 64, 7), ), ), ), ); }
0
mirrored_repositories/DiceRollApp
mirrored_repositories/DiceRollApp/lib/dice_roller.dart
import 'dart:math'; import 'package:flutter/material.dart'; final randomizer = Random(); class DiceRoller extends StatefulWidget { DiceRoller({super.key}); @override State<DiceRoller> createState() { return _DiceRollerState(); } } class _DiceRollerState extends State<DiceRoller> { var currentDiceRoll = 3; void rollDice() { setState(() { currentDiceRoll = randomizer.nextInt(6) + 1; }); } @override Widget build(context) { return Column( mainAxisSize: MainAxisSize.min, children: [ Image.asset( 'assets/dice/dice-$currentDiceRoll.png', width: 200, ), const SizedBox(height: 20), TextButton( onPressed: rollDice, style: TextButton.styleFrom( padding: const EdgeInsets.only(top: 20), foregroundColor: Colors.white, textStyle: const TextStyle( fontSize: 24, ), ), child: const Text('Roll Dice'), ) ], ); } }
0
mirrored_repositories/DiceRollApp/.dart_tool
mirrored_repositories/DiceRollApp/.dart_tool/dartpad/web_plugin_registrant.dart
// Flutter web plugin registrant file. // // Generated file. Do not edit. // // ignore_for_file: type=lint void registerPlugins() {}
0
mirrored_repositories/DiceRollApp
mirrored_repositories/DiceRollApp/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:first_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/shoppinglist
mirrored_repositories/shoppinglist/lib/main.dart
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return MaterialApp( title: 'My Supermarket Shopping List', theme: ThemeData( appBarTheme: AppBarTheme(color: Color.fromRGBO(0, 0, 128, 1)), visualDensity: VisualDensity.adaptivePlatformDensity, ), home: MyHomePage(title: 'My Supermarket Shopping List'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<ListItem> items = <ListItem>[]; final TextEditingController textController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: SingleChildScrollView( padding: const EdgeInsets.all(8.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Card( child: Column( children: [ Title(), ListView(shrinkWrap: true, children: items), EnterItems( controller: textController, onPressed: _searchItem) ], ), ) ], ), ), ), drawer: Drawer( child: ListView( children: <Widget>[ DrawerHeader( child: Container( decoration: BoxDecoration( image: DecorationImage( image: AssetImage("assets/ShoppingLogo.png"), fit: BoxFit.contain, ), ), ), decoration: BoxDecoration( color: Colors.indigoAccent, ), ), ListTile( leading: Icon(Icons.home), title: Text('Home', style: TextStyle(fontSize: 16.0)), onTap: () { Navigator.push( context, MaterialPageRoute(builder: (context) => MyApp()), ); }, ), ListTile( leading: Icon(Icons.info), title: Text('About the Developer', style: TextStyle(fontSize: 16.0)), onTap: () { Navigator.push( context, MaterialPageRoute(builder: (context) => _AboutPage()), ); }, ), ], ), ), ); } _addItem(String text) { setState(() { Key key = Key(text); final newListItem = ListItem( key: key, label: text, onClosed: () => _removeItem(key), ); items = List.from(items..add(newListItem)); }); } _searchItem(String text) { setState(() { Key key = Key(text); final newListItem = ListItem( key: key, label: text, onClosed: () => _removeItem(key), ); bool found = false; if (items.length == 0) { _addItem(text); found = false; } else { for (int x = 0; x < items.length; x++) { if (items[x].label == newListItem.label) { showAlertDialog(context); found = true; } } if (found == false) { _addItem(text); } } }); } _removeItem(Key key) { setState(() { items = List.from(items..removeWhere((item) => item.key == key)); }); } } showAlertDialog(BuildContext context) { Widget okButton = FlatButton( child: Text("OK"), onPressed: () => Navigator.of(context, rootNavigator: true).pop('dialog'), ); AlertDialog alert = AlertDialog( title: Text("Repeated Entry!"), content: Text("The item is already in your shopping list."), actions: [ okButton, ], ); showDialog( context: context, builder: (BuildContext context) { return alert; }, ); } class ListItem extends StatefulWidget { final String label; final Function onClosed; const ListItem({Key key, this.label, this.onClosed}) : super(key: key); @override _ListItemState createState() => _ListItemState(); } class _ListItemState extends State<ListItem> { bool status = false; @override Widget build(BuildContext context) { if (status == false) { return Container( child: SingleChildScrollView( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ FlatButton( onPressed: () => { setState(() { if (status == true) { status = false; } else { status = true; } _switchTextStyle(); }) }, child: Text( widget.label, style: TextStyle( fontSize: 16.0, ), ), ), IconButton( color: Colors.red, onPressed: () { final snackBar = SnackBar( backgroundColor: Colors.red, content: Text('Item Removed.'), ); widget.onClosed(); Scaffold.of(context).showSnackBar(snackBar); }, icon: Icon(Icons.close), ) ], ), )); } else { return Container( child: SingleChildScrollView( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ FlatButton( onPressed: () => { setState(() { if (status == true) { status = false; } else { status = true; } _switchTextStyle(); }) }, child: Text( widget.label, style: TextStyle( fontSize: 16.0, decoration: TextDecoration.lineThrough), ), ), IconButton( color: Colors.red, onPressed: () { final snackBar = SnackBar( backgroundColor: Colors.red, content: Text('Item Removed.'), ); widget.onClosed(); Scaffold.of(context).showSnackBar(snackBar); }, icon: Icon(Icons.close), ) ], ), )); } } void _switchTextStyle() { setState(() { if (status == true) { Text(widget.label, style: TextStyle( fontSize: 18, decoration: TextDecoration.lineThrough)); } }); } } class Title extends StatefulWidget { @override _TitleState createState() => _TitleState(); } class _TitleState extends State<Title> { @override Widget build(BuildContext context) { return Row(children: <Widget>[ Padding( padding: const EdgeInsets.all(16.0), child: Text( 'My Shopping List', style: TextStyle(fontSize: 24.0), ), ), ]); } } class EnterItems extends StatelessWidget { final TextEditingController controller; final Function(String) onPressed; const EnterItems({Key key, this.controller, this.onPressed}) : super(key: key); @override Widget build(BuildContext context) { return Row( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Flexible( child: Padding( padding: const EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 16.0), child: TextField( controller: controller, decoration: InputDecoration( border: OutlineInputBorder( borderSide: BorderSide(color: Colors.black))), ), )), Padding( padding: const EdgeInsets.all(8.0), child: FlatButton( color: Colors.lightBlueAccent, child: Text('Add Item'), onPressed: () => onPressed(controller.text), ), ), ], ); } } class _AboutPage extends StatelessWidget { final String _fullName = "Daavid Sinclair"; final String _status = "Software Engineer"; final String _bio = "\"I am Daavid A.S. Sinclair. I am a 19 year old male, who is from Jamaica." "I am a senior at NCU. I am pursuing a Batchelors degree in Computer Science where my concentration is Software Engineering.\""; final String _projects = "5"; final String _age = "19"; Widget _buildCoverImage(Size screenSize) { return Container( height: screenSize.height / 2.6, decoration: BoxDecoration( image: DecorationImage( image: AssetImage('assets/background.jpg'), fit: BoxFit.cover, ), ), ); } Widget _buildProfileImage() { return Center( child: Container( width: 160.0, height: 160.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage('assets/dsinclair.png'), fit: BoxFit.cover, ), borderRadius: BorderRadius.circular(100.0), border: Border.all( color: Colors.white, width: 4.5, ), ), ), ); } Widget _buildFullName() { TextStyle _nameTextStyle = TextStyle( color: Colors.black, fontSize: 28.0, fontWeight: FontWeight.w700, ); return Container( padding: EdgeInsets.symmetric(vertical: 3.0, horizontal: 3.0), child: Text( _fullName, style: _nameTextStyle, ), ); } Widget _buildStatus(BuildContext context) { return Container( padding: EdgeInsets.symmetric(vertical: 4.0, horizontal: 6.0), decoration: BoxDecoration( color: Theme.of(context).scaffoldBackgroundColor, borderRadius: BorderRadius.circular(4.0), ), child: Text( _status, style: TextStyle( color: Colors.black, fontSize: 20.0, fontWeight: FontWeight.w300, ), ), ); } Widget _buildSkills(String skill) { return Container( padding: EdgeInsets.symmetric(vertical: 4.0, horizontal: 6.0), decoration: BoxDecoration( borderRadius: BorderRadius.circular(4.0), ), child: Text( skill, textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontSize: 20.0, fontWeight: FontWeight.w300, ), ), ); } Widget _buildStatItem(String label, String count) { TextStyle _statLabelTextStyle = TextStyle( color: Colors.black, fontSize: 16.0, fontWeight: FontWeight.w200, ); TextStyle _statCountTextStyle = TextStyle( color: Colors.black54, fontSize: 24.0, fontWeight: FontWeight.bold, ); return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( count, style: _statCountTextStyle, ), Text( label, style: _statLabelTextStyle, ), ], ); } Widget _buildSkillItem(String label) { TextStyle _statCountTextStyle = TextStyle( color: Colors.black, fontSize: 24.0, fontWeight: FontWeight.bold, ); return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( label, style: _statCountTextStyle, ), ], ); } Widget _buildStatContainer() { return Container( height: 50.0, margin: EdgeInsets.only(top: 18.0), decoration: BoxDecoration( color: Color(0xFFEFF4F7), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ _buildStatItem("Major Projects", _projects), _buildStatItem("Age", _age), ], ), ); } Widget _buildSkillContainer() { return Container( height: 40.0, margin: EdgeInsets.only(top: 2.0), decoration: BoxDecoration( color: Color(0xFFEFF4F7), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ _buildSkillItem("Skills"), ], ), ); } Widget _buildBio(BuildContext context) { TextStyle bioTextStyle = TextStyle( //fontFamily: 'Spectral', fontWeight: FontWeight.w400, //try changing weight to w500 if not thin fontStyle: FontStyle.italic, color: Color(0xFF799497), fontSize: 16.0, ); return Container( color: Theme.of(context).scaffoldBackgroundColor, padding: EdgeInsets.all(8.0), child: Text( _bio, textAlign: TextAlign.center, style: bioTextStyle, ), ); } Widget _buildSeparator(Size screenSize) { return Container( width: screenSize.width / 1.6, height: 2.0, color: Colors.black54, margin: EdgeInsets.only(top: 4.0), ); } @override Widget build(BuildContext context) { Size screenSize = MediaQuery.of(context).size; return Scaffold( appBar: AppBar( title: Text("About the Developer"), ), body: Stack( children: <Widget>[ _buildCoverImage(screenSize), SafeArea( child: SingleChildScrollView( child: Column( children: <Widget>[ SizedBox(height: screenSize.height / 10.4), _buildProfileImage(), Container( color: Colors.white, child: Column( children: [ _buildFullName(), _buildStatus(context), _buildStatContainer(), _buildBio(context), _buildSeparator(screenSize), _buildSkillContainer(), _buildSkills( "C#, C++, Python, Java, Dart, ASP.net, Flask, PHP, Laravel, Flutter") ], ), ), SizedBox(height: 10.0), SizedBox(height: 8.0), ], ), ), ), ], ), ); } }
0
mirrored_repositories/shoppinglist
mirrored_repositories/shoppinglist/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:shoppinglist/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_mockup_bloc
mirrored_repositories/flutter_mockup_bloc/lib/app.dart
import 'package:device_preview/device_preview.dart'; import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_mockup_bloc/common/theme/theme_data.dart'; import 'package:flutter_mockup_bloc/core/net/dio_utils.dart'; import 'package:flutter_mockup_bloc/core/net/intercept.dart'; import 'package:flutter_mockup_bloc/core/view_model/global/global_viewmodel.dart'; import 'package:flutter_mockup_bloc/presentation/router/app_router.dart'; import 'package:flutter_mockup_bloc/presentation/router/route_logging_observer.dart'; import 'package:flutter_mockup_bloc/presentation/screens/splash_screen.dart'; import 'package:flutter_mockup_bloc/presentation/screens/list_offline_screen.dart'; import 'package:flutter_mockup_bloc/provider/provider_widget.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_mockup_bloc/repository/common_data_repo.dart'; import 'package:flutter_mockup_bloc/resource/app_constant.dart'; import 'package:flutter_mockup_bloc/utils/env/flavor_config.dart'; import 'package:flutter_mockup_bloc/utils/locale/localization_delegate.dart'; import 'package:flutter_mockup_bloc/utils/locale/localization_fallback_cupertino_delegate.dart'; import 'package:get_it/get_it.dart'; import 'package:oktoast/oktoast.dart'; class MyApp extends StatelessWidget { MyApp({Key? key}) : super(key: key){ initDio(); } void initDio() { final List<Interceptor> interceptors = <Interceptor>[]; /// interceptors.add(AuthInterceptor()); /// Token interceptors.add(TokenInterceptor()); /// Log nếu ko ở chế độ production if (!AppConstants.inProduction) { interceptors.add(LoggingInterceptor()); } /// interceptors.add(AdapterInterceptor()); configDio( // baseUrl: 'https://stoplight.io/mocks/phongdoan/test/11233479/', interceptors: interceptors, ); } @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle( systemNavigationBarColor: Colors.transparent, )); SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); return OKToast( backgroundColor: Colors.black54, textPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0), radius: 20.0, position: ToastPosition.bottom, child: InternalApp() // DevicePreview( // enabled: !kReleaseMode, // builder: (context) => InternalApp() // ) ); } } class InternalApp extends StatelessWidget { final Widget? home; const InternalApp({Key? key}) : home = null, super(key: key); @visibleForTesting const InternalApp.test({required this.home, Key? key}) : super(key: key); @override Widget build(BuildContext context) { return ProviderWidget<GlobalViewModel>( lazy: FlavorConfig.isInTest(), consumer: (context, viewModel, consumerChild) => RepositoryProvider( create: (_) => CommonDataRepo(), child: MaterialApp( // useInheritedMediaQuery: true, // locale: DevicePreview.locale(context), // builder: DevicePreview.appBuilder, debugShowCheckedModeBanner: !FlavorConfig.isInTest(), localizationsDelegates: [ viewModel.localeDelegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, FallbackCupertinoLocalisationsDelegate.delegate, ], locale: viewModel.locale, supportedLocales: LocalizationDelegate.supportedLocales, themeMode: viewModel.themeMode, theme: FlutterTemplateThemeData.lightTheme(viewModel.targetPlatform), darkTheme: FlutterTemplateThemeData.darkTheme(viewModel.targetPlatform), // navigatorKey: MainNavigatorWidgetState.navigationKey, // initialRoute: home == null ? MainNavigatorWidgetState.initialRoute : null, // onGenerateRoute: MainNavigatorWidgetState.onGenerateRoute, // builder: home == null ? (context, child) => SplashScreen() : null, home: SplashScreen(), // navigatorObservers: [ // if (kDebugMode) RouteLoggingObserver(), // AppRouter.createRouteObserver(), // ], ), ), create: () => GetIt.I()..init(), ); } }
0
mirrored_repositories/flutter_mockup_bloc
mirrored_repositories/flutter_mockup_bloc/lib/main_common.dart
import 'dart:async'; import 'package:flutter/widgets.dart'; import 'package:flutter_mockup_bloc/architecture.dart'; import 'package:flutter_mockup_bloc/utils/logging/logging.dart'; import 'package:flutter_mockup_bloc/utils/web/app_configurator.dart' if (dart.library.html) 'package:flutter_mockup_bloc/utils/web/app_configurator_web.dart'; Future<void> _setupCrashLogging() async { final originalOnError = FlutterError.onError; FlutterError.onError = (errorDetails) async { originalOnError?.call(errorDetails); }; } FutureOr<R>? wrapMain<R>(FutureOr<R> Function() appCode) { return runZonedGuarded(() async { WidgetsFlutterBinding.ensureInitialized(); configureWebApp(); await _setupCrashLogging(); await initArchitecture(); return await appCode(); }, (object, trace) { try { WidgetsFlutterBinding.ensureInitialized(); } catch (_) {} try { staticLogger.e('Zone error', error: object, trace: trace); } catch (_) { // ignore: avoid_print print(object); // ignore: avoid_print print(trace); } }); }
0
mirrored_repositories/flutter_mockup_bloc
mirrored_repositories/flutter_mockup_bloc/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/app.dart'; import 'package:flutter_mockup_bloc/common/config/configuration.dart'; import 'package:flutter_mockup_bloc/common/config/index.dart'; import 'package:flutter_mockup_bloc/di/environments.dart'; import 'package:flutter_mockup_bloc/di/injectable.dart'; import 'package:flutter_mockup_bloc/main_common.dart'; import 'package:flutter_mockup_bloc/utils/env/flavor_config.dart'; import 'package:sp_util/sp_util.dart'; Future<void> main() async { await wrapMain(() async { const values = FlavorValues( baseUrl: 'https://jsonplaceholder.typicode.com/', logNetworkInfo: true, showFullErrorMessages: true, ); FlavorConfig( flavor: Flavor.dev, name: 'DEV', color: Colors.red, values: values, ); // ignore: avoid_print print('Starting app from main.dart'); await configureDependencies(Environments.dev); await SpUtil.getInstance(); Configurations().setConfigurationValues(config); runApp(MyApp()); }); }
0
mirrored_repositories/flutter_mockup_bloc
mirrored_repositories/flutter_mockup_bloc/lib/architecture.dart
import 'package:flutter/widgets.dart'; import 'package:flutter_mockup_bloc/common/theme/theme_data.dart'; import 'package:flutter_mockup_bloc/provider/theme_provider_widget.dart'; import 'package:flutter_mockup_bloc/utils/env/os_info.dart'; import 'package:flutter_mockup_bloc/utils/locale/localization.dart'; L _getLocale<L>(BuildContext context) => Localization.of(context) as L; T _getTheme<T>(BuildContext context) => FlutterTemplateTheme.of(context) as T; Future<void> initArchitecture() async { await OsInfo.init(); localizationLookup = _getLocale; themeLookup = _getTheme; }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/repository/multi_repository.dart
import 'package:flutter_mockup_bloc/core/mvp/base_state_view.dart'; import 'package:flutter_mockup_bloc/repository/base_repository.dart'; class PowerRepo<IMvpView> extends BaseRepo { // late BasePageMixin _state; List<BaseRepo> _listRepo = []; void requestListRepo(List<BaseRepo> presenters) { _listRepo = presenters; // _presenters.forEach(_requestPresenter); } // void _requestPresenter(BaseRepo presenter) { // // presenter.view = _state; // } }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/repository/common_data_repo.dart
import 'dart:async'; import 'dart:convert'; import 'package:flutter_mockup_bloc/common/common_export.dart'; import 'package:flutter_mockup_bloc/core/error_handling/exceptions.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_mockup_bloc/core/net/api.dart'; import 'package:flutter_mockup_bloc/core/net/dio_utils.dart'; import 'package:flutter_mockup_bloc/model/City.dart'; import 'package:flutter_mockup_bloc/model/request_response.dart'; import 'package:flutter_mockup_bloc/model/selectable_item.dart'; import 'package:flutter_mockup_bloc/repository/base_repository.dart'; import 'package:flutter_mockup_bloc/resource/app_constant.dart'; import 'package:flutter_mockup_bloc/utils/device/api_data_resolver.dart'; import 'package:sp_util/sp_util.dart'; class CommonDataRepo { final LocalDataStorageService _localDataStorageService; final _MemoryCacheManager _memoryCacheManager; final _RemoteDataRepo _remoteDataRepo; static CommonDataRepo? _instance; factory CommonDataRepo() => _instance ??= CommonDataRepo._(); CommonDataRepo._() : _localDataStorageService = LocalDataStorageService(), _memoryCacheManager = _MemoryCacheManager(), _remoteDataRepo = _RemoteDataRepo(); Future<void> loadCommonData() async { await getCity(); } /// -------------------------------------------------------------------------- /// City /// -------------------------------------------------------------------------- Future<List<SelectableItem>> getCity() async { if (_memoryCacheManager.city.hasData) return _memoryCacheManager.city.retrieveData(); try { _memoryCacheManager.city.update( _localDataStorageService.containsCityData() ? _localDataStorageService .getListCityData() .map((e) => SelectableItem.fromJsonCity(e)) : await _remoteDataRepo.getCity( (rawData) => _localDataStorageService.saveCityResponeData(rawData), ), ); } catch (e) { rethrow; } return _memoryCacheManager.city.retrieveData(); } Future<List<SelectableItem>> getGeneralCity() async { try { return List.unmodifiable([ ApiDataResolver.nationalSelectableItem, ...(await getCity()), ]); } catch (e) { rethrow; } } String getCityName(String id) { try { return _memoryCacheManager.city .firstWhere(SelectableItemExt.equalIdTester(id)) .name; } catch (e) { throw DataNotFoundException( 'City.id == $id', 'CommonDataRepo.getCityName()'); } } String? getNullableCityName(String id) { try { return getCityName(id); } catch (e) { return null; } } SelectableItem getCitySelectableItem(String id) { try { return SelectableItem( id: id, name: getCityName(id), ); } catch (e) { throw DataNotFoundException( 'City.id == $id', 'CommonDataRepo.getCityName()'); } } } typedef _RawDataCallback = void Function(dynamic); class _RemoteDataRepo extends BaseRepo{ // _RemoteDataRepo({required cubit}) : super(cubit: cubit); // final ApiClient _client; // // _RemoteDataRepo() : _client = ApiClient(); // Future<Iterable<SelectableItem>> getCity(_RawDataCallback onData) async { // RequestResponse res = await _client.fetch(ApiPath.city, RequestMethod.post); try { City res = await requestNetwork<City>(Method.get, url: Api.GET_LIST_CITY); onData(jsonEncode(res.data!.items!)); return res.data!.items!.map((e) => SelectableItem(id: e.code.toString(), name: e.name.toString())).toList(); } catch (e){ return []; } } } class _MemoryCacheManager { _MemoryCacheManager() : city = _InMemoryListDataCacheStorage(); final _InMemoryListDataCacheStorage city; late final _InMemoryMapDataCacheStorage district = _InMemoryMapDataCacheStorage(); late final _InMemoryListDataCacheStorage bussinessArea = _InMemoryListDataCacheStorage(); } class _InMemoryListDataCacheStorage { _InMemoryListDataCacheStorage() : _data = []; List<SelectableItem> _data; bool get hasData => _data.isNotEmpty; List<SelectableItem> retrieveData() => List.unmodifiable(_data); /// Returns the first element that satisfies the given predicate [test]. /// /// Iterates through elements and returns the first to satisfy [test]. /// /// If no element satisfies [test], the result of invoking the [orElse] /// function is returned. /// If [orElse] is omitted, it defaults to throwing a [StateError]. SelectableItem firstWhere( bool Function(SelectableItem) test, { SelectableItem Function()? orElse, }) { return _data.firstWhere(test, orElse: orElse); } void update(Iterable<SelectableItem> data) => _data = data.toList(); } class _InMemoryMapDataCacheStorage { _InMemoryMapDataCacheStorage() : _data = {}; Map<String, List<SelectableItem>> _data; bool hasData(String key) => _data[key] != null; List<SelectableItem>? retrieveData(String key) => _data[key] == null ? null : List.unmodifiable(_data[key]!); /// Returns the first element that satisfies the given predicate [key] & [test]. /// /// Iterates through elements and returns the first to satisfy [test]. /// /// If there is no value for the given [key], throwing a [StateError] /// If no element satisfies [test], the result of invoking the [orElse] /// function is returned. /// If [orElse] is omitted, it defaults to throwing a [StateError]. SelectableItem firstWhere( String key, bool Function(SelectableItem) test, { SelectableItem Function()? orElse, }) { if (_data[key] == null) { throw StateError("No element"); } return _data[key]!.firstWhere(test, orElse: orElse); } void update(String key, List<SelectableItem> data) => _data[key] = data; } const _jsonCodec = JsonCodec(); Map<String, dynamic> _decodeStringData(String data) => _jsonCodec.decode(data); List _getListDataFromMap( Map<String, dynamic> mapData, ) => mapData['data']; const String _cityKey = 'city'; const String _lastTimeFetchCityDataKey = 'last_time_fetch_city_data'; class LocalDataStorageService { bool _hasExpired(String? lastTime) { if (lastTime != null) { if (lastTime.isEmpty) return true; DateTime? lastFetchDate = DateTime.tryParse(lastTime); if (lastFetchDate == null || DateTime.now() .add(AppConstants.timesToFetchCommonDataAgain) .isBefore(lastFetchDate)) return true; } return false; } /// -------------------------------------------------------------------------- /// City /// -------------------------------------------------------------------------- bool containsCityData() => !_hasExpired(SpUtil.getString(_lastTimeFetchCityDataKey)); /// return List<Map<String, dynamic>> List getListCityData() => _jsonCodec.decode(SpUtil.getString(_cityKey)!); void saveCityResponeData(String response) { SpUtil.putString(_cityKey, response); SpUtil.putString(_lastTimeFetchCityDataKey, DateTime.now().toString()); } }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/repository/base_repository.dart
import 'package:dio/dio.dart'; import 'package:flutter_mockup_bloc/core/generated/json/base/json_convert_content.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_presenter.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_state_view.dart'; import 'package:flutter_mockup_bloc/core/net/dio_utils.dart'; import 'package:flutter_mockup_bloc/core/net/error_handle.dart'; import 'package:flutter_mockup_bloc/model/request_response.dart'; abstract class BaseRepo <V extends BaseView>{ V? view; late CancelToken _cancelToken; BaseRepo() { _cancelToken = CancelToken(); } setViewRepo(V viewRepo){ this.view = viewRepo; } @override void dispose() { if (!_cancelToken.isCancelled) { _cancelToken.cancel(); } } Future<T> requestNetwork<T>(Method method, { required String url, bool isShow = true, bool isClose = true, NetErrorCallback? onError, dynamic params, Map<String, dynamic>? queryParameters, CancelToken? cancelToken, Options? options, }) async { late T responseData; if (isShow) { view?.showProgress(); } await DioUtils.instance.requestNetwork(method, url, params: params, queryParameters: queryParameters, options: options, cancelToken: cancelToken?? _cancelToken, onSuccess: (data) { if (isClose) { view?.closeProgress(); } responseData = _generateOBJ<T>(data)!; }, onError: (code, msg) { _onError(code, msg, onError); }, ); return responseData; } void asyncRequestNetwork<T>(Method method, { required String url, bool isShow = true, bool isClose = true, NetSuccessCallback<T?>? onSuccess, NetErrorCallback? onError, dynamic params, Map<String, dynamic>? queryParameters, CancelToken? cancelToken, Options? options, }) { if (isShow) { view?.showProgress(); } DioUtils.instance.asyncRequestNetwork<T>(method, url, params: params, queryParameters: queryParameters, options: options, cancelToken: cancelToken?? _cancelToken, onSuccess: (data) { if (isClose) { view?.closeProgress(); } onSuccess?.call(data); }, onError: (code, msg) { _onError(code, msg, onError); }, ); } void _onError(int code, String msg, NetErrorCallback? onError) { view?.closeProgress(); if (code != ExceptionHandle.cancel_error) { view?.showToast(msg); } if (onError != null) { onError(code, msg); } } T? _generateOBJ<T>(RequestResponse response) { if (T.toString() == 'String') { return response.toString() as T; } else if (T.toString() == 'Map<dynamic, dynamic>') { return response as T; } else { return JsonConvert.fromJsonAsT<T>(response); } } } mixin IBaseRepo { void initRepo(); } mixin BaseRepoMixin<R extends BaseRepo> implements IBaseRepo { late R repo; R createRepo(); @override void initRepo() { // TODO: implement initRepo repo = createRepo(); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/repository/shared_prefs
mirrored_repositories/flutter_mockup_bloc/lib/repository/shared_prefs/local/local_storage.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/common/common_export.dart'; import 'package:flutter_mockup_bloc/repository/secure_storage/auth/auth_storage.dart'; import 'package:flutter_mockup_bloc/utils/extension/iterable_extensions.dart'; import 'package:injectable/injectable.dart'; @lazySingleton abstract class LocalStorage { @factoryMethod factory LocalStorage(AuthStorage storage, SharedPreferenceStorage preferences) = _LocalStorage; Future<void> checkForNewInstallation(); ThemeMode getThemeMode(); Future<void> updateThemeMode(ThemeMode themeMode); } class _LocalStorage implements LocalStorage { static const _uninstallCheckKey = 'UNINSTALL_CHECK'; static const _appearanceThemeKey = 'APPEARANCE_THEME'; final AuthStorage _authStorage; final SharedPreferenceStorage _sharedPreferences; _LocalStorage(this._authStorage, this._sharedPreferences); @override Future<void> checkForNewInstallation() async { final result = _sharedPreferences.getBoolean(_uninstallCheckKey); if (result == null) { await _sharedPreferences.saveBoolean(key: _uninstallCheckKey, value: true); await _authStorage.clear(); } } @override Future<void> updateThemeMode(ThemeMode themeMode) async { await _sharedPreferences.saveString(key: _appearanceThemeKey, value: themeMode.toString()); } @override ThemeMode getThemeMode() { final themeString = _sharedPreferences.getString(_appearanceThemeKey); final theme = ThemeMode.values.find((element) => element.toString() == themeString); return theme ?? ThemeMode.system; } }
0
mirrored_repositories/flutter_mockup_bloc/lib/repository
mirrored_repositories/flutter_mockup_bloc/lib/repository/author/author_repository.dart
import 'package:flutter_mockup_bloc/core/net/api.dart'; import 'package:flutter_mockup_bloc/core/net/dio_utils.dart'; import 'package:flutter_mockup_bloc/model/AuthorResponse.dart'; import 'package:flutter_mockup_bloc/repository/base_repository.dart'; class AuthorRepository extends BaseRepo{ getListAuthorRepository(currentPos, maxPos) async { final Map<String, dynamic> params = <String, dynamic>{}; params['currentPos'] = currentPos; params['maxPos'] = maxPos; return requestNetwork<AuthorResponse>(Method.get, url: Api.GET_LIST_AUTHOR, queryParameters: params,); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/repository
mirrored_repositories/flutter_mockup_bloc/lib/repository/locale/locale_repository.dart
import 'package:flutter/widgets.dart'; import 'package:flutter_mockup_bloc/common/common_export.dart'; import 'package:injectable/injectable.dart'; @lazySingleton abstract class LocaleRepository { @factoryMethod factory LocaleRepository(SharedPreferenceStorage preferences) = _LocaleRepository; Future<void> setCustomLocale(Locale? locale); Locale? getCustomLocale(); } class _LocaleRepository implements LocaleRepository { static const _localeKey = 'locale'; final SharedPreferenceStorage _sharedPreferences; _LocaleRepository(this._sharedPreferences); @override Future<void> setCustomLocale(Locale? locale) async { if (locale == null) { await _sharedPreferences.deleteKey(_localeKey); } else { await _sharedPreferences.saveString(key: _localeKey, value: locale.languageCode); } } @override Locale? getCustomLocale() { final localeCode = _sharedPreferences.getString(_localeKey); if (localeCode == null || localeCode.isEmpty) return null; return Locale(localeCode); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/repository
mirrored_repositories/flutter_mockup_bloc/lib/repository/profile/profile_repository.dart
import 'package:flutter_mockup_bloc/repository/base_repository.dart'; class ProfileRepo extends BaseRepo { }
0
mirrored_repositories/flutter_mockup_bloc/lib/repository
mirrored_repositories/flutter_mockup_bloc/lib/repository/secure_storage/secure_storage.dart
import 'package:flutter_mockup_bloc/common/common_export.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:injectable/injectable.dart'; @lazySingleton abstract class SecureStorage implements SimpleKeyValueStorage { @factoryMethod factory SecureStorage(FlutterSecureStorage storage) = _SecureStorage; Future<void> deleteAll(); Future<void> write({required String key, required String value}); Future<String?> read({required String key}); Future<void> delete({required String key}); Future<bool> containsKey({required String key}); } class _SecureStorage implements SecureStorage { final FlutterSecureStorage _storage; final iOSOptions = const IOSOptions(accessibility: IOSAccessibility.unlocked); _SecureStorage(this._storage); @override Future<void> deleteAll() => _storage.deleteAll(iOptions: iOSOptions); @override Future<void> write({required String key, required String value}) => _storage.write(key: key, value: value, iOptions: iOSOptions); @override Future<String?> read({required String key}) => _storage.read(key: key, iOptions: iOSOptions); @override Future<void> delete({required String key}) => _storage.delete(key: key, iOptions: iOSOptions); @override Future<bool> containsKey({required String key}) => _storage.containsKey(key: key, iOptions: iOSOptions); @override Future<String?> getValue({required String key}) => read(key: key); @override Future<bool> hasValue({required String key}) => containsKey(key: key); @override Future<void> removeValue({required String key}) => delete(key: key); @override Future<void> setValue({required String key, required String value}) => write(key: key, value: value); }
0
mirrored_repositories/flutter_mockup_bloc/lib/repository/secure_storage
mirrored_repositories/flutter_mockup_bloc/lib/repository/secure_storage/auth/auth_storage.dart
import 'package:flutter_mockup_bloc/common/common_export.dart'; import 'package:injectable/injectable.dart'; @lazySingleton abstract class AuthStorage { @factoryMethod factory AuthStorage(SimpleKeyValueStorage storage) = _AuthStorage; Future<String?> getRefreshToken(); Future<String?> getAccessToken(); Future<void> clear(); Future<void> saveUserCredentials({required String accessToken, required String refreshToken}); Future<bool> hasLoggedInUser(); } class _AuthStorage implements AuthStorage { final SimpleKeyValueStorage _storage; static const _accessTokenKey = 'ACCESS_TOKEN'; static const _refreshTokenKey = 'ACCESS_REFRESH_TOKEN'; _AuthStorage(this._storage); @override Future<String?> getAccessToken() => _storage.getValue(key: _accessTokenKey); @override Future<String?> getRefreshToken() => _storage.getValue(key: _refreshTokenKey); @override Future<void> saveUserCredentials({required String accessToken, required String refreshToken}) { return Future.wait( [ _storage.setValue(key: _accessTokenKey, value: accessToken), _storage.setValue(key: _refreshTokenKey, value: refreshToken), ], ); } @override Future<bool> hasLoggedInUser() async { final resultRefresh = await getRefreshToken(); final resultAccess = await getAccessToken(); return resultRefresh != null && resultAccess != null; } @override Future<void> clear() async { await Future.wait([ _storage.removeValue(key: _accessTokenKey), _storage.removeValue(key: _refreshTokenKey), ]); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/repository
mirrored_repositories/flutter_mockup_bloc/lib/repository/auth/login_repository.dart
import 'package:flutter_mockup_bloc/core/net/api.dart'; import 'package:flutter_mockup_bloc/core/net/dio_utils.dart'; import 'package:flutter_mockup_bloc/model/LoginResponse.dart'; import 'package:flutter_mockup_bloc/repository/base_repository.dart'; class LoginRepository extends BaseRepo{ Future<LoginResponse> login(user, pass) async { return requestNetwork<LoginResponse>(Method.get, url: Api.LOGIN); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/repository
mirrored_repositories/flutter_mockup_bloc/lib/repository/auth/user_info_repository.dart
import 'package:flutter_mockup_bloc/core/net/api.dart'; import 'package:flutter_mockup_bloc/core/net/dio_utils.dart'; import 'package:flutter_mockup_bloc/model/UserItem.dart'; import 'package:flutter_mockup_bloc/repository/base_repository.dart'; class UserInfoRepository extends BaseRepo{ late UserInfo userInfo; getUserInfo() { return requestNetwork<UserItem>(Method.get, url: Api.USER_INFO); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/repository
mirrored_repositories/flutter_mockup_bloc/lib/repository/splash/splash_repo.dart
import 'package:flutter_mockup_bloc/core/mvp/base_state_view.dart'; import 'package:flutter_mockup_bloc/repository/base_repository.dart'; import 'package:flutter_mockup_bloc/resource/app_constant.dart'; import 'package:sp_util/sp_util.dart'; class SplashRepo extends BaseRepo { bool checkTokenExits() { // print("getCity: ${SpUtil.getString("city")}"); if (SpUtil.getString(AppConstants.accessToken, defValue: "")!.isNotEmpty){ return true; } return false; } }
0
mirrored_repositories/flutter_mockup_bloc/lib/repository
mirrored_repositories/flutter_mockup_bloc/lib/repository/city/city_repository.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_mockup_bloc/repository/base_repository.dart'; import 'package:flutter_mockup_bloc/repository/common_data_repo.dart'; class CityRepository extends BaseRepo { getListCityRepo(BuildContext context){ return context.read<CommonDataRepo>().getCity(); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/repository
mirrored_repositories/flutter_mockup_bloc/lib/repository/refresh/refresh_repository.dart
import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_mockup_bloc/repository/secure_storage/auth/auth_storage.dart'; import 'package:flutter_mockup_bloc/utils/exception/un_authorized_error.dart'; import 'package:injectable/injectable.dart'; import 'package:synchronized/synchronized.dart' as synchronized; import 'package:flutter_mockup_bloc/common/common_export.dart'; @lazySingleton abstract class RefreshRepository { @factoryMethod factory RefreshRepository(AuthStorage storage) = _RefreshRepository; Future<void> refresh(DioError err); void resetFailure(); VoidCallback? logoutCallback; } class _RefreshRepository implements RefreshRepository { final AuthStorage _authStorage; final _lock = synchronized.Lock(); bool _failure = false; @override VoidCallback? logoutCallback; _RefreshRepository(this._authStorage); @override void resetFailure() { _failure = false; } @override Future<void> refresh(DioError err) async { final accessToken = await _authStorage.getAccessToken(); await _lock.synchronized(() async { final newAccessToken = await _authStorage.getAccessToken(); if (accessToken != newAccessToken) { logger.debug('ACCESS TOKEN was already renewed'); return; } if (_failure) { throw UnAuthorizedError(err); } try { await _authStorage.getRefreshToken(); // TODO implement refresh call // await _authStoring.saveRefreshToken(refreshToken: result.refreshToken, accessToken: result.accessToken); throw UnimplementedError('No implementatino for the refresh in the refresh repository'); } catch (e) { _failure = true; final logoutCb = logoutCallback; if (logoutCb != null) { await _authStorage.clear(); logoutCb.call(); } rethrow; } }); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/repository
mirrored_repositories/flutter_mockup_bloc/lib/repository/debug/debug_repository.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_mockup_bloc/utils/preferences/preferences_storage.dart'; import 'package:injectable/injectable.dart'; @lazySingleton abstract class DebugRepository { @factoryMethod factory DebugRepository(SharedPreferenceStorage sharedPrefs) = _DebugRepository; Future<void> saveSlowAnimations({required bool enabled}); bool isSlowAnimationsEnabled(); Future<void> saveSelectedPlatform(String? selectedPlatform); TargetPlatform? getTargetPlatform(); } class _DebugRepository implements DebugRepository { static const _enableSlowAnimationsKey = 'enable_slow_animations'; static const _selectedPlatformKey = 'selected_platform'; final SharedPreferenceStorage _sharedPreferences; _DebugRepository(this._sharedPreferences); @override Future<void> saveSlowAnimations({required bool enabled}) async { await _sharedPreferences.saveBoolean(key: _enableSlowAnimationsKey, value: enabled); } @override bool isSlowAnimationsEnabled() { final slowAnimations = _sharedPreferences.getBoolean(_enableSlowAnimationsKey) ?? false; if (slowAnimations) { timeDilation = 4.0; } else { timeDilation = 1.0; } return slowAnimations; } @override Future<void> saveSelectedPlatform(String? selectedPlatform) async { if (selectedPlatform == null) { await _sharedPreferences.deleteKey(_selectedPlatformKey); } else { await _sharedPreferences.saveString(key: _selectedPlatformKey, value: selectedPlatform); } } @override TargetPlatform? getTargetPlatform() { final selectedPlatform = _sharedPreferences.getString(_selectedPlatformKey); if (selectedPlatform == null) return null; if (selectedPlatform == 'ios') return TargetPlatform.iOS; return TargetPlatform.android; } }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/resource/gaps.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/resource/dimens.dart'; class Gaps { // Khoang cach ngang static const Widget hGap4 = const SizedBox(width: Dimens.gap_dp4); static const Widget hGap5 = const SizedBox(width: Dimens.gap_dp5); static const Widget hGap8 = const SizedBox(width: Dimens.gap_dp8); static const Widget hGap10 = const SizedBox(width: Dimens.gap_dp10); static const Widget hGap12 = const SizedBox(width: Dimens.gap_dp12); static const Widget hGap15 = const SizedBox(width: Dimens.gap_dp15); static const Widget hGap16 = const SizedBox(width: Dimens.gap_dp16); static const Widget hGap20 = const SizedBox(width: Dimens.gap_dp20); static const Widget hGap32 = const SizedBox(width: Dimens.gap_dp32); // Khoang cach doc static const Widget vGap4 = const SizedBox(height: Dimens.gap_dp4); static const Widget vGap5 = const SizedBox(height: Dimens.gap_dp5); static const Widget vGap8 = const SizedBox(height: Dimens.gap_dp8); static const Widget vGap10 = const SizedBox(height: Dimens.gap_dp10); static const Widget vGap12 = const SizedBox(height: Dimens.gap_dp12); static const Widget vGap15 = const SizedBox(height: Dimens.gap_dp15); static const Widget vGap16 = const SizedBox(height: Dimens.gap_dp16); static const Widget vGap20 = const SizedBox(height: Dimens.gap_dp20); static const Widget vGap24 = const SizedBox(height: Dimens.gap_dp24); static const Widget vGap32 = const SizedBox(height: Dimens.gap_dp32); static const Widget vGap50 = const SizedBox(height: Dimens.gap_dp50); static const Widget vGap80 = const SizedBox(height: Dimens.gap_dp80); // static Widget line = const SizedBox( // height: 0.6, // width: double.infinity, // child: const DecoratedBox(decoration: BoxDecoration(color: Colours.line)), // ); static Widget line = const Divider(); static Widget vLine = const SizedBox( width: 0.6, height: 24.0, child: const VerticalDivider(), ); static const Widget empty = const SizedBox.shrink(); }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/resource/app_text_styles.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/resource/app_fonts.dart'; import 'app_colors.dart'; class AppTextStyles { static const TextStyle appbarTitle = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.white, fontSize: 18, fontWeight: FontWeight.w600, height: 2, ); static const TextStyle text = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.text, fontSize: 14, fontWeight: FontWeight.w300, height: 19.1 / 14, ); static const TextStyle textLabel = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.text, fontSize: 13, fontWeight: FontWeight.w400, height: 20 / 13, ); static const TextStyle formFieldLabel = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.formFieldLabel, fontSize: 16, fontWeight: FontWeight.w400, ); static const TextStyle tabTitle = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.text, fontSize: 16, fontWeight: FontWeight.w400, ); static const TextStyle input = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.text, fontSize: 15, fontWeight: FontWeight.w400, ); static const TextStyle hintText = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.hintText, fontSize: 15, fontWeight: FontWeight.w400, ); static const TextStyle dialogTitle = TextStyle( fontFamily: AppFonts.roboto, color: Colors.white, fontSize: 14, fontWeight: FontWeight.w400, ); static const TextStyle itemDataLabel = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.dataLabel, fontSize: 14, fontWeight: FontWeight.w400, ); static const TextStyle itemData = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.itemData, fontSize: 14, fontWeight: FontWeight.w400, ); // Button static const TextStyle button = TextStyle( fontFamily: AppFonts.roboto, color: Colors.white, fontSize: 16, fontWeight: FontWeight.w400, ); static const TextStyle bottomNavButton = TextStyle( fontFamily: AppFonts.roboto, color: Colors.white, fontSize: 14, fontWeight: FontWeight.w400, ); static const TextStyle dialogDescription = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.text, fontSize: 14, fontWeight: FontWeight.w400, ); }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/resource/app_colors.dart
import 'package:flutter/material.dart'; class AppColors { static const Color app_main = Color(0xFF4688FA); static const Color dark_app_main = Color(0xFF3F7AE0); static const Color bg_color = Color(0xfff1f1f1); static const Color dark_bg_color = Color(0xFF18191A); static const Color material_bg = Color(0xFFFFFFFF); static const Color dark_material_bg = Color(0xFF303233); static const Color text = Color(0xFF333333); static const Color dark_text = Color(0xFFB8B8B8); static const Color text_gray = Color(0xFF999999); static const Color dark_text_gray = Color(0xFF666666); static const Color text_gray_c = Color(0xFFcccccc); static const Color dark_button_text = Color(0xFFF2F2F2); static const Color bg_gray = Color(0xFFF6F6F6); static const Color dark_bg_gray = Color(0xFF1F1F1F); static const Color line = Color(0xFFEEEEEE); static const Color dark_line = Color(0xFF3A3C3D); static const Color red = Color(0xFFFF4759); static const Color dark_red = Color(0xFFE03E4E); static const Color text_disabled = Color(0xFFD4E2FA); static const Color dark_text_disabled = Color(0xFFCEDBF2); static const Color button_disabled = Color(0xFF96BBFA); static const Color dark_button_disabled = Color(0xFF83A5E0); static const Color unselected_item_color = Color(0xffbfbfbf); static const Color dark_unselected_item_color = Color(0xFF4D4D4D); static const Color bg_gray_ = Color(0xFFFAFAFA); static const Color dark_bg_gray_ = Color(0xFF242526); static const Color gradient_blue = Color(0xFF5793FA); static const Color shadow_blue = Color(0x805793FA); static const Color orange = Color(0xFFFF8547); static const Color darkGray = Color(0xFF333333); static const primary = Color(0xFF002548); static const primaryDark = Color(0xFF001223); static const accent = Color(0xFF009AC7); static const accentDark = Color(0xFF0080A8); static const white = Color(0xFFFFFFFF); static const black = Color(0xFF000000); static const grey = Color(0xB3000000); //black 70% static const mediumGrey = Color(0x80000000); //black 50% static const lightGrey = Color(0x33000000); //black 20% static const backgroundGrey = Color(0xFFF1F2F3); static const disabledGrey = Color(0xFFE6E6E6); static const shadow = Color(0x1e000000); //black 12% static const error = Color(0xFFE30000); static const Color gray = Color(0xFF757575); static const Color tiber = Color(0xFFF2F2F2); static const Color suvaGrey = Color(0xFF8B8B8B); static const Color lightGray = Color(0xFFA9A9A9); static const Color matterhorn = Color(0xFF505050); static const Color eclipse = Color(0xFF404040); static const Color black50 = Color(0x80000000); // Colors.black.withOpacity(0.5), static const Color formFieldLabel = darkGray; // static const Color border = lightGray; static const Color tabBarBorder = suvaGrey; static const Color divider = lightGray; static const Color dialogBarrier = black50; static const Color shadow10 = Color(0x1A000000); // Colors.black.withOpacity(0.10); static const Color shadow20 = Color(0x33000000); // Colors.black.withOpacity(0.20); static const Color shadow25 = Color(0x40000000); // Colors.black.withOpacity(0.25); static const Color appBarShadow = Color(0x33A7A7A7); // Form static const Color active = primary; static const Color inactive = darkGray; static const Color background = Color(0xFFFAFAFA); static const Color formRequired = red; static const Color formTitle = darkGray; static const Color formIcon = matterhorn; static const Color hintText = gray; static const Color radioIcon = primary; static const Color radioLabel = eclipse; static const Color dropdownItem = matterhorn; static const Color dataLabel = matterhorn; static const Color itemDataLabel = gray; static const Color itemData = matterhorn; }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/resource/app_fonts.dart
class AppFonts { static const roboto = 'Roboto'; static const _openSans = 'OpenSans'; static const title = _openSans; static const body = _openSans; static const button = _openSans; }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/resource/dimens.dart
class Dimens { static const double font_sp10 = 10.0; static const double font_sp12 = 12.0; static const double font_sp13 = 13.0; static const double font_sp14 = 14.0; static const double font_sp15 = 15.0; static const double font_sp16 = 16.0; static const double font_sp18 = 18.0; static const double gap_dp4 = 4; static const double gap_dp5 = 5; static const double gap_dp8 = 8; static const double gap_dp10 = 10; static const double gap_dp12 = 12; static const double gap_dp15 = 15; static const double gap_dp16 = 16; static const double gap_dp20 = 20; static const double gap_dp24 = 24; static const double gap_dp32 = 32; static const double gap_dp50 = 50; static const double gap_dp80 = 80; }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/resource/app_constant.dart
import 'package:flutter/foundation.dart'; class AppConstants { /// App运行在Release环境时,inProduction为true;当App运行在Debug和Profile环境时,inProduction为false static const bool inProduction = kReleaseMode; static bool isDriverTest = false; static bool isUnitTest = false; static const String data = 'data'; static const String message = 'message'; static const String code = 'code'; static const String keyGuide = 'keyGuide'; static const String phone = 'phone'; static const String accessToken = 'accessToken'; static const String refreshToken = 'refreshToken'; static const String theme = 'AppTheme'; static const String locale = 'locale'; static const basicAuthPrefixHeader = 'Basic'; static const protectedAuthenticationHeaderPrefix = 'Bearer'; static const authorizationHeader = 'Authorization'; static const String not_update = 'not_update'; static const String login = 'auth'; static const Duration timesToFetchCommonDataAgain = Duration(days: 3); static const errorHappened = 'Đã có lỗi xảy ra'; static const errorHappenedTryAgain = "$errorHappened, vui lòng thử lại sau."; // static const String user_name_input_hint = 'Enter email'; static const String password_input_hint = 'Enter password'; static const String user_name_input = 'Email'; static const String password_input = 'Password'; static const String agree = 'OK'; static const String cancel = 'Huỷ bỏ'; static const String signUp = 'Đăng ký'; static const String signOut = 'Đăng xuất'; static const String featureInDevelopment = 'Chức năng đang phát triển'; static const String logo_app = 'https://meterpreter.org/wp-content/uploads/2018/09/flutter.png'; }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/presenters/profile_presenter.dart
import 'package:flutter_mockup_bloc/core/mvp/base_cubit.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_presenter.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_state_view.dart'; import 'package:flutter_mockup_bloc/repository/base_repository.dart'; import 'package:flutter_mockup_bloc/repository/profile/profile_repository.dart'; abstract class ProfileView extends BaseView { } class ProfileCubit extends BaseCubit with BaseRepoMixin{ @override BaseRepo<BaseView> createRepo() => ProfileRepo(); } class ProfilePresenter extends BasePresenter<ProfileView, ProfileCubit> { ProfilePresenter() : super(cubit: ProfileCubit()){ cubit.initRepo(); } updateProfile(){ } }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/presenters/splash_presenter.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_mockup_bloc/common/loading/loading.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_presenter.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_state_view.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_cubit.dart'; import 'package:flutter_mockup_bloc/model/UserItem.dart'; import 'package:flutter_mockup_bloc/repository/auth/user_info_repository.dart'; import 'package:flutter_mockup_bloc/repository/base_repository.dart'; import 'package:flutter_mockup_bloc/repository/multi_repository.dart'; import 'package:flutter_mockup_bloc/repository/splash/splash_repo.dart'; /* ┌────────────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ │ │ ┌───────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ │ │ │ False │ │ │ │ │ Splash ├─────────► Check Token ├─────────► Login │ │ │ │ │ │ │ │ │ │ │ └───────────────┘ └──────┬──────┘ └─────────────┘ │ │ │ │ │ │ True │ │ ┌──────▼──────┐ │ │ │ │ │ │ │ Home │ │ │ │ │ │ │ └─────────────┘ │ │ │ │ │ │ │ └────────────────────────────────────────────────────────────────────────────┘ */ abstract class SplashView implements BaseView { void gotoHome(UserInfoRepository userInfoRepository); void gotoLogin(); } class SplashCubit extends BaseCubit with BaseRepoMixin<PowerRepo>{ late SplashRepo _splashRepo; late UserInfoRepository _userInfoRepository; // SplashCubit() : super(repo: SplashRepo()); getInfoUser(){ } @override PowerRepo createRepo() { // TODO: implement createRepo final PowerRepo powerPresenter = PowerRepo<dynamic>(); _splashRepo = SplashRepo(); _userInfoRepository = UserInfoRepository(); powerPresenter.requestListRepo([_splashRepo, _userInfoRepository]); return powerPresenter; } } class SplashPresenter extends BasePresenter<SplashView, SplashCubit> { // nếu cần view thì gọi trong initStateDone, ko thì khởi tạo luôn trong constructor SplashPresenter() : _hasInfoUpdated = false, super(cubit: SplashCubit()) { // cubit.initRepo(); } late bool _hasInfoUpdated; bool get hasInfoUpdated => _hasInfoUpdated; _checkToken() async { if (cubit._splashRepo.checkTokenExits()){ view.showCustomProgress(loader: kLoadingWidget()); UserItem user = await cubit._userInfoRepository.getUserInfo(); cubit._userInfoRepository.userInfo = user.data!.userInfo!; Future.delayed(const Duration(seconds: 2)); emitState(LoadSuccessState(model: 2)); view.gotoHome(cubit._userInfoRepository); // UserItem user = cubit.getInfoUser(); } else { //goto auth view.gotoLogin(); } } _loadData() async { } test(){ } @override void initStateDone() { // TODO: implement initState cubit._userInfoRepository.setViewRepo(view); WidgetsBinding.instance!.addPostFrameCallback((_) { _checkToken(); }); super.initStateDone(); } }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/presenters/home_presenter.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_cubit.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_presenter.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_state_view.dart'; import 'package:flutter_mockup_bloc/model/AuthorResponse.dart'; import 'package:flutter_mockup_bloc/model/selectable_item.dart'; import 'package:flutter_mockup_bloc/repository/author/author_repository.dart'; import 'package:flutter_mockup_bloc/repository/base_repository.dart'; import 'package:flutter_mockup_bloc/common/common_export.dart'; import 'package:flutter_mockup_bloc/repository/city/city_repository.dart'; import 'package:flutter_mockup_bloc/repository/multi_repository.dart'; abstract class HomeView extends BaseView{ } class HomeCubit extends BaseCubit with BaseRepoMixin<PowerRepo>{ late AuthorRepository _authRepo; late CityRepository _cityRepo; AuthorRepository get authRepo => _authRepo; CityRepository get cityRepo => _cityRepo; List<ItemsAuthorResponse> _listAuthorsItem = []; List<ItemsAuthorResponse> get listAuthorsItem => _listAuthorsItem; List<SelectableItem> _listCity = []; List<SelectableItem> get listCity => _listCity; late int _currentAuthorPosition; late bool _canLoadMore = true; bool get canLoadMore => _canLoadMore; int get currentAuthorPosition => (_listAuthorsItem.length - 1); set setListAuthorsItem(List<ItemsAuthorResponse> value) { _listAuthorsItem = value; } addAllAuthorItem(List<ItemsAuthorResponse> list){ _listAuthorsItem.addAll(list); } clearListAuthors(){ _listAuthorsItem.clear(); } @override PowerRepo createRepo() { final PowerRepo powerPresenter = PowerRepo<dynamic>(); _authRepo = AuthorRepository(); _cityRepo = CityRepository(); powerPresenter.requestListRepo([_authRepo, _cityRepo]); return powerPresenter; } } class HomePresenter extends BasePresenter<HomeView, HomeCubit>{ HomePresenter() : super(cubit: HomeCubit()){ cubit.initRepo(); getListAuthor(); } getListAuthor() async { try { emitState(LoadingState()); AuthorResponse authorResponse = await cubit.authRepo.getListAuthorRepository(cubit.currentAuthorPosition + 1, 15); cubit.addAllAuthorItem(authorResponse.data!.items!); emitState(LoadSuccessState(model: authorResponse)); } catch (e){ logger.e(e.toString()); } } refreshListAuthor() async { try { cubit.clearListAuthors(); emitState(LoadingState()); AuthorResponse authorResponse = await cubit.authRepo.getListAuthorRepository(cubit.currentAuthorPosition + 1, 15); cubit.setListAuthorsItem = authorResponse.data!.items!; emitState(LoadSuccessState(model: authorResponse)); } catch (e){ logger.e(e.toString()); } } getListCity(BuildContext context) async { try { List<SelectableItem> list = await cubit.cityRepo.getListCityRepo(context); cubit._listCity = list; } catch (e){ logger.e(e.toString()); } } }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/presenters/login_presenter.dart
import 'package:flutter_mockup_bloc/core/mvp/base_cubit.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_presenter.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_state_view.dart'; import 'package:flutter_mockup_bloc/model/LoginResponse.dart'; import 'package:flutter_mockup_bloc/model/UserItem.dart'; import 'package:flutter_mockup_bloc/repository/auth/login_repository.dart'; import 'package:flutter_mockup_bloc/repository/auth/user_info_repository.dart'; import 'package:flutter_mockup_bloc/repository/base_repository.dart'; import 'package:flutter_mockup_bloc/common/common_export.dart'; import 'package:flutter_mockup_bloc/repository/multi_repository.dart'; import 'package:flutter_mockup_bloc/resource/app_constant.dart'; import 'package:sp_util/sp_util.dart'; abstract class LoginView implements BaseView { void gotoHome(UserInfoRepository userInfoRepo); void tryAgain(); } class LoginCubit extends BaseCubit with BaseRepoMixin<PowerRepo>{ late LoginRepository _loginRepo; late UserInfoRepository _userInfoRepo; LoginRepository get loginRepo => _loginRepo; UserInfoRepository get userInfoRepo => _userInfoRepo; @override PowerRepo createRepo() { // TODO: implement createRepo final PowerRepo powerPresenter = PowerRepo<dynamic>(); _loginRepo = LoginRepository(); _userInfoRepo = UserInfoRepository(); powerPresenter.requestListRepo([_loginRepo, _userInfoRepo]); return powerPresenter; } saveToken(LoginResponse loginResponse){ SpUtil.putString(AppConstants.accessToken, loginResponse.data!.accessToken!); SpUtil.putString(AppConstants.refreshToken, loginResponse.data!.refreshToken!); } } class LoginPresenter extends BasePresenter<LoginView, LoginCubit>{ LoginPresenter() : super(cubit: LoginCubit()){ cubit.initRepo(); } loginUser(email, pass) async { try { emitState(LoadingState()); LoginResponse loginResponse = await cubit.loginRepo.login(email, pass); emitState(LoadSuccessState(model: loginResponse)); UserItem user = await cubit.userInfoRepo.getUserInfo(); cubit.userInfoRepo.userInfo = user.data!.userInfo!; view.gotoHome(cubit.userInfoRepo); // view.showToast(loginResponse.data!.accessToken!); cubit.saveToken(loginResponse); } catch (e){ logger.e(e.toString()); view.tryAgain(); } } }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/model/request_response.dart
import 'dart:convert' show JsonCodec; import 'package:flutter_mockup_bloc/model/status_code.dart'; import 'package:flutter_mockup_bloc/resource/app_constant.dart'; import 'package:flutter_mockup_bloc/utils/device/system_utils.dart'; import 'error.dart'; const _jsonCodec = JsonCodec(); const String _source = 'RequestResponse'; class RequestResponse { final dynamic response; late final Map<String, dynamic> json; final int? code; final String? message; final dynamic headers; Error? error; bool get result { try { return json['data']?['result'] ?? json['error']?['result'] ?? false; } catch (e) { throw _buildJsonErrorMessage(e, 'result'); } } Map<String, dynamic> get data { try { return code == StatusCode.notFound ? {} : json['data']; } catch (e) { throw _buildJsonErrorMessage(e, 'data'); } } List<dynamic> get items { try { return code == StatusCode.notFound ? [] : data['items'] ?? []; } catch (e) { throw _buildJsonErrorMessage(e, 'items'); } } int get totalRecords { try { return data['total'] is String ? int.parse(data['total']) : data['total']; } catch (e) { throw _buildJsonErrorMessage(e, 'total'); } } bool get hasData => json['data'] != null; bool get hasError => error != null; RequestResponse(this.response, this.code, this.headers, this.message) { try { json = response is String ? _jsonCodec.decode((response as String).trim()) : response is Map ? response : {}; error = json['error'] == null ? null : Error.fromJson(json['error']); } catch (e) { error = Error( code: StatusCode.jsonDecodeError, messages: e.toString(), ); } } static Map<String, dynamic> parseResponseDataString(String str) => RequestResponse(str, StatusCode.ok, null, null).data; _buildJsonErrorMessage(Object e, String key) { if (error != null) return error!.messages; if (e.runtimeType.toString().contains('_TypeError')) SystemUtils.debugLog( _source, ''' ${e.toString()} ==> Response json did not contain key: $key reponse data: ${response.toString()} ''', ); if (e is NoSuchMethodError) { SystemUtils.debugLog( _source, ''' NoSuchMethodError: The method '[]' was called on null ==> Response json did not contain key: $key reponse data: ${response.toString()} ''', ); return AppConstants.errorHappenedTryAgain; } return e.toString(); } }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/model/status_code.dart
class StatusCode { static const ok = 200; static const unauthorized = 401; static const notFound = 404; static const requestTimeout = 408; static const badGateway = 502; static const int jsonDecodeError = 353071860; }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/model/selectable_item.dart
import 'package:equatable/equatable.dart'; import 'package:flutter_mockup_bloc/utils/extension/string_extension.dart'; class SelectableItem extends Equatable { final String id; final String name; late final bool isSelected = false; SelectableItem({ required this.id, required this.name, }); // để name = '' do api search chỉ cần id // factory SelectableItem.fromId(String id) => SelectableItem(id: id, name: ''); bool get available => id.isNotEmpty && name.isNotEmpty; bool get unavailable => available == false; factory SelectableItem.unavailable() => SelectableItem(id: '', name: ''); factory SelectableItem.fromJsonCity(Map<String, dynamic> json) => SelectableItem( id: json["code"].toString(), name: json["name"], ); @override List<Object?> get props => [id, name, isSelected]; // @override // bool get stringify => true; // @override // String toString() => "$runtimeType(id: $id, name: $name})"; } extension SelectableItemExt on List<SelectableItem> { String get names => this.map((e) => e.name.capitalize).join(', '); static bool Function(SelectableItem) equalIdTester(String desiredId) => (value) => desiredId == value.id; }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/model/UserItem.dart
class UserItem { UserItem({ Data? data, dynamic error,}){ _data = data; _error = error; } UserItem.fromJson(dynamic json) { _data = json['data'] != null ? Data.fromJson(json['data']) : null; _error = json['error']; } Data? _data; dynamic _error; UserItem copyWith({ Data? data, dynamic error, }) => UserItem( data: data ?? _data, error: error ?? _error, ); Data? get data => _data; dynamic get error => _error; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; if (_data != null) { map['data'] = _data?.toJson(); } map['error'] = _error; return map; } } class Data { Data({ bool? result, String? message, UserInfo? userInfo,}){ _result = result; _message = message; _userInfo = userInfo; } Data.fromJson(dynamic json) { _result = json['result']; _message = json['message']; _userInfo = json['user_info'] != null ? UserInfo.fromJson(json['user_info']) : null; } bool? _result; String? _message; UserInfo? _userInfo; Data copyWith({ bool? result, String? message, UserInfo? userInfo, }) => Data( result: result ?? _result, message: message ?? _message, userInfo: userInfo ?? _userInfo, ); bool? get result => _result; String? get message => _message; UserInfo? get userInfo => _userInfo; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; map['result'] = _result; map['message'] = _message; if (_userInfo != null) { map['user_info'] = _userInfo?.toJson(); } return map; } } class UserInfo { UserInfo({ String? userId, String? userEmail, String? userName, String? userImage,}){ _userId = userId; _userEmail = userEmail; _userName = userName; _userImage = userImage; } UserInfo.fromJson(dynamic json) { _userId = json['user_id']; _userEmail = json['user_email']; _userName = json['user_name']; _userImage = json['user_image']; } String? _userId; String? _userEmail; String? _userName; String? _userImage; UserInfo copyWith({ String? userId, String? userEmail, String? userName, String? userImage, }) => UserInfo( userId: userId ?? _userId, userEmail: userEmail ?? _userEmail, userName: userName ?? _userName, userImage: userImage ?? _userImage, ); String? get userId => _userId; String? get userEmail => _userEmail; String? get userName => _userName; String? get userImage => _userImage; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; map['user_id'] = _userId; map['user_email'] = _userEmail; map['user_name'] = _userName; map['user_image'] = _userImage; return map; } }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/model/City.dart
class City { City({ Data? data, dynamic error,}){ _data = data; _error = error; } City.fromJson(dynamic json) { _data = json['data'] != null ? Data.fromJson(json['data']) : null; _error = json['error']; } Data? _data; dynamic _error; City copyWith({ Data? data, dynamic error, }) => City( data: data ?? _data, error: error ?? _error, ); Data? get data => _data; dynamic get error => _error; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; if (_data != null) { map['data'] = _data?.toJson(); } map['error'] = _error; return map; } } class Data { Data({ bool? result, String? message, List<Items>? items,}){ _result = result; _message = message; _items = items; } Data.fromJson(dynamic json) { _result = json['result']; _message = json['message']; if (json['items'] != null) { _items = []; json['items'].forEach((v) { _items?.add(Items.fromJson(v)); }); } } bool? _result; String? _message; List<Items>? _items; Data copyWith({ bool? result, String? message, List<Items>? items, }) => Data( result: result ?? _result, message: message ?? _message, items: items ?? _items, ); bool? get result => _result; String? get message => _message; List<Items>? get items => _items; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; map['result'] = _result; map['message'] = _message; if (_items != null) { map['items'] = _items?.map((v) => v.toJson()).toList(); } return map; } } class Items { Items({ String? name, int? code, String? divisionType, String? codename, int? phoneCode, List<dynamic>? districts,}){ _name = name; _code = code; _divisionType = divisionType; _codename = codename; _phoneCode = phoneCode; _districts = districts; } Items.fromJson(dynamic json) { _name = json['name']; _code = json['code']; _divisionType = json['division_type']; _codename = json['codename']; _phoneCode = json['phone_code']; if (json['districts'] != null) { _districts = []; } } String? _name; int? _code; String? _divisionType; String? _codename; int? _phoneCode; List<dynamic>? _districts; Items copyWith({ String? name, int? code, String? divisionType, String? codename, int? phoneCode, List<dynamic>? districts, }) => Items( name: name ?? _name, code: code ?? _code, divisionType: divisionType ?? _divisionType, codename: codename ?? _codename, phoneCode: phoneCode ?? _phoneCode, districts: districts ?? _districts, ); String? get name => _name; int? get code => _code; String? get divisionType => _divisionType; String? get codename => _codename; int? get phoneCode => _phoneCode; List<dynamic>? get districts => _districts; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; map['name'] = _name; map['code'] = _code; map['division_type'] = _divisionType; map['codename'] = _codename; map['phone_code'] = _phoneCode; if (_districts != null) { map['districts'] = _districts?.map((v) => v.toJson()).toList(); } return map; } }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/model/city_item.dart
// To parse this JSON data, do // // final cityItem = cityItemFromJson(jsonString); import 'dart:convert'; CityItem cityItemFromJson(String str) => CityItem.fromJson(json.decode(str)); String cityItemToJson(CityItem data) => json.encode(data.toJson()); class CityItem { CityItem({ this.data, this.error, }); final Data? data; final dynamic error; factory CityItem.fromJson(Map<String, dynamic> json) => CityItem( data: json["data"] == null ? null : Data.fromJson(json["data"]), error: json["error"], ); Map<String, dynamic> toJson() => { "data": data == null ? null : data!.toJson(), "error": error, }; } class Data { Data({ this.result, this.message, this.items, }); final bool? result; final String? message; final List<Item>? items; factory Data.fromJson(Map<String, dynamic> json) => Data( result: json["result"] == null ? null : json["result"], message: json["message"] == null ? null : json["message"], items: json["items"] == null ? null : List<Item>.from(json["items"].map((x) => Item.fromJson(x))), ); Map<String, dynamic> toJson() => { "result": result == null ? null : result, "message": message == null ? null : message, "items": items == null ? null : List<dynamic>.from(items!.map((x) => x.toJson())), }; } class Item { Item({ this.name, this.code, this.divisionType, this.codename, this.phoneCode, this.districts, }); final String? name; final int? code; final String? divisionType; final String? codename; final int? phoneCode; final List<dynamic>? districts; factory Item.fromJson(Map<String, dynamic> json) => Item( name: json["name"] == null ? null : json["name"], code: json["code"] == null ? null : json["code"], divisionType: json["division_type"] == null ? null : json["division_type"], codename: json["codename"] == null ? null : json["codename"], phoneCode: json["phone_code"] == null ? null : json["phone_code"], districts: json["districts"] == null ? null : List<dynamic>.from(json["districts"].map((x) => x)), ); Map<String, dynamic> toJson() => { "name": name == null ? null : name, "code": code == null ? null : code, "division_type": divisionType == null ? null : divisionType, "codename": codename == null ? null : codename, "phone_code": phoneCode == null ? null : phoneCode, "districts": districts == null ? null : List<dynamic>.from(districts!.map((x) => x)), }; }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/model/AuthorResponse.dart
class AuthorResponse { AuthorResponse({ DataAuthorResponse? data, dynamic error,}){ _data = data; _error = error; } AuthorResponse.fromJson(dynamic json) { _data = json['data'] != null ? DataAuthorResponse.fromJson(json['data']) : null; _error = json['error']; } DataAuthorResponse? _data; dynamic _error; AuthorResponse copyWith({ DataAuthorResponse? data, dynamic error, }) => AuthorResponse( data: data ?? _data, error: error ?? _error, ); DataAuthorResponse? get data => _data; dynamic get error => _error; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; if (_data != null) { map['data'] = _data?.toJson(); } map['error'] = _error; return map; } } class DataAuthorResponse { DataAuthorResponse({ bool? result, String? message, List<ItemsAuthorResponse>? items,}){ _result = result; _message = message; _items = items; } DataAuthorResponse.fromJson(dynamic json) { _result = json['result']; _message = json['message']; if (json['items'] != null) { _items = []; json['items'].forEach((v) { _items?.add(ItemsAuthorResponse.fromJson(v)); }); } } bool? _result; String? _message; List<ItemsAuthorResponse>? _items; DataAuthorResponse copyWith({ bool? result, String? message, List<ItemsAuthorResponse>? items, }) => DataAuthorResponse( result: result ?? _result, message: message ?? _message, items: items ?? _items, ); bool? get result => _result; String? get message => _message; List<ItemsAuthorResponse>? get items => _items; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; map['result'] = _result; map['message'] = _message; if (_items != null) { map['items'] = _items?.map((v) => v.toJson()).toList(); } return map; } } class ItemsAuthorResponse { ItemsAuthorResponse({ String? createdAt, String? name, String? avatar, String? id,}){ _createdAt = createdAt; _name = name; _avatar = avatar; _id = id; } ItemsAuthorResponse.fromJson(dynamic json) { _createdAt = json['createdAt']; _name = json['name']; _avatar = json['avatar']; _id = json['id']; } String? _createdAt; String? _name; String? _avatar; String? _id; ItemsAuthorResponse copyWith({ String? createdAt, String? name, String? avatar, String? id, }) => ItemsAuthorResponse( createdAt: createdAt ?? _createdAt, name: name ?? _name, avatar: avatar ?? _avatar, id: id ?? _id, ); String? get createdAt => _createdAt; String? get name => _name; String? get avatar => _avatar; String? get id => _id; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; map['createdAt'] = _createdAt; map['name'] = _name; map['avatar'] = _avatar; map['id'] = _id; return map; } }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/model/error.dart
class Error { Error({ required this.code, required this.messages, }); int code; String messages; factory Error.fromJson(Map<String, dynamic> json) => Error( code: json["code"] ?? 0, messages: (json["messages"] ?? json["message"]).toString(), ); Map<String, dynamic> toJson() => { "code": code, "messages": messages, }; @override String toString() { return "code: $code, messages: $messages"; } }
0
mirrored_repositories/flutter_mockup_bloc/lib
mirrored_repositories/flutter_mockup_bloc/lib/model/LoginResponse.dart
class LoginResponse{ LoginResponse({ Data? data, dynamic error,}){ _data = data; _error = error; } LoginResponse.fromJson(dynamic json) { _data = json['data'] != null ? Data.fromJson(json['data']) : null; _error = json['error']; } Data? _data; dynamic _error; LoginResponse copyWith({ Data? data, dynamic error, }) => LoginResponse( data: data ?? _data, error: error ?? _error, ); Data? get data => _data; dynamic get error => _error; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; if (_data != null) { map['data'] = _data?.toJson(); } map['error'] = _error; return map; } } class Data { Data({ bool? result, String? accessToken, String? refreshToken, String? message,}){ _result = result; _accessToken = accessToken; _refreshToken = refreshToken; _message = message; } Data.fromJson(dynamic json) { _result = json['result']; _accessToken = json['access_token']; _refreshToken = json['refresh_token']; _message = json['message']; } bool? _result; String? _accessToken; String? _refreshToken; String? _message; Data copyWith({ bool? result, String? accessToken, String? refreshToken, String? message, }) => Data( result: result ?? _result, accessToken: accessToken ?? _accessToken, refreshToken: refreshToken ?? _refreshToken, message: message ?? _message, ); bool? get result => _result; String? get accessToken => _accessToken; String? get refreshToken => _refreshToken; String? get message => _message; Map<String, dynamic> toJson() { final map = <String, dynamic>{}; map['result'] = _result; map['access_token'] = _accessToken; map['refresh_token'] = _refreshToken; map['message'] = _message; return map; } }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/resource/assets.gen.dart
/// GENERATED CODE - DO NOT MODIFY BY HAND /// ***************************************************** /// FlutterGen /// ***************************************************** // ignore_for_file: directives_ordering,unnecessary_import import 'package:flutter/widgets.dart'; class $AssetImageGen { const $AssetImageGen(); /// File path: asset/image/.keep String get keep => 'asset/image/.keep'; } class Assets { Assets._(); static const $AssetImageGen image = $AssetImageGen(); } class AssetGenImage extends AssetImage { const AssetGenImage(String assetName) : super(assetName); Image image({ Key? key, ImageFrameBuilder? frameBuilder, ImageLoadingBuilder? loadingBuilder, ImageErrorWidgetBuilder? errorBuilder, String? semanticLabel, bool excludeFromSemantics = false, double? width, double? height, Color? color, BlendMode? colorBlendMode, BoxFit? fit, AlignmentGeometry alignment = Alignment.center, ImageRepeat repeat = ImageRepeat.noRepeat, Rect? centerSlice, bool matchTextDirection = false, bool gaplessPlayback = false, bool isAntiAlias = false, FilterQuality filterQuality = FilterQuality.low, }) { return Image( key: key, image: this, frameBuilder: frameBuilder, loadingBuilder: loadingBuilder, errorBuilder: errorBuilder, semanticLabel: semanticLabel, excludeFromSemantics: excludeFromSemantics, width: width, height: height, color: color, colorBlendMode: colorBlendMode, fit: fit, alignment: alignment, repeat: repeat, centerSlice: centerSlice, matchTextDirection: matchTextDirection, gaplessPlayback: gaplessPlayback, isAntiAlias: isAntiAlias, filterQuality: filterQuality, ); } String get path => assetName; }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/error_handling/app_error_state.dart
import 'package:dio/dio.dart'; import 'package:flutter_mockup_bloc/core/error_handling/exceptions.dart'; enum AppErrorState { lostConnection, poorConnection, serverDataStructureChanged, lookupServerFailure, unkownn, } extension AppErrorStateExt on AppErrorState { String get friendlyMessage { switch (this) { case AppErrorState.lostConnection: return 'Không có kết nối mạng.'; case AppErrorState.poorConnection: return 'Kết nối mạng kém.'; case AppErrorState.serverDataStructureChanged: return 'Có vẻ như ứng dụng cần được cập nhật ' 'phiên bản mới để phản ánh những thay đổi ở phía chúng tôi.'; case AppErrorState.lookupServerFailure: return 'Có vẻ như đã có sự cố xảy ra ở phía chúng tôi, ' 'vui lòng thử lại sau.'; case AppErrorState.unkownn: return 'Đã có lỗi xảy ra, vui lòng thử lại sau.'; } } static String getFriendlyRequestResponseError( Object e, { bool rethrowUnhandled = false, }) { if (e is String) return e; return AppErrorStateExt.getAppErrorState( e, rethrowUnhandled: rethrowUnhandled, ).friendlyMessage; } static String getFriendlyErrorString( Object e, { bool rethrowUnhandled = false, }) => getFriendlyRequestResponseError(e, rethrowUnhandled: rethrowUnhandled); static AppErrorState getAppErrorState( Object e, { bool rethrowUnhandled = false, }) { if (e is NoConnectionException) return AppErrorState.lostConnection; if (e is PoorConnectionException) return AppErrorState.poorConnection; if (e is InternalServerException) return AppErrorState.lookupServerFailure; if (e is DataParsingException) return AppErrorState.serverDataStructureChanged; if (e is DioError && e.message.contains('SocketException')) return AppErrorState.lostConnection; if (rethrowUnhandled) throw e; return AppErrorState.unkownn; } }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/error_handling/exceptions.dart
abstract class AppException implements Exception { final String? message; final String? from; AppException(this.message, this.from); } class UnhandledException extends AppException { UnhandledException([String? message, String? from]) : super(message ?? 'Unkown', from); String toString() { return ''' UnhandledException: $message from: $from '''; } } class DataNotFoundException extends AppException { DataNotFoundException(String message, [String? from]) : super(message, from); String toString() { return ''' DataNotFoundException: $message not found from: $from '''; } } class InternalServerException extends AppException { InternalServerException([String? message, String? from]) : super(message, from); String toString() { return ''' InternalServerException: $message from: $from '''; } } class NoConnectionException extends AppException { NoConnectionException([String? message, String? from]) : super(message, from); String toString() { return ''' NoConnectionException: $message from: $from '''; } } class PoorConnectionException extends AppException { PoorConnectionException([String? message, String? from]) : super(message, from); String toString() { return ''' PoorConnectionException: $message from: $from '''; } } class DataParsingException extends AppException { DataParsingException(String message, [String? from]) : super(message, from); String toString() { return ''' DataParsingException: $message from: $from '''; } }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/error_handling/errors.dart
/// The operation was not allowed by the object. /// /// This [Error] is thrown when an instance cannot implement one of the methods /// in its signature. @pragma("vm:entry-point") class PermissionDenied extends UnsupportedError { PermissionDenied(String message) : super(message); @override String toString() => "Permission denied: $message"; } class FileNotFound extends Error { @override String toString() => "Không tìm thấy file!"; }
0
mirrored_repositories/flutter_mockup_bloc/lib/core/generated/json
mirrored_repositories/flutter_mockup_bloc/lib/core/generated/json/base/json_convert_content.dart
// ignore_for_file: non_constant_identifier_names // ignore_for_file: camel_case_types // ignore_for_file: prefer_single_quotes // This file is automatically generated. DO NOT EDIT, all your changes would be lost. import 'package:flutter_mockup_bloc/model/AuthorResponse.dart'; import 'package:flutter_mockup_bloc/model/City.dart'; import 'package:flutter_mockup_bloc/model/LoginResponse.dart'; import 'package:flutter_mockup_bloc/model/UserItem.dart'; import 'package:flutter_mockup_bloc/model/request_response.dart'; JsonConvert jsonConvert = JsonConvert(); class JsonConvert { T? convert<T>(dynamic value) { if (value == null) { return null; } return asT<T>(value); } T? asT<T extends Object?>(dynamic value) { if (value is T) { return value; } final String type = T.toString(); try { final String valueS = value.toString(); if (type == "String") { return valueS as T; } else if (type == "int") { final int? intValue = int.tryParse(valueS); if (intValue == null) { return double.tryParse(valueS)?.toInt() as T?; } else { return intValue as T; } } else if (type == "double") { return double.parse(valueS) as T; } else if (type == "DateTime") { return DateTime.parse(valueS) as T; } else if (type == "bool") { if (valueS == '0' || valueS == '1') { return (valueS == '1') as T; } return (valueS == 'true') as T; } else { return JsonConvert.fromJsonAsT<T>(value); } } catch (e, stackTrace) { print('asT<$T> $e $stackTrace'); return null; } } //Go back to a single instance by type static M? _fromJsonSingle<M>(Map<String, dynamic> json) { // nhớ gen file json model xong phải vào đây thêm model để convert ở dio final String type = M.toString(); if (type == (City).toString()){ return City.fromJson(json) as M; } if (type == (LoginResponse).toString()){ return LoginResponse.fromJson(json) as M; } if (type == (AuthorResponse).toString()){ return AuthorResponse.fromJson(json) as M; } if (type == (UserItem).toString()){ return UserItem.fromJson(json) as M; } print("$type not found"); return null; } static M? fromJsonAsT<M>(RequestResponse json) { return _fromJsonSingle<M>(json.data); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/core/generated/json
mirrored_repositories/flutter_mockup_bloc/lib/core/generated/json/base/json_field.dart
// ignore_for_file: non_constant_identifier_names // ignore_for_file: camel_case_types // ignore_for_file: prefer_single_quotes // This file is automatically generated. DO NOT EDIT, all your changes would be lost. class JsonSerializable{ const JsonSerializable(); } class JSONField { //Specify the parse field name final String? name; //Whether to participate in toJson final bool? serialize; //Whether to participate in fromMap final bool? deserialize; const JSONField({this.name, this.serialize, this.deserialize}); }
0
mirrored_repositories/flutter_mockup_bloc/lib/core/view_model
mirrored_repositories/flutter_mockup_bloc/lib/core/view_model/global/global_viewmodel.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/provider/change_notifier_ex.dart'; import 'package:flutter_mockup_bloc/repository/debug/debug_repository.dart'; import 'package:flutter_mockup_bloc/repository/locale/locale_repository.dart'; import 'package:flutter_mockup_bloc/repository/shared_prefs/local/local_storage.dart'; import 'package:flutter_mockup_bloc/utils/env/flavor_config.dart'; import 'package:flutter_mockup_bloc/utils/locale/localization.dart'; import 'package:flutter_mockup_bloc/utils/locale/localization_delegate.dart'; import 'package:flutter_mockup_bloc/utils/locale/localization_keys.dart'; import 'package:injectable/injectable.dart'; @injectable class GlobalViewModel with ChangeNotifierEx { final LocaleRepository _localeRepo; final DebugRepository _debugRepo; final LocalStorage _localStorage; var _localeDelegate = LocalizationDelegate(); var _showsTranslationKeys = false; TargetPlatform? _targetPlatform; GlobalViewModel( this._localeRepo, this._debugRepo, this._localStorage, ); ThemeMode get themeMode => FlavorConfig.instance.themeMode; Locale? get locale => _localeDelegate.newLocale; TargetPlatform? get targetPlatform => _targetPlatform; LocalizationDelegate get localeDelegate => _localeDelegate; bool get showsTranslationKeys => _showsTranslationKeys; Future<void> init() async { _initLocale(); _initTargetPlatform(); _getThemeMode(); } void _initTargetPlatform() { _targetPlatform = _debugRepo.getTargetPlatform(); notifyListeners(); } void _initLocale() { final locale = _localeRepo.getCustomLocale(); if (locale != null) { _localeDelegate = LocalizationDelegate(newLocale: locale); notifyListeners(); } } void _getThemeMode() { FlavorConfig.instance.themeMode = _localStorage.getThemeMode(); notifyListeners(); } Future<void> onSwitchToVietnam() async { await _onUpdateLocaleClicked(const Locale('vi')); } Future<void> onSwitchToEnglish() async { await _onUpdateLocaleClicked(const Locale('en')); } Future<void> onSwitchToSystemLanguage() async { await _onUpdateLocaleClicked(null); } Future<void> _onUpdateLocaleClicked(Locale? locale) async { await _localeRepo.setCustomLocale(locale); _localeDelegate = LocalizationDelegate(newLocale: locale); notifyListeners(); } Future<void> setSelectedPlatformToAndroid() async { await _debugRepo.saveSelectedPlatform('android'); _initTargetPlatform(); } Future<void> setSelectedPlatformToIOS() async { await _debugRepo.saveSelectedPlatform('ios'); _initTargetPlatform(); } Future<void> setSelectedPlatformToDefault() async { await _debugRepo.saveSelectedPlatform(null); _initTargetPlatform(); } Future<void> updateThemeMode(ThemeMode themeMode) async { FlavorConfig.instance.themeMode = themeMode; notifyListeners(); await _localStorage.updateThemeMode(themeMode); } String getCurrentPlatform() { if (targetPlatform == TargetPlatform.android) { return LocalizationKeys.generalLabelAndroid; } else if (targetPlatform == TargetPlatform.iOS) { return LocalizationKeys.generalLabelIos; } return LocalizationKeys.generalLabelSystemDefault; } String getAppearanceValue(Localization localization) { switch (FlavorConfig.instance.themeMode) { case ThemeMode.dark: return localization.themeModeLabelDark; case ThemeMode.light: return localization.themeModeLabelLight; default: return localization.themeModeLabelSystem; } } String getCurrentLanguage() { switch (localeDelegate.activeLocale?.languageCode) { case 'vi': return 'Vietname'; case 'en': return 'English'; } return 'English'; } bool isLanguageSelected(String? languageCode) { if (localeDelegate.activeLocale == null && languageCode == null) return true; return localeDelegate.activeLocale?.languageCode == languageCode; } void toggleTranslationKeys() { _showsTranslationKeys = !showsTranslationKeys; _localeDelegate = LocalizationDelegate(newLocale: localeDelegate.activeLocale, showLocalizationKeys: showsTranslationKeys); notifyListeners(); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/net/http_api.dart
class HttpApi{ static const String users = 'users/simplezhli'; static const String search = 'search/repositories'; static const String subscriptions = 'users/simplezhli/subscriptions'; static const String upload = 'uuc/upload-inco'; }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/net/net.dart
export 'dio_utils.dart'; export 'error_handle.dart'; export 'http_api.dart';
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/net/api.dart
class Api { static const String BASE_API_URL = 'https://stoplight.io/mocks/phongdoan/test/11233479/'; static const String REFRESH_TOKEN = BASE_API_URL + 'refresh_token.php'; static const String LOGIN = BASE_API_URL + 'login'; static const String GET_LIST_CITY = BASE_API_URL + 'get_list_city'; static const String GET_LIST_AUTHOR = BASE_API_URL + 'get_list_authors'; static const String USER_INFO = BASE_API_URL + 'user_info'; }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/net/dio_utils.dart
import 'dart:convert'; import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_mockup_bloc/model/request_response.dart'; import 'package:flutter_mockup_bloc/model/status_code.dart'; import 'package:flutter_mockup_bloc/resource/app_constant.dart'; import 'error_handle.dart'; import 'package:flutter_mockup_bloc/common/common_export.dart'; /// Cấu hình Dio mặc định int _connectTimeout = 15000; int _receiveTimeout = 15000; int _sendTimeout = 10000; String _baseUrl = ''; List<Interceptor> _interceptors = []; void configDio({ int? connectTimeout, int? receiveTimeout, int? sendTimeout, String? baseUrl, List<Interceptor>? interceptors, }) { _connectTimeout = connectTimeout ?? _connectTimeout; _receiveTimeout = receiveTimeout ?? _receiveTimeout; _sendTimeout = sendTimeout ?? _sendTimeout; _baseUrl = baseUrl ?? _baseUrl; _interceptors = interceptors ?? _interceptors; } typedef NetSuccessCallback<T> = Function(T data); typedef NetSuccessListCallback<T> = Function(List<T> data); typedef NetErrorCallback = Function(int code, String msg); class DioUtils { factory DioUtils() => _singleton; DioUtils._() { final BaseOptions options = BaseOptions( connectTimeout: _connectTimeout, receiveTimeout: _receiveTimeout, sendTimeout: _sendTimeout, responseType: ResponseType.plain, validateStatus: (_) { return true; }, baseUrl: _baseUrl, // contentType: Headers.formUrlEncodedContentType, // Thích hợp cho việc gửi post-form ); _dio = Dio(options); // (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = // (HttpClient client) { // client.findProxy = (uri) { // //proxy all request to localhost:8888 // return 'PROXY 10.41.0.132:8888'; // }; // client.badCertificateCallback = // (X509Certificate cert, String host, int port) => true; // }; /// thêm Interceptor void addInterceptor(Interceptor interceptor) { _dio.interceptors.add(interceptor); } _interceptors.forEach(addInterceptor); } static final DioUtils _singleton = DioUtils._(); static DioUtils get instance => DioUtils(); static late Dio _dio; Dio get dio => _dio; // Định dạng trả về dữ liệu thống nhất và xử lý thống nhất các ngoại lệ Future<RequestResponse> _request<T>(String method, String url, { Object? data, Map<String, dynamic>? queryParameters, CancelToken? cancelToken, Options? options, }) async { final Response<String> response = await _dio.request<String>( url, data: data, queryParameters: queryParameters, options: _checkOptions(method, options), cancelToken: cancelToken, ); try { final String data = response.data.toString(); final bool isCompute = !AppConstants.isDriverTest && data.length > 10 * 1024; // debugPrint('isCompute:$isCompute'); final Map<String, dynamic> map = isCompute ? await compute(parseData, data) : parseData(data); final statusCodeFromServer = parseData(response.toString())['code']; // print(response); // print("response statusCode: ${statusCodeFromServer}"); // check lai cho nay return RequestResponse(map, statusCodeFromServer == 0 ? response.statusCode : statusCodeFromServer, response.headers, parseData(response.toString())['message'] ?? ""); } catch(e) { debugPrint(e.toString()); return RequestResponse(ExceptionHandle.parse_error, response.statusCode, response.headers, e.toString()); } } Options _checkOptions(String method, Options? options) { options ??= Options(); options.method = method; return options; } Future requestNetwork(Method method, String url, { NetSuccessCallback<dynamic>? onSuccess, NetErrorCallback? onError, Object? params, Map<String, dynamic>? queryParameters, CancelToken? cancelToken, Options? options, }) { return _request<RequestResponse>(method.value, url, data: params, queryParameters: queryParameters, options: options, cancelToken: cancelToken, ).then<void>((RequestResponse result) { // print("result.code: ${result.code}"); // print("result.message: ${result.message}"); if (result.code == StatusCode.ok) { onSuccess?.call(result); } else { _onError(result.code, result.message!, onError); } }, onError: (dynamic e) { _cancelLogPrint(e, url); final NetError error = ExceptionHandle.handleException(e); _onError(error.code, error.msg, onError); }); } void asyncRequestNetwork<T>(Method method, String url, { NetSuccessCallback<dynamic>? onSuccess, NetErrorCallback? onError, Object? params, Map<String, dynamic>? queryParameters, CancelToken? cancelToken, Options? options, }) { Stream.fromFuture(_request<T>(method.value, url, data: params, queryParameters: queryParameters, options: options, cancelToken: cancelToken, )).asBroadcastStream() .listen((result) { if (result.code == 0) { if (onSuccess != null) { onSuccess(result.data); } } else { _onError(result.code, result.message!, onError); } }, onError: (dynamic e) { _cancelLogPrint(e, url); final NetError error = ExceptionHandle.handleException(e); _onError(error.code, error.msg, onError); }); } void _cancelLogPrint(dynamic e, String url) { if (e is DioError && CancelToken.isCancel(e)) { logger.error('Huỷ in log:', error: e.toString()); } } void _onError(int? code, String msg, NetErrorCallback? onError) { if (code == null) { code = ExceptionHandle.unknown_error; msg = 'Ngoại lệ không xác định'; } logger.error('Request Exception:', error: 'code: $code, mag: $msg'); onError?.call(code, msg); } } Map<String, dynamic> parseData(String data) { return json.decode(data) as Map<String, dynamic>; } enum Method { get, post, put, patch, delete, head } extension MethodExtension on Method { String get value => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD'][index]; }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/net/intercept.dart
import 'dart:convert'; import 'package:dio/dio.dart'; import 'package:flutter_mockup_bloc/resource/app_constant.dart'; import 'package:flutter_mockup_bloc/utils/device/device_utils.dart'; import 'package:sp_util/sp_util.dart'; import 'package:sprintf/sprintf.dart'; import 'dio_utils.dart'; import 'error_handle.dart'; import 'package:flutter_mockup_bloc/common/common_export.dart'; import 'package:flutter_mockup_bloc/utils/device/other_utils.dart'; class AuthInterceptor extends Interceptor { @override void onRequest(RequestOptions options, RequestInterceptorHandler handler) { final String accessToken = SpUtil.getString(AppConstants.accessToken).nullSafe; if (accessToken.isNotEmpty) { options.headers['Authorization'] = 'token $accessToken'; } if (!Device.isWeb) { options.headers['User-Agent'] = 'Mozilla/5.0'; } super.onRequest(options, handler); } } class TokenInterceptor extends Interceptor { Dio? _tokenDio; Future<String?> getToken() async { final Map<String, String> params = <String, String>{}; params['refresh_token'] = SpUtil.getString(AppConstants.refreshToken).nullSafe; try { _tokenDio ??= Dio(); _tokenDio!.options = DioUtils.instance.dio.options; final Response response = await _tokenDio!.post<dynamic>('login/pathToRefreshToken', data: params); if (response.statusCode == ExceptionHandle.success) { return (json.decode(response.data.toString()) as Map<String, dynamic>)['access_token'] as String; } } catch(e) { logger.error('Không thể làm mới được token!', error: 'Không thể làm mới được token!'); } return null; } @override Future<void> onResponse(Response response, ResponseInterceptorHandler handler) async { //401 token hết hạn if (response.statusCode == ExceptionHandle.unauthorized) { logger.info('-----------Làm mới Token------------'); final Dio dio = DioUtils.instance.dio; dio.lock(); final String? accessToken = await getToken(); // Lấy accessToken mới khi token hết hạn logger.info('-----------NewToken: $accessToken ------------'); SpUtil.putString(AppConstants.accessToken, accessToken.nullSafe); dio.unlock(); if (accessToken != null) { // Lấy token ko thành công final RequestOptions request = response.requestOptions; request.headers['Authorization'] = 'Bearer $accessToken'; final Options options = Options( headers: request.headers, method: request.method, ); try { logger.info('----------- Yêu cầu lại token mới ------------'); /// Tránh lặp lại bằng cách sử dụng tokenDio final Response response = await _tokenDio!.request<dynamic>(request.path, data: request.data, queryParameters: request.queryParameters, cancelToken: request.cancelToken, options: options, onReceiveProgress: request.onReceiveProgress, ); return handler.next(response); } on DioError catch (e) { return handler.reject(e); } } } super.onResponse(response, handler); } } class LoggingInterceptor extends Interceptor{ late DateTime _startTime; late DateTime _endTime; @override void onRequest(RequestOptions options, RequestInterceptorHandler handler) { _startTime = DateTime.now(); logger.debug('----------Start----------'); if (options.queryParameters.isEmpty) { logger.debug('RequestUrl: ${options.baseUrl}${options.path}'); } else { logger.debug('RequestUrl: ${options.baseUrl}${options.path}?${Transformer.urlEncodeMap(options.queryParameters)}'); } logger.debug('RequestMethod: ${options.method}'); logger.debug('RequestHeaders:${options.headers}'); logger.debug('RequestContentType: ${options.contentType}'); logger.debug('RequestData: ${options.data.toString()}'); super.onRequest(options, handler); } @override void onResponse(Response response, ResponseInterceptorHandler handler) { _endTime = DateTime.now(); final int duration = _endTime.difference(_startTime).inMilliseconds; if (response.statusCode == ExceptionHandle.success) { logger.debug('ResponseCode: ${response.statusCode}'); } else { logger.e('ResponseCode: ${response.statusCode}'); } // in đầu ra logger.info(response.data.toString()); logger.debug('----------End in: $duration seconds----------'); super.onResponse(response, handler); } @override void onError(DioError err, ErrorInterceptorHandler handler) { logger.debug('----------Error-----------'); super.onError(err, handler); } } class AdapterInterceptor extends Interceptor{ static const String _kMsg = 'msg'; static const String _kSlash = "'"; static const String _kMessage = 'message'; static const String _kDefaultText = 'Không có thông tin trả lại'; static const String _kNotFound = 'Không tìm thấy thông tin truy vấn'; static const String _kFailureFormat = '{"code":%d,"message":"%s"}'; static const String _kSuccessFormat = '{"code":0,"data":%s,"message":""}'; @override void onResponse(Response response, ResponseInterceptorHandler handler) { final Response r = adapterData(response); super.onResponse(r, handler); } @override void onError(DioError err, ErrorInterceptorHandler handler) { if (err.response != null) { adapterData(err.response!); } super.onError(err, handler); } Response adapterData(Response response) { String result; String content = response.data?.toString() ?? ''; /// Khi thành công, hãy định dạng trả lại trực tiếp if (response.statusCode == ExceptionHandle.success || response.statusCode == ExceptionHandle.success_not_content) { if (content.isEmpty) { content = _kDefaultText; } result = sprintf(_kSuccessFormat, [content]); response.statusCode = ExceptionHandle.success; } else { if (response.statusCode == ExceptionHandle.not_found) { /// Sau khi định dạng dữ liệu lỗi, trả về theo dữ liệu thành công result = sprintf(_kFailureFormat, [response.statusCode, _kNotFound]); response.statusCode = ExceptionHandle.success; } else { if (content.isEmpty) { // ngắt kết nối mạng result = content; } else { String msg; try { content = content.replaceAll(r'\', ''); if (_kSlash == content.substring(0, 1)) { content = content.substring(1, content.length - 1); } final Map<String, dynamic> map = json.decode(content) as Map<String, dynamic>; if (map.containsKey(_kMessage)) { msg = map[_kMessage] as String; } else if (map.containsKey(_kMsg)) { msg = map[_kMsg] as String; } else { msg = 'Ngoại lệ không xác định'; } result = sprintf(_kFailureFormat, [response.statusCode, msg]); // 401 Token không hợp lệ, nó sẽ được xử lý riêng và những mã khác sẽ thành công. if (response.statusCode == ExceptionHandle.unauthorized) { response.statusCode = ExceptionHandle.unauthorized; } else { response.statusCode = ExceptionHandle.success; } } catch (e) { logger.e('Thông tin ngoại lệ:$e'); // Các ngoại lệ phân tích cú pháp được xử lý trực tiếp theo dữ liệu ban đầu được trả về (thông thường, 500.503 mã trang HTML được trả về) result = sprintf(_kFailureFormat, [response.statusCode, 'Máy chủ ngoại lệ(${response.statusCode})']); } } } } response.data = result; return response; } }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/net/error_handle.dart
import 'dart:io'; import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; class ExceptionHandle { static const int success = 200; static const int success_not_content = 204; static const int not_modified = 304; static const int unauthorized = 401; static const int forbidden = 403; static const int not_found = 404; static const int net_error = 1000; static const int parse_error = 1001; static const int socket_error = 1002; static const int http_error = 1003; static const int connect_timeout_error = 1004; static const int send_timeout_error = 1005; static const int receive_timeout_error = 1006; static const int cancel_error = 1007; static const int unknown_error = 9999; static final Map<int, NetError> _errorMap = <int, NetError>{ net_error : NetError(net_error, 'Mạng không bình thường, vui lòng kiểm tra mạng của bạn!'), parse_error : NetError(parse_error, 'Lỗi phân tích cú pháp dữ liệu!'), socket_error : NetError(socket_error, 'Mạng không bình thường, vui lòng kiểm tra mạng của bạn!'), http_error : NetError(http_error, 'Máy chủ ngoại lệ, vui lòng thử lại sau!'), connect_timeout_error : NetError(connect_timeout_error, 'Kết nối quá hạn!'), send_timeout_error : NetError(send_timeout_error, 'Yêu cầu đã hết thời gian chờ!'), receive_timeout_error : NetError(receive_timeout_error, 'Đã hết thời gian trả lời!'), cancel_error : NetError(cancel_error, 'Hủy bỏ yêu cầu'), unknown_error : NetError(unknown_error, 'Ngoại lệ không xác định'), }; static NetError handleException(dynamic error) { debugPrint(error.toString()); if (error is DioError) { if (error.type.errorCode == 0) { return _handleException(error.error); } else { return _errorMap[error.type.errorCode]!; } } else { return _handleException(error); } } static NetError _handleException(dynamic error) { int errorCode = unknown_error; if (error is SocketException) { errorCode = socket_error; } if (error is HttpException) { errorCode = http_error; } if (error is FormatException) { errorCode = parse_error; } return _errorMap[errorCode]!; } } class NetError{ NetError(this.code, this.msg); int code; String msg; } extension DioErrorTypeExtension on DioErrorType { int get errorCode => [ ExceptionHandle.connect_timeout_error, ExceptionHandle.send_timeout_error, ExceptionHandle.receive_timeout_error, 0, ExceptionHandle.cancel_error, 0, ][index]; }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/mvp/base_state_view.dart
import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; /* ╭━━━┳╮╱╱╱╱╱╱╱╱╱╱╱╭━━━╮╱╱╱╱╱╱╱╱╱╭━━━┳━━━┳╮╱╱╭╮ ┃╭━╮┃┃╱╱╱╱╱╱╱╱╱╱╱╰╮╭╮┃╱╱╱╱╱╱╱╱╱╰╮╭╮┃╭━━┫╰╮╭╯┃ ┃╰━╯┃╰━┳━━┳━╮╭━━╮╱┃┃┃┣━━┳━━┳━╮╱╱┃┃┃┃╰━━╋╮┃┃╭╯ ┃╭━━┫╭╮┃╭╮┃╭╮┫╭╮┃╱┃┃┃┃╭╮┃╭╮┃╭╮╮╱┃┃┃┃╭━━╯┃╰╯┃ ┃┃╱╱┃┃┃┃╰╯┃┃┃┃╰╯┃╭╯╰╯┃╰╯┃╭╮┃┃┃┃╭╯╰╯┃╰━━╮╰╮╭╯ ╰╯╱╱╰╯╰┻━━┻╯╰┻━╮┃╰━━━┻━━┻╯╰┻╯╰╯╰━━━┻━━━╯╱╰╯ ╱╱╱╱╱╱╱╱╱╱╱╱╱╭━╯┃ ╱╱╱╱╱╱╱╱╱╱╱╱╱╰━━╯ */ abstract class BaseView { BuildContext getContext(); /// Show Progress void showProgress(); /// Close Progress void closeProgress(); /// Show Toast void showToast(String string); /// Progress void showCustomProgress({Widget loader}); /// showDialogCustom void showDialogCustom(Widget child, {String title}); void initViewDone(); } abstract class BaseState extends Equatable { const BaseState(); @override List<Object> get props => []; } class InitSate extends BaseState {} class LoadingState extends BaseState { } class LoadSuccessState extends BaseState { final dynamic model; const LoadSuccessState({required this.model}); @override List<Object> get props => [model]; } class LoadFailedState extends BaseState { final dynamic error; const LoadFailedState({required this.error}); @override List<Object> get props => [error]; }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/mvp/base_page.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_presenter.dart'; import 'package:flutter_mockup_bloc/presentation/widgets/dialog/progress_dialog.dart'; import 'package:flutter_mockup_bloc/utils/device/toast_utils.dart'; import 'package:flutter_mockup_bloc/utils/ui/dialog/base_custom_dialog.dart'; import 'package:flutter_mockup_bloc/utils/ui/dialog/dialog_action.dart'; import 'base_state_view.dart'; import 'package:flutter_mockup_bloc/common/common_export.dart'; mixin BasePageMixin<T extends StatefulWidget, P extends BasePresenter> on State<T> implements BaseView { P? presenter; P createPresenter(); @override BuildContext getContext() { return context; } @override void closeProgress() { if (mounted && _isShowDialog) { _isShowDialog = false; Navigator.pop(context); } } bool _isShowDialog = false; @override void showProgress() { if (mounted && !_isShowDialog) { _isShowDialog = true; try { showDialog<void>( context: context, barrierDismissible: false, barrierColor: const Color(0x00FFFFFF), builder:(_) { return WillPopScope( onWillPop: () async { _isShowDialog = false; return Future.value(true); }, child: buildProgress(), ); }, ); } catch(e) { debugPrint(e.toString()); } } } @override void showCustomProgress({Widget? loader}) { if (mounted && !_isShowDialog) { _isShowDialog = true; try { showTransparentDialog( context: context, barrierDismissible: false, builder:(_) { return WillPopScope( onWillPop: () async { _isShowDialog = false; return Future.value(true); }, child: loader!, ); } ); } catch(e) { print(e); } } } @override void showDialogCustom(Widget child, {String title = "365"}) { showDialog( context: context, barrierDismissible: false, builder: (BuildContext context) { return BaseCustomDialog( title: title, child: child, onPressed: () { Navigator.pop(context); }, ); }); } @override void showToast(String string) { Toast.show(string); } Widget buildProgress() => const ProgressDialog(hintText: 'Đang tải...'); @override void didChangeDependencies() { presenter?.didChangeDependencies(); logger.debug('$T ==> didChangeDependencies'); super.didChangeDependencies(); } @override void dispose() { presenter?.dispose(); logger.debug('$T ==> dispose'); super.dispose(); } @override void deactivate() { presenter?.deactivate(); logger.debug('$T ==> deactivate'); super.deactivate(); } @override void didUpdateWidget(T oldWidget) { presenter?.didUpdateWidgets<T>(oldWidget); logger.debug('$T ==> didUpdateWidgets'); super.didUpdateWidget(oldWidget); } @override void initState() { logger.debug('$T ==> initState'); presenter = createPresenter(); presenter?.view = this; // print("view: ${presenter?.view}"); presenter?.initStateDone(); super.initState(); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/mvp/base_presenter.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_state_view.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_cubit.dart'; abstract class ILifecycle<C extends BaseCubit> extends Cubit<BaseState>{ ILifecycle(BaseState initialState) : super(initialState); void initStateDone(); void didChangeDependencies(); void didUpdateWidgets<W>(W oldWidget); void deactivate(); void dispose(); void emitState(BaseState s); } class BasePresenter<V extends BaseView, C extends BaseCubit> extends ILifecycle { late V view; late C cubit; BasePresenter({required this.cubit}) : super(InitSate()); // late S state; @override void deactivate() {} @override void didChangeDependencies() {} @override void didUpdateWidgets<W>(W oldWidget) {} @override void initStateDone() { // TODO: implement initState view.initViewDone(); } @override void dispose() {} @override void emitState(BaseState s) { // TODO: implement emitState print("emitState: ${s}"); cubit.emit(s); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/mvp/base_list_cubit.dart
import 'package:flutter_bloc/flutter_bloc.dart'; import 'base_state_view.dart'; class BaseListCubit<V extends Cubit>{ late List<V> listCubit; @override void deactivate() {} @override void didChangeDependencies() {} @override void didUpdateWidgets<W>(W oldWidget) {} @override void dispose() {} @override void initState() {} }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/mvp/base_cubit.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_mockup_bloc/core/mvp/base_state_view.dart'; import 'package:flutter_mockup_bloc/repository/base_repository.dart'; // mixin BaseCubit<C extends Cubit> implements BaseView { // C? cubittt; // // C? getCubit() => cubittt; // } abstract class BaseCubit extends Cubit<BaseState>{ BaseCubit() : super(InitSate()); }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/mvp/multi_cubit.dart
// // import 'package:flutter_bloc/flutter_bloc.dart'; // import 'package:flutter_mockup_bloc/core/mvp/base_list_cubit.dart'; // import 'package:flutter_mockup_bloc/core/mvp/base_page.dart'; // import 'package:flutter_mockup_bloc/core/mvp/base_presenter.dart'; // import 'package:flutter_mockup_bloc/core/mvp/base_presenter.dart'; // import 'package:flutter_mockup_bloc/core/mvp/base_state_view.dart'; // // /// 管理多个Presenter,实现复用。 // class PowerPresenter<IMvpView> extends BasePresenter{ // // PowerPresenter(BasePageMixin state) { // _state = state; // } // // late BasePageMixin _state; // List<BaseCubit> _presenters = []; // // void requestPresenter(List<BaseCubit> presenters) { // _presenters = presenters; // _presenters.forEach(_requestPresenter); // } // // void _requestPresenter(BaseCubit presenter) { // presenter = _state.cubit!; // presenter.view = _state; // } // // @override // void deactivate() { // _presenters.forEach(_deactivate); // } // // void _deactivate(List<Cubit> presenter) { // presenter.deactivate(); // } // // @override // void didChangeDependencies() { // _presenters.forEach(_didChangeDependencies); // } // // void _didChangeDependencies(BasePagePresenter presenter) { // presenter.didChangeDependencies(); // } // // @override // void didUpdateWidgets<W>(W oldWidget) { // // void _didUpdateWidgets(BasePagePresenter presenter) { // presenter.didUpdateWidgets<W>(oldWidget); // } // _presenters.forEach(_didUpdateWidgets); // } // // @override // void dispose() { // _presenters.forEach(_dispose); // } // // void _dispose(Cubit presenter) { // presenter.close(); // } // // @override // void initState() { // _presenters.forEach(_initState); // } // // void _initState(Cubit presenter) { // presenter.emit(InitSate()); // } // // }
0
mirrored_repositories/flutter_mockup_bloc/lib/core
mirrored_repositories/flutter_mockup_bloc/lib/core/mvp/power_presenter.dart
// import 'package:flutter_bloc/flutter_bloc.dart'; // import 'package:flutter_mockup_bloc/core/mvp/base_page.dart'; // import 'package:flutter_mockup_bloc/core/mvp/base_page_presenter.dart'; // import 'package:flutter_mockup_bloc/core/mvp/base_presenter.dart'; // import 'package:flutter_mockup_bloc/core/mvp/base_state_view.dart'; // // /// 管理多个Presenter,实现复用。 // class PowerPresenter<IMvpView> extends Cubit { // // PowerPresenter(BasePageMixin state) : super(null) { // _state = state; // } // // late BasePageMixin _state; // List<BasePagePresenter> _presenters = []; // // void requestPresenter(List<BasePagePresenter> presenters) { // _presenters = presenters; // _presenters.forEach(_requestPresenter); // } // // void _requestPresenter(BasePagePresenter presenter) { // presenter.view = _state as BaseState; // } // // @override // void deactivate() { // _presenters.forEach(_deactivate); // } // // void _deactivate(BasePagePresenter presenter) { // presenter.deactivate(); // } // // @override // void didChangeDependencies() { // _presenters.forEach(_didChangeDependencies); // } // // void _didChangeDependencies(BasePagePresenter presenter) { // presenter.didChangeDependencies(); // } // // @override // void didUpdateWidgets<W>(W oldWidget) { // // void _didUpdateWidgets(BasePagePresenter presenter) { // presenter.didUpdateWidgets<W>(oldWidget); // } // _presenters.forEach(_didUpdateWidgets); // } // // @override // void dispose() { // _presenters.forEach(_dispose); // } // // void _dispose(BasePagePresenter presenter) { // presenter.dispose(); // } // // @override // void initState() { // _presenters.forEach(_initState); // } // // void _initState(BasePagePresenter presenter) { // presenter.initState(); // } // // }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/drawer/custom_drawer.dart
import 'package:flutter/material.dart'; import 'bottom_user_info.dart'; import 'custom_list_tile.dart'; import 'header.dart'; class CustomDrawer extends StatefulWidget { final Function(Action_Drawer)? onTapChangeLanguage; const CustomDrawer({Key? key, this.onTapChangeLanguage}) : super(key: key); @override State<CustomDrawer> createState() => _CustomDrawerState(); } class _CustomDrawerState extends State<CustomDrawer> { bool _isCollapsed = false; @override Widget build(BuildContext context) { return SafeArea( child: AnimatedContainer( curve: Curves.easeInOutCubic, duration: const Duration(milliseconds: 500), width: _isCollapsed ? 300 : 70, margin: const EdgeInsets.only(bottom: 10, top: 10), decoration: const BoxDecoration( borderRadius: BorderRadius.only( bottomRight: Radius.circular(10), topRight: Radius.circular(10), ), color: Color.fromRGBO(20, 20, 20, 1), ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ CustomDrawerHeader(isColapsed: _isCollapsed), const Divider( color: Colors.grey, ), CustomListTile( isCollapsed: _isCollapsed, icon: Icons.home_outlined, title: 'Trang chủ', infoCount: 0, onTap: () => Navigator.pop(context), ), CustomListTile( isCollapsed: _isCollapsed, icon: Icons.brightness_4_rounded, title: 'Sáng/Tối', infoCount: 0, onTap: () => widget.onTapChangeLanguage!(Action_Drawer.theme), ), CustomListTile( isCollapsed: _isCollapsed, icon: Icons.language, title: 'Ngôn ngữ', infoCount: 0, onTap: () => widget.onTapChangeLanguage!(Action_Drawer.language), ), CustomListTile( isCollapsed: _isCollapsed, icon: Icons.calendar_today, title: 'Lịch', infoCount: 0, ), CustomListTile( isCollapsed: _isCollapsed, icon: Icons.pin_drop, title: 'Vị trí', infoCount: 0, doHaveMoreOptions: Icons.arrow_forward_ios, ), CustomListTile( isCollapsed: _isCollapsed, icon: Icons.message_rounded, title: 'Tin nhắn', infoCount: 8, ), CustomListTile( isCollapsed: _isCollapsed, icon: Icons.cloud, title: 'Thời tiết', infoCount: 0, doHaveMoreOptions: Icons.arrow_forward_ios, ), CustomListTile( isCollapsed: _isCollapsed, icon: Icons.airplane_ticket, title: 'Chuyến bay', infoCount: 0, doHaveMoreOptions: Icons.arrow_forward_ios, ), const Divider(color: Colors.grey), const Spacer(), CustomListTile( isCollapsed: _isCollapsed, icon: Icons.notifications, title: 'Thông báo', infoCount: 2, ), CustomListTile( isCollapsed: _isCollapsed, icon: Icons.settings, title: 'Cài đặt', infoCount: 0, ), const SizedBox(height: 10), BottomUserInfo(isCollapsed: _isCollapsed), Align( alignment: _isCollapsed ? Alignment.bottomRight : Alignment.bottomCenter, child: IconButton( splashColor: Colors.transparent, icon: Icon( _isCollapsed ? Icons.arrow_back_ios : Icons.arrow_forward_ios, color: Colors.white, size: 16, ), onPressed: () { setState(() { _isCollapsed = !_isCollapsed; }); }, ), ), ], ), ), ), ); } } enum Action_Drawer{ theme, language }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/drawer/bottom_user_info.dart
import 'package:flutter/material.dart'; class BottomUserInfo extends StatelessWidget { final bool isCollapsed; const BottomUserInfo({ Key? key, required this.isCollapsed, }) : super(key: key); @override Widget build(BuildContext context) { return AnimatedContainer( duration: const Duration(milliseconds: 300), height: isCollapsed ? 70 : 100, width: double.infinity, decoration: BoxDecoration( color: Colors.white10, borderRadius: BorderRadius.circular(20), ), child: isCollapsed ? Center( child: Row( children: [ Expanded( flex: 2, child: Container( margin: const EdgeInsets.symmetric(horizontal: 10), width: 40, height: 40, decoration: BoxDecoration( color: Colors.grey, borderRadius: BorderRadius.circular(20), ), child: ClipRRect( borderRadius: BorderRadius.circular(20), child: Image.network( 'https://t3.ftcdn.net/jpg/02/99/21/98/360_F_299219888_2E7GbJyosu0UwAzSGrpIxS0BrmnTCdo4.jpg', fit: BoxFit.cover, ), ), ), ), Expanded( flex: 5, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: const [ Expanded( child: Align( alignment: Alignment.bottomLeft, child: Text( 'User Name', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18, ), maxLines: 1, overflow: TextOverflow.clip, ), ), ), Expanded( child: Text( 'MEMBER', style: TextStyle( color: Colors.grey, ), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), ), const Spacer(), Expanded( flex: 2, child: Padding( padding: const EdgeInsets.only(right: 10), child: IconButton( onPressed: () {}, icon: const Icon( Icons.logout, color: Colors.white, ), ), ), ), ], ), ) : Column( children: [ Expanded( child: Container( margin: const EdgeInsets.only(top: 10), width: 40, height: 40, decoration: BoxDecoration( color: Colors.grey, borderRadius: BorderRadius.circular(20), ), child: ClipRRect( borderRadius: BorderRadius.circular(20), child: Image.network( 'https://t3.ftcdn.net/jpg/02/99/21/98/360_F_299219888_2E7GbJyosu0UwAzSGrpIxS0BrmnTCdo4.jpg', fit: BoxFit.cover, ), ), ), ), Expanded( child: IconButton( onPressed: () {}, icon: const Icon( Icons.logout, color: Colors.white, size: 18, ), ), ), ], ), ); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/drawer/custom_list_tile.dart
import 'package:flutter/material.dart'; class CustomListTile extends StatelessWidget { final bool isCollapsed; final IconData icon; final String title; final IconData? doHaveMoreOptions; final int infoCount; final Function()? onTap; const CustomListTile({ Key? key, required this.isCollapsed, required this.icon, required this.title, this.doHaveMoreOptions, required this.infoCount, this.onTap, }) : super(key: key); @override Widget build(BuildContext context) { return InkWell( onTap: onTap ?? (){ }, child: AnimatedContainer( duration: const Duration(milliseconds: 500), width: isCollapsed ? 300 : 80, height: 40, child: Row( children: [ Expanded( child: Center( child: Stack( clipBehavior: Clip.none, children: [ Icon( icon, color: Colors.white, ), if (infoCount > 0) Positioned( right: -5, top: -5, child: Container( height: 10, width: 10, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.red, ), ), ), ], ), ), ), if (isCollapsed) const SizedBox(width: 10), if (isCollapsed) Expanded( flex: 3, child: Row( children: [ Expanded( flex: 4, child: Text( title, style: const TextStyle( color: Colors.white, ), maxLines: 1, overflow: TextOverflow.clip, ), ), if (infoCount > 0) Expanded( flex: 2, child: Container( margin: const EdgeInsets.only(left: 10), width: 20, height: 20, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: Colors.purple[200], ), child: Center( child: Text( infoCount.toString(), style: const TextStyle( color: Colors.black, fontWeight: FontWeight.bold, ), ), ), ), ), ], ), ), if (isCollapsed) const Spacer(), if (isCollapsed) Expanded( flex: 1, child: doHaveMoreOptions != null ? IconButton( icon: Icon( doHaveMoreOptions, color: Colors.white, size: 12, ), onPressed: () {}, ) : const Center(), ), ], ), ), ); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/drawer/header.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class CustomDrawerHeader extends StatelessWidget { final bool isColapsed; const CustomDrawerHeader({ Key? key, required this.isColapsed, }) : super(key: key); @override Widget build(BuildContext context) { return AnimatedContainer( duration: const Duration(milliseconds: 500), height: 60, width: double.infinity, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const FlutterLogo(size: 30), if (isColapsed) const SizedBox(width: 10), if (isColapsed) const Expanded( flex: 3, child: Text( 'FlyCompany', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20, ), maxLines: 1, ), ), if (isColapsed) const Spacer(), if (isColapsed) Expanded( flex: 1, child: IconButton( onPressed: () {}, icon: const Icon( Icons.search, color: Colors.white, ), ), ), ], ), ); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/author/author_item.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_mockup_bloc/common/theme/app_decoration.dart'; import 'package:flutter_mockup_bloc/common/theme/app_padding.dart'; import 'package:flutter_mockup_bloc/model/AuthorResponse.dart'; import 'package:flutter_mockup_bloc/presentation/widgets/common/load_image.dart'; import 'package:flutter_mockup_bloc/presentation/widgets/common/widget_utils.dart'; import 'package:flutter_mockup_bloc/presentation/widgets/dialog/app_dialogs.dart'; import 'package:flutter_mockup_bloc/resource/app_colors.dart'; import 'package:flutter_mockup_bloc/resource/app_fonts.dart'; import 'package:flutter_mockup_bloc/resource/app_text_styles.dart'; import 'package:flutter_mockup_bloc/utils/ui/icon_utils.dart'; import 'package:intl/intl.dart'; class AuthorItem extends StatelessWidget { AuthorItem({ Key? key, required this.model, this.switchTitlePositionWithSubtitle = false, this.showSaveBtn = false, this.showSaveAndChatBtn = false, this.explicitDate = true, this.additionalWidget, this.margin, this.addDeleteBtnBehind = false, this.onDeleteBtnBehindTap, }) : super(key: key); final ItemsAuthorResponse model; final bool switchTitlePositionWithSubtitle; final bool showSaveBtn; final bool showSaveAndChatBtn; final bool explicitDate; final Widget? additionalWidget; final EdgeInsetsGeometry? margin; final bool addDeleteBtnBehind; final void Function()? onDeleteBtnBehindTap; final DateFormat dateFormat = DateFormat("yyyy-MM-ddTHH:mm:ss"); _onTap(BuildContext context){ } _onSaveBtnTap(BuildContext context) { } _onChatBtnTap(BuildContext context) { } // _onChatBtnBehindTap(BuildContext context) => _onChatBtnTap(context) // ?.whenComplete(() => slidableController?.activeState?.close()); static const BorderRadius _borderRadius = BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10), bottomRight: Radius.circular(10), bottomLeft: Radius.circular(10), ); static const TextStyle _title = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.text, fontSize: 16, fontWeight: FontWeight.w400, height: 23 / 16, ); static const TextStyle _subtitle = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.primary, fontSize: 14, fontWeight: FontWeight.w400, height: 20 / 14, ); static const TextStyle titleSwitched = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.primary, fontSize: 16, fontWeight: FontWeight.w600, height: 23 / 16, ); static const TextStyle subtitleSwitched = TextStyle( fontFamily: AppFonts.roboto, color: AppColors.text, fontSize: 14, fontWeight: FontWeight.w400, height: 20 / 14, ); @override Widget build(BuildContext context) { final IconButton saveBtn, chatBtn; final width = MediaQuery.of(context).size.width; saveBtn = IconButton( onPressed: () => AppDialogs.showLoginDialog( context, 'Bạn chưa đăng nhập. Vui lòng đăng nhập để sử dụng tính năng này!', ), icon: IconUtils.dialog_check_icon, ); chatBtn = IconButton( onPressed: () => AppDialogs.showLoginDialog( context, 'Bạn chưa đăng nhập. Vui lòng đăng nhập để sử dụng tính năng này!', ), icon: IconUtils.dialog_check_icon, ); late final Widget avatar = ClipRRect( borderRadius: BorderRadius.circular(10), child: LoadImage(model.avatar!, width: width/3, height: width/3,), ); /* late final Widget avatar = CachedNetworkImage( key: Key(model.avatarUrl), imageUrl: model.avatarUrl, width: 80, height: 80, fit: BoxFit.cover, progressIndicatorBuilder: (_, __, ___) => const DecoratedBox( decoration: BoxDecoration( color: Colors.white, border: const Border.fromBorderSide( BorderSide( color: AppColors.border, ), ), // borderRadius: _borderRadius, shape: BoxShape.circle, // boxShadow: [ // BoxShadow( // offset: Offset(0, 0), // spreadRadius: 0.7, // color: AppColors.border, // ), // ], ), child: Padding( padding: EdgeInsets.all(16.0), child: WidgetUtils.loadingCircle, ), ), imageBuilder: (_, imageProvider) => Container( decoration: BoxDecoration( color: Colors.white, border: const Border.fromBorderSide( BorderSide( color: AppColors.border, ), ), // borderRadius: _borderRadius, shape: BoxShape.circle, image: DecorationImage( image: imageProvider, fit: BoxFit.cover, ), ), ), errorWidget: (_, __, ___) => model.isFemale == true ? Image.asset(AssetPath.anonymous_female_avatar) : Image.asset(AssetPath.anonymous_male_avatar), // const DecoratedBox( // decoration: BoxDecoration( // color: Colors.white, // borderRadius: _borderRadius, // boxShadow: [ // BoxShadow( // offset: Offset(0, 0), // spreadRadius: 0.7, // color: AppColors.border, // ), // ], // ), // child: AnonymousCandidateAvatarPainter.customPaint, // ), // // model.isFemale == true // ? const CustomPaint( // size: Size(80, 80), // painter: AnonymousFemaleCandidateAvatarPainter(), // ) // : const CustomPaint( // size: Size(80, 80), // painter: AnonymousMaleCandidateAvatarPainter(), // ), ); */ Widget current = InkWell( onTap: () => _onTap(context), borderRadius: _borderRadius, child: Ink( padding: AppPad.a16, decoration: AppDecoration.cardBox.copyWith(borderRadius: _borderRadius), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Column( children: [ avatar, const SizedBox(height: 7), if (showSaveAndChatBtn) Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [saveBtn, chatBtn], ) else if (showSaveBtn) saveBtn ], ), SizedBoxExt.w10, Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: WidgetUtils.addSizedBoxAsSeparator(SizedBoxExt.h10, [ Text( model.name!, style: titleSwitched, overflow: TextOverflow.visible, ), _getItemDataWithIcon( Icons.insert_drive_file, "(ID) ${model.id!}", ), _getItemDataWithIcon( Icons.calendar_today_outlined, "Tạo ngày: ${DateFormat("dd-MM-yyyy").format(dateFormat.parse(model.createdAt!))}", ), ]), ), ), SizedBoxExt.w10, ], ), ), ); if (margin != null) { current = Padding(padding: margin!, child: current); } return current; } Row _getItemDataWithIcon(IconData icon, String data) => Row( crossAxisAlignment: CrossAxisAlignment.center, textBaseline: TextBaseline.alphabetic, children: [ Icon(icon), SizedBoxExt.w5, Expanded( child: Text( data, style: AppTextStyles.itemData, overflow: TextOverflow.visible, ), ), ], ); Text _getItemDataWithLabel(String? label, String data) => Text.rich( TextSpan(children: [ TextSpan( text: label != null ? label + ': ' : null, style: AppTextStyles.itemDataLabel, ), TextSpan( text: data, style: AppTextStyles.itemData, ), ]), ); }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/responsive/responsive_widget.dart
import 'package:flutter/widgets.dart'; /// Widget that builds different UIs based on device characteristics /// /// Speciality builder functions exist for building on tablets regardless of /// orientation ([tabletBuilder]), tablet in landscape mode ([tabletLandscapeBuilder]), /// landscape mode ([landscapeBuilder]) or regular ([builder]). Note that if a /// specific builder is not provided, the system will fall back to the next /// specified builder. Order: [tabletLandscapeBuilder] => [tabletBuilder] => /// [landscapeBuilder] => [builder] class ResponsiveWidget extends StatelessWidget { final Function(BuildContext context, SizeInformation sizeInformation)? tabletBuilder; final Function(BuildContext context, SizeInformation sizeInformation)? landscapeBuilder; final Function(BuildContext context, SizeInformation sizeInformation)? tabletLandscapeBuilder; final Widget Function(BuildContext context, SizeInformation sizeInformation)? builder; const ResponsiveWidget({ this.tabletBuilder, this.landscapeBuilder, this.tabletLandscapeBuilder, this.builder, Key? key, }) : super(key: key); @override Widget build(BuildContext context) { final mediaQuery = MediaQuery.of(context); return LayoutBuilder(builder: (context, boxSizing) { final info = SizeInformation( orientation: mediaQuery.orientation, deviceType: getDeviceType(mediaQuery), screenSize: mediaQuery.size, localWidgetSize: Size(boxSizing.maxWidth, boxSizing.maxHeight), ); final tabletLandscapeB = tabletLandscapeBuilder; final tabletB = tabletBuilder; final landscapeB = landscapeBuilder; final portraitBuilder = builder; if (info.orientation == Orientation.landscape && info.deviceType == DeviceScreenType.Tablet && tabletLandscapeB != null) { return tabletLandscapeB(context, info); } else if (info.deviceType == DeviceScreenType.Tablet && tabletB != null) { return tabletB(context, info); } else if (info.orientation == Orientation.landscape && landscapeB != null) { return landscapeB(context, info); } else if (portraitBuilder != null) { return portraitBuilder(context, info); } throw Exception('Failed to build Responsive Widget'); }); } /// Returns the device screen type based on the [mediaQuery]. /// /// Devices are assumed to be tablets if their width (in portrait) or height /// (in landscape) is greater than a predefined number (600) static DeviceScreenType getDeviceType(MediaQueryData mediaQuery) { final orientation = mediaQuery.orientation; var deviceWidth = 0.0; if (orientation == Orientation.landscape) { deviceWidth = mediaQuery.size.height; } else { deviceWidth = mediaQuery.size.width; } if (deviceWidth > 600) { return DeviceScreenType.Tablet; } return DeviceScreenType.Mobile; } } /// The type of device screen enum DeviceScreenType { /// A mobile form factor. This can also include TVs, desktop, web, ... if the /// size indicates phone form factor. See [ResponsiveWidget.getDeviceType] Mobile, /// A tablet form factor. This can also include TVs, desktop, web, ... if the /// size indicates tablet form factor. See [ResponsiveWidget.getDeviceType] Tablet, } /// Device/screen information holder class SizeInformation { /// The orientation of the device final Orientation orientation; /// The device screen type final DeviceScreenType deviceType; /// The size of the screen final Size screenSize; /// The local max size of the widget that resolved this information final Size localWidgetSize; SizeInformation({ required this.orientation, required this.deviceType, required this.screenSize, required this.localWidgetSize, }); }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/button/pill_button.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/resource/app_colors.dart'; import 'package:flutter_mockup_bloc/resource/app_text_styles.dart'; enum ButtonType { CTA, OUTLINED_PRIMARY, OUTLINED, FILLED, BOTTOM_NAV, } extension on ButtonType { Color get backgroundColor { switch (this) { case ButtonType.CTA: case ButtonType.OUTLINED: return AppColors.primary; case ButtonType.BOTTOM_NAV: return Colors.transparent; case ButtonType.OUTLINED_PRIMARY: case ButtonType.FILLED: return Colors.white; } } Color get borderColor { switch (this) { case ButtonType.CTA: case ButtonType.OUTLINED_PRIMARY: return AppColors.primary; case ButtonType.BOTTOM_NAV: return Colors.transparent; case ButtonType.OUTLINED: case ButtonType.FILLED: return Colors.white; } } Color get textColor { switch (this) { case ButtonType.CTA: case ButtonType.OUTLINED: case ButtonType.BOTTOM_NAV: return Colors.white; case ButtonType.FILLED: case ButtonType.OUTLINED_PRIMARY: return AppColors.primary; } } FontWeight? get fontWeight { switch (this) { case ButtonType.CTA: case ButtonType.OUTLINED_PRIMARY: case ButtonType.OUTLINED: case ButtonType.FILLED: return FontWeight.w600; case ButtonType.BOTTOM_NAV: return null; } } } class PillButton extends StatelessWidget { const PillButton({ Key? key, this.width = 200, required this.type, required this.text, this.backgroundColor, this.borderColor, this.textColor, required this.onPressed, this.padding = const EdgeInsets.symmetric( horizontal: 20, vertical: 10, ), }) : /*assert(type == ButtonType.BOTTOM_NAV && backgroundColor != null, 'Button type == BOTTOM_NAV must have backgroundColor'),*/ super(key: key); final double? width; final ButtonType type; final String text; final Color? backgroundColor; final Color? borderColor; final Color? textColor; final void Function()? onPressed; final EdgeInsetsGeometry? padding; @override Widget build(BuildContext context) { Widget current = ElevatedButton( onPressed: onPressed, child: Text( text, style: type == ButtonType.BOTTOM_NAV ? AppTextStyles.bottomNavButton.copyWith(color: textColor) : AppTextStyles.button.copyWith( color: type.textColor, fontWeight: type.fontWeight, ), textAlign: TextAlign.center, ), style: ElevatedButton.styleFrom( side: BorderSide( color: type == ButtonType.BOTTOM_NAV ? borderColor ?? textColor ?? backgroundColor! : type.borderColor, ), shape: StadiumBorder(), primary: type == ButtonType.BOTTOM_NAV ? backgroundColor : type.backgroundColor, padding: padding, shadowColor: Colors.black, elevation: 4, ), ); if (width != null) current = SizedBox(width: width, child: current); return current; } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/button/app_bar_back_button.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/resource/app_colors.dart'; class AppBarBackButton extends StatelessWidget { const AppBarBackButton({ Key? key, this.onBackBtnPressed, }) : super(key: key); final void Function()? onBackBtnPressed; @override Widget build(BuildContext context) { navigateBack() => Navigator.pop(context); return IconButton( icon: const RotatedBox( quarterTurns: -2, child: Icon( Icons.play_circle_filled_rounded, size: 24, color: AppColors.primary, ), ), onPressed: onBackBtnPressed ?? navigateBack, ); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common/my_button.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/resource/app_colors.dart'; import 'package:flutter_mockup_bloc/resource/dimens.dart'; /// 默认字号18,白字蓝底,高度48 class MyButton extends StatelessWidget { const MyButton({ Key? key, this.text = '', this.fontSize = Dimens.font_sp18, this.textColor, this.disabledTextColor, this.backgroundColor, this.disabledBackgroundColor, this.minHeight = 48.0, this.minWidth = double.infinity, this.padding = const EdgeInsets.symmetric(horizontal: 16.0), this.radius = 2.0, this.side = BorderSide.none, required this.onPressed, }): super(key: key); final String text; final double fontSize; final Color? textColor; final Color? disabledTextColor; final Color? backgroundColor; final Color? disabledBackgroundColor; final double? minHeight; final double? minWidth; final VoidCallback? onPressed; final EdgeInsetsGeometry padding; final double radius; final BorderSide side; @override Widget build(BuildContext context) { final bool isDark = false; return TextButton( onPressed: onPressed, style: ButtonStyle( // 文字颜色 foregroundColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.disabled)) { return disabledTextColor ?? (isDark ? AppColors.dark_text_disabled : AppColors.text_disabled); } return textColor ?? (isDark ? AppColors.dark_button_text : Colors.white); }, ), // 背景颜色 backgroundColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.disabled)) { return disabledBackgroundColor ?? (isDark ? AppColors.dark_button_disabled : AppColors.button_disabled); } return backgroundColor ?? (isDark ? AppColors.dark_app_main : AppColors.app_main); }), // 水波纹 overlayColor: MaterialStateProperty.resolveWith((states) { return (textColor ?? (isDark ? AppColors.dark_button_text : Colors.white)).withOpacity(0.12); }), // 按钮最小大小 minimumSize: (minWidth == null || minHeight == null) ? null : MaterialStateProperty.all<Size>(Size(minWidth!, minHeight!)), padding: MaterialStateProperty.all<EdgeInsetsGeometry>(padding), shape: MaterialStateProperty.all<OutlinedBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.circular(radius), ), ), side: MaterialStateProperty.all<BorderSide>(side), ), child: Text(text, style: TextStyle(fontSize: fontSize),) ); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common/custom_tab_bar.dart
import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; const double _kTabHeight = 46.0; const double _kTextAndIconTabHeight = 72.0; class CustomTab extends StatelessWidget { /// Creates a material design [TabBar] tab. /// /// At least one of [text], [icon], and [child] must be non-null. The [text] /// and [child] arguments must not be used at the same time. The /// [iconMargin] is only useful when [icon] and either one of [text] or /// [child] is non-null. const CustomTab({ Key? key, this.text, this.icon, this.iconMargin = const EdgeInsets.only(bottom: 10.0), this.height, this.child, }) : assert(text != null || child != null || icon != null), assert(text == null || child == null), super(key: key); /// The text to display as the tab's label. /// /// Must not be used in combination with [child]. final String? text; /// The widget to be used as the tab's label. /// /// Usually a [Text] widget, possibly wrapped in a [Semantics] widget. /// /// Must not be used in combination with [text]. final Widget? child; /// An icon to display as the tab's label. final Widget? icon; /// The margin added around the tab's icon. /// /// Only useful when used in combination with [icon], and either one of /// [text] or [child] is non-null. final EdgeInsetsGeometry iconMargin; final double? height; Widget _buildLabelText() { return child ?? Text(text!, softWrap: false, overflow: TextOverflow.fade); } @override Widget build(BuildContext context) { assert(debugCheckHasMaterial(context)); if (height == null && icon == null) return _buildLabelText(); final double effectiveHeight; final Widget label; if (icon == null) { effectiveHeight = height ?? _kTabHeight; label = _buildLabelText(); } else if (text == null && child == null) { effectiveHeight = _kTabHeight; label = icon!; } else { effectiveHeight = _kTextAndIconTabHeight; label = Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Container( child: icon, margin: iconMargin, ), _buildLabelText(), ], ); } return SizedBox( height: effectiveHeight, child: Center( child: label, widthFactor: 1.0, ), ); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(StringProperty('text', text, defaultValue: null)); properties .add(DiagnosticsProperty<Widget>('icon', icon, defaultValue: null)); } } class _TabStyle extends AnimatedWidget { const _TabStyle({ Key? key, required Animation<double> animation, required this.selected, required this.labelColor, required this.unselectedLabelColor, required this.labelStyle, required this.unselectedLabelStyle, required this.child, }) : super(key: key, listenable: animation); final TextStyle? labelStyle; final TextStyle? unselectedLabelStyle; final bool selected; final Color? labelColor; final Color? unselectedLabelColor; final Widget child; @override Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); final TabBarTheme tabBarTheme = TabBarTheme.of(context); final Animation<double> animation = listenable as Animation<double>; // To enable TextStyle.lerp(style1, style2, value), both styles must have // the same value of inherit. Force that to be inherit=true here. final TextStyle defaultStyle = (labelStyle ?? tabBarTheme.labelStyle ?? themeData.primaryTextTheme.bodyText1!) .copyWith(inherit: true); final TextStyle defaultUnselectedStyle = (unselectedLabelStyle ?? tabBarTheme.unselectedLabelStyle ?? labelStyle ?? themeData.primaryTextTheme.bodyText1!) .copyWith(inherit: true); final TextStyle textStyle = selected ? TextStyle.lerp(defaultStyle, defaultUnselectedStyle, animation.value)! : TextStyle.lerp( defaultUnselectedStyle, defaultStyle, animation.value)!; final Color selectedColor = labelColor ?? tabBarTheme.labelColor ?? themeData.primaryTextTheme.bodyText1!.color!; final Color unselectedColor = unselectedLabelColor ?? tabBarTheme.unselectedLabelColor ?? selectedColor.withAlpha(0xB2); // 70% alpha final Color color = selected ? Color.lerp(selectedColor, unselectedColor, animation.value)! : Color.lerp(unselectedColor, selectedColor, animation.value)!; return DefaultTextStyle( style: textStyle.copyWith(color: color), child: IconTheme.merge( data: IconThemeData( size: 24.0, color: color, ), child: child, ), ); } } typedef _LayoutCallback = void Function( List<double> xOffsets, TextDirection textDirection, double width); class _TabLabelBarRenderer extends RenderFlex { _TabLabelBarRenderer({ List<RenderBox>? children, required Axis direction, required MainAxisSize mainAxisSize, required MainAxisAlignment mainAxisAlignment, required CrossAxisAlignment crossAxisAlignment, required TextDirection textDirection, required VerticalDirection verticalDirection, required this.onPerformLayout, }) : super( children: children, direction: direction, mainAxisSize: mainAxisSize, mainAxisAlignment: mainAxisAlignment, crossAxisAlignment: crossAxisAlignment, textDirection: textDirection, verticalDirection: verticalDirection, ); _LayoutCallback onPerformLayout; @override void performLayout() { super.performLayout(); // xOffsets will contain childCount+1 values, giving the offsets of the // leading edge of the first tab as the first value, of the leading edge of // the each subsequent tab as each subsequent value, and of the trailing // edge of the last tab as the last value. RenderBox? child = firstChild; final List<double> xOffsets = <double>[]; while (child != null) { final FlexParentData childParentData = child.parentData! as FlexParentData; xOffsets.add(childParentData.offset.dx); assert(child.parentData == childParentData); child = childParentData.nextSibling; } assert(textDirection != null); switch (textDirection!) { case TextDirection.rtl: xOffsets.insert(0, size.width); break; case TextDirection.ltr: xOffsets.add(size.width); break; } onPerformLayout(xOffsets, textDirection!, size.width); } } // This class and its renderer class only exist to report the widths of the tabs // upon layout. The tab widths are only used at paint time (see _IndicatorPainter) // or in response to input. class _TabLabelBar extends Flex { _TabLabelBar({ Key? key, List<Widget> children = const <Widget>[], required this.onPerformLayout, }) : super( key: key, children: children, direction: Axis.horizontal, mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, verticalDirection: VerticalDirection.down, ); final _LayoutCallback onPerformLayout; @override RenderFlex createRenderObject(BuildContext context) { return _TabLabelBarRenderer( direction: direction, mainAxisAlignment: mainAxisAlignment, mainAxisSize: mainAxisSize, crossAxisAlignment: crossAxisAlignment, textDirection: getEffectiveTextDirection(context)!, verticalDirection: verticalDirection, onPerformLayout: onPerformLayout, ); } @override void updateRenderObject( BuildContext context, _TabLabelBarRenderer renderObject) { super.updateRenderObject(context, renderObject); renderObject.onPerformLayout = onPerformLayout; } } double _indexChangeProgress(TabController controller) { final double controllerValue = controller.animation!.value; final double previousIndex = controller.previousIndex.toDouble(); final double currentIndex = controller.index.toDouble(); // The controller's offset is changing because the user is dragging the // TabBarView's PageView to the left or right. if (!controller.indexIsChanging) return (currentIndex - controllerValue).abs().clamp(0.0, 1.0); // The TabController animation's value is changing from previousIndex to currentIndex. return (controllerValue - currentIndex).abs() / (currentIndex - previousIndex).abs(); } class _IndicatorPainter extends CustomPainter { _IndicatorPainter({ required this.controller, required this.indicator, required this.tabKeys, required _IndicatorPainter? old, }) : super(repaint: controller.animation) { if (old != null) saveTabOffsets(old._currentTabOffsets, old._currentTextDirection); } final TabController controller; final Decoration indicator; final List<GlobalKey> tabKeys; // _currentTabOffsets and _currentTextDirection are set each time TabBar // layout is completed. These values can be null when TabBar contains no // tabs, since there are nothing to lay out. List<double>? _currentTabOffsets; TextDirection? _currentTextDirection; Rect? _currentRect; BoxPainter? _painter; bool _needsPaint = false; void markNeedsPaint() { _needsPaint = true; } void dispose() { _painter?.dispose(); } void saveTabOffsets(List<double>? tabOffsets, TextDirection? textDirection) { _currentTabOffsets = tabOffsets; _currentTextDirection = textDirection; } // _currentTabOffsets[index] is the offset of the start edge of the tab at index, and // _currentTabOffsets[_currentTabOffsets.length] is the end edge of the last tab. int get maxTabIndex => _currentTabOffsets!.length - 2; double centerOf(int tabIndex) { assert(_currentTabOffsets != null); assert(_currentTabOffsets!.isNotEmpty); assert(tabIndex >= 0); assert(tabIndex <= maxTabIndex); return (_currentTabOffsets![tabIndex] + _currentTabOffsets![tabIndex + 1]) / 2.0; } Rect indicatorRect(Size tabBarSize, int tabIndex) { assert(_currentTabOffsets != null); assert(_currentTextDirection != null); assert(_currentTabOffsets!.isNotEmpty); assert(tabIndex >= 0); assert(tabIndex <= maxTabIndex); double tabLeft, tabRight; switch (_currentTextDirection!) { case TextDirection.rtl: tabLeft = _currentTabOffsets![tabIndex + 1]; tabRight = _currentTabOffsets![tabIndex]; break; case TextDirection.ltr: tabLeft = _currentTabOffsets![tabIndex]; tabRight = _currentTabOffsets![tabIndex + 1]; break; } final EdgeInsets insets = EdgeInsets.zero.resolve(_currentTextDirection); final Rect rect = Rect.fromLTWH(tabLeft, 0.0, tabRight - tabLeft, tabBarSize.height); if (!(rect.size >= insets.collapsedSize)) { throw FlutterError( 'indicatorPadding insets should be less than Tab Size\n' 'Rect Size : ${rect.size}, Insets: ${insets.toString()}', ); } return insets.deflateRect(rect); } @override void paint(Canvas canvas, Size size) { _needsPaint = false; _painter ??= indicator.createBoxPainter(markNeedsPaint); final double index = controller.index.toDouble(); final double value = controller.animation!.value; final bool ltr = index > value; final int from = (ltr ? value.floor() : value.ceil()).clamp(0, maxTabIndex).toInt(); final int to = (ltr ? from + 1 : from - 1).clamp(0, maxTabIndex).toInt(); final Rect fromRect = indicatorRect(size, from); final Rect toRect = indicatorRect(size, to); _currentRect = Rect.lerp(fromRect, toRect, (value - from).abs()); assert(_currentRect != null); final ImageConfiguration configuration = ImageConfiguration( size: _currentRect!.size, textDirection: _currentTextDirection, ); _painter!.paint(canvas, _currentRect!.topLeft, configuration); } @override bool shouldRepaint(_IndicatorPainter old) { return _needsPaint || controller != old.controller || indicator != old.indicator || tabKeys.length != old.tabKeys.length || (!listEquals(_currentTabOffsets, old._currentTabOffsets)) || _currentTextDirection != old._currentTextDirection; } } class _ChangeAnimation extends Animation<double> with AnimationWithParentMixin<double> { _ChangeAnimation(this.controller); final TabController controller; @override Animation<double> get parent => controller.animation!; @override void removeStatusListener(AnimationStatusListener listener) { if (controller.animation != null) super.removeStatusListener(listener); } @override void removeListener(VoidCallback listener) { if (controller.animation != null) super.removeListener(listener); } @override double get value => _indexChangeProgress(controller); } class _DragAnimation extends Animation<double> with AnimationWithParentMixin<double> { _DragAnimation(this.controller, this.index); final TabController controller; final int index; @override Animation<double> get parent => controller.animation!; @override void removeStatusListener(AnimationStatusListener listener) { if (controller.animation != null) super.removeStatusListener(listener); } @override void removeListener(VoidCallback listener) { if (controller.animation != null) super.removeListener(listener); } @override double get value { assert(!controller.indexIsChanging); final double controllerMaxValue = (controller.length - 1).toDouble(); final double controllerValue = controller.animation!.value.clamp(0.0, controllerMaxValue); return (controllerValue - index.toDouble()).abs().clamp(0.0, 1.0); } } // This class, and TabBarScrollController, only exist to handle the case // where a scrollable TabBar has a non-zero initialIndex. In that case we can // only compute the scroll position's initial scroll offset (the "correct" // pixels value) after the TabBar viewport width and scroll limits are known. class _TabBarScrollPosition extends ScrollPositionWithSingleContext { _TabBarScrollPosition({ required ScrollPhysics physics, required ScrollContext context, required ScrollPosition? oldPosition, required this.tabBar, }) : super( physics: physics, context: context, initialPixels: null, oldPosition: oldPosition, ); final _CustomTabBarState tabBar; bool? _initialViewportDimensionWasZero; @override bool applyContentDimensions(double minScrollExtent, double maxScrollExtent) { bool result = true; if (_initialViewportDimensionWasZero != true) { // If the viewport never had a non-zero dimension, we just want to jump // to the initial scroll position to avoid strange scrolling effects in // release mode: In release mode, the viewport temporarily may have a // dimension of zero before the actual dimension is calculated. In that // scenario, setting the actual dimension would cause a strange scroll // effect without this guard because the super call below would starts a // ballistic scroll activity. _initialViewportDimensionWasZero = viewportDimension != 0.0; correctPixels(tabBar._initialScrollOffset( viewportDimension, minScrollExtent, maxScrollExtent)); result = false; } return super.applyContentDimensions(minScrollExtent, maxScrollExtent) && result; } } // This class, and TabBarScrollPosition, only exist to handle the case // where a scrollable TabBar has a non-zero initialIndex. class _TabBarScrollController extends ScrollController { _TabBarScrollController(this.tabBar); final _CustomTabBarState tabBar; @override ScrollPosition createScrollPosition(ScrollPhysics physics, ScrollContext context, ScrollPosition? oldPosition) { return _TabBarScrollPosition( physics: physics, context: context, oldPosition: oldPosition, tabBar: tabBar, ); } } class CustomTabBar extends StatefulWidget implements PreferredSizeWidget { /// Creates a material design tab bar. /// /// The [tabs] argument must not be null and its length must match the [controller]'s /// [TabController.length]. /// /// If a [TabController] is not provided, then there must be a /// [DefaultTabController] ancestor. /// /// The [indicatorWeight] parameter defaults to 2, and must not be null. /// /// The [indicatorPadding] parameter defaults to [EdgeInsets.zero], and must not be null. /// /// If [indicator] is not null or provided from [TabBarTheme], /// then [indicatorWeight], [indicatorPadding], and [indicatorColor] are ignored. const CustomTabBar({ Key? key, required this.tabs, this.controller, this.isScrollable = false, this.indicator, this.labelColor, this.labelStyle, this.labelPadding, this.unselectedLabelColor, this.unselectedLabelStyle, this.dragStartBehavior = DragStartBehavior.start, this.overlayColor, this.mouseCursor, this.enableFeedback, this.onTap, this.physics, }) : super(key: key); /// Typically a list of two or more [Tab] widgets. /// /// The length of this list must match the [controller]'s [TabController.length] /// and the length of the [TabBarView.children] list. final List<Widget> tabs; /// This widget's selection and animation state. /// /// If [TabController] is not provided, then the value of [DefaultTabController.of] /// will be used. final TabController? controller; /// Whether this tab bar can be scrolled horizontally. /// /// If [isScrollable] is true, then each tab is as wide as needed for its label /// and the entire [TabBar] is scrollable. Otherwise each tab gets an equal /// share of the available space. final bool isScrollable; /// The color of the line that appears below the selected tab. /// /// If this parameter is null, then the value of the Theme's indicatorColor /// property is used. /// /// If [indicator] is specified or provided from [TabBarTheme], /// this property is ignored. // final Color? indicatorColor; /// The thickness of the line that appears below the selected tab. /// /// The value of this parameter must be greater than zero and its default /// value is 2.0. /// /// If [indicator] is specified or provided from [TabBarTheme], /// this property is ignored. // final double indicatorWeight; /// Padding for indicator. /// This property will now no longer be ignored even if indicator is declared /// or provided by [TabBarTheme] /// /// For [isScrollable] tab bars, specifying [kTabLabelPadding] will align /// the indicator with the tab's text for [Tab] widgets and all but the /// shortest [Tab.text] values. /// /// The default value of [indicatorPadding] is [EdgeInsets.zero]. // final EdgeInsetsGeometry indicatorPadding; /// Defines the appearance of the selected tab indicator. /// /// If [indicator] is specified or provided from [TabBarTheme], /// the [indicatorColor], and [indicatorWeight] properties are ignored. /// /// The default, underline-style, selected tab indicator can be defined with /// [UnderlineTabIndicator]. /// /// The indicator's size is based on the tab's bounds. If [indicatorSize] /// is [TabBarIndicatorSize.tab] the tab's bounds are as wide as the space /// occupied by the tab in the tab bar. If [indicatorSize] is /// [TabBarIndicatorSize.label], then the tab's bounds are only as wide as /// the tab widget itself. final BoxDecoration? indicator; /// Whether this tab bar should automatically adjust the [indicatorColor]. /// /// If [automaticIndicatorColorAdjustment] is true, /// then the [indicatorColor] will be automatically adjusted to [Colors.white] /// when the [indicatorColor] is same as [Material.color] of the [Material] parent widget. // final bool automaticIndicatorColorAdjustment; /// Defines how the selected tab indicator's size is computed. /// /// The size of the selected tab indicator is defined relative to the /// tab's overall bounds if [indicatorSize] is [TabBarIndicatorSize.tab] /// (the default) or relative to the bounds of the tab's widget if /// [indicatorSize] is [TabBarIndicatorSize.label]. /// /// The selected tab's location appearance can be refined further with /// the [indicatorColor], [indicatorWeight], [indicatorPadding], and /// [indicator] properties. // final TabBarIndicatorSize? indicatorSize; /// The color of selected tab labels. /// /// Unselected tab labels are rendered with the same color rendered at 70% /// opacity unless [unselectedLabelColor] is non-null. /// /// If this parameter is null, then the color of the [ThemeData.primaryTextTheme]'s /// bodyText1 text color is used. final Color? labelColor; /// The color of unselected tab labels. /// /// If this property is null, unselected tab labels are rendered with the /// [labelColor] with 70% opacity. final Color? unselectedLabelColor; /// The text style of the selected tab labels. /// /// If [unselectedLabelStyle] is null, then this text style will be used for /// both selected and unselected label styles. /// /// If this property is null, then the text style of the /// [ThemeData.primaryTextTheme]'s bodyText1 definition is used. final TextStyle? labelStyle; /// The padding added to each of the tab labels. /// /// If this property is null, then kTabLabelPadding is used. final EdgeInsetsGeometry? labelPadding; /// The text style of the unselected tab labels. /// /// If this property is null, then the [labelStyle] value is used. If [labelStyle] /// is null, then the text style of the [ThemeData.primaryTextTheme]'s /// bodyText1 definition is used. final TextStyle? unselectedLabelStyle; /// Defines the ink response focus, hover, and splash colors. /// /// If non-null, it is resolved against one of [MaterialState.focused], /// [MaterialState.hovered], and [MaterialState.pressed]. /// /// [MaterialState.pressed] triggers a ripple (an ink splash), per /// the current Material Design spec. The [overlayColor] doesn't map /// a state to [InkResponse.highlightColor] because a separate highlight /// is not used by the current design guidelines. See /// https://material.io/design/interaction/states.html#pressed /// /// If the overlay color is null or resolves to null, then the default values /// for [InkResponse.focusColor], [InkResponse.hoverColor], [InkResponse.splashColor] /// will be used instead. final MaterialStateProperty<Color?>? overlayColor; /// {@macro flutter.widgets.scrollable.dragStartBehavior} final DragStartBehavior dragStartBehavior; /// The cursor for a mouse pointer when it enters or is hovering over the /// individual tab widgets. /// /// If this property is null, [SystemMouseCursors.click] will be used. final MouseCursor? mouseCursor; /// Whether detected gestures should provide acoustic and/or haptic feedback. /// /// For example, on Android a tap will produce a clicking sound and a long-press /// will produce a short vibration, when feedback is enabled. /// /// Defaults to true. final bool? enableFeedback; /// An optional callback that's called when the [TabBar] is tapped. /// /// The callback is applied to the index of the tab where the tap occurred. /// /// This callback has no effect on the default handling of taps. It's for /// applications that want to do a little extra work when a tab is tapped, /// even if the tap doesn't change the TabController's index. TabBar [onTap] /// callbacks should not make changes to the TabController since that would /// interfere with the default tap handler. final ValueChanged<int>? onTap; /// How the [TabBar]'s scroll view should respond to user input. /// /// For example, determines how the scroll view continues to animate after the /// user stops dragging the scroll view. /// /// Defaults to matching platform conventions. final ScrollPhysics? physics; /// A size whose height depends on if the tabs have both icons and text. /// /// [AppBar] uses this size to compute its own preferred size. @override Size get preferredSize { for (final Widget item in tabs) { if (item is Tab) { final Tab tab = item; if ((tab.text != null || tab.child != null) && tab.icon != null) return Size.fromHeight(_kTextAndIconTabHeight); } } return Size.fromHeight(_kTabHeight); } @override _CustomTabBarState createState() => _CustomTabBarState(); } class _CustomTabBarState extends State<CustomTabBar> { ScrollController? _scrollController; TabController? _controller; _IndicatorPainter? _indicatorPainter; int? _currentIndex; late double _tabStripWidth; late List<GlobalKey> _tabKeys; @override void initState() { super.initState(); // If indicatorSize is TabIndicatorSize.label, _tabKeys[i] is used to find // the width of tab widget i. See _IndicatorPainter.indicatorRect(). _tabKeys = widget.tabs.map((Widget tab) => GlobalKey()).toList(); } Decoration get _indicator { if (widget.indicator != null) return widget.indicator!; final TabBarTheme tabBarTheme = TabBarTheme.of(context); if (tabBarTheme.indicator != null) return tabBarTheme.indicator!; throw StateError('TabBar indicator is null'); } // If the TabBar is rebuilt with a new tab controller, the caller should // dispose the old one. In that case the old controller's animation will be // null and should not be accessed. bool get _controllerIsValid => _controller?.animation != null; void _updateTabController() { final TabController? newController = widget.controller ?? DefaultTabController.of(context); assert(() { if (newController == null) { throw FlutterError( 'No TabController for ${widget.runtimeType}.\n' 'When creating a ${widget.runtimeType}, you must either provide an explicit ' 'TabController using the "controller" property, or you must ensure that there ' 'is a DefaultTabController above the ${widget.runtimeType}.\n' 'In this case, there was neither an explicit controller nor a default controller.', ); } return true; }()); if (newController == _controller) return; if (_controllerIsValid) { _controller!.animation!.removeListener(_handleTabControllerAnimationTick); _controller!.removeListener(_handleTabControllerTick); } _controller = newController; if (_controller != null) { _controller!.animation!.addListener(_handleTabControllerAnimationTick); _controller!.addListener(_handleTabControllerTick); _currentIndex = _controller!.index; } } void _initIndicatorPainter() { _indicatorPainter = !_controllerIsValid ? null : _IndicatorPainter( controller: _controller!, indicator: _indicator, tabKeys: _tabKeys, old: _indicatorPainter, ); } @override void didChangeDependencies() { super.didChangeDependencies(); assert(debugCheckHasMaterial(context)); _updateTabController(); _initIndicatorPainter(); } @override void didUpdateWidget(CustomTabBar oldWidget) { super.didUpdateWidget(oldWidget); if (widget.controller != oldWidget.controller) { _updateTabController(); _initIndicatorPainter(); } else if (widget.indicator != oldWidget.indicator) { _initIndicatorPainter(); } if (widget.tabs.length > oldWidget.tabs.length) { final int delta = widget.tabs.length - oldWidget.tabs.length; _tabKeys.addAll(List<GlobalKey>.generate(delta, (int n) => GlobalKey())); } else if (widget.tabs.length < oldWidget.tabs.length) { _tabKeys.removeRange(widget.tabs.length, oldWidget.tabs.length); } } @override void dispose() { _indicatorPainter!.dispose(); if (_controllerIsValid) { _controller!.animation!.removeListener(_handleTabControllerAnimationTick); _controller!.removeListener(_handleTabControllerTick); } _controller = null; // We don't own the _controller Animation, so it's not disposed here. super.dispose(); } int get maxTabIndex => _indicatorPainter!.maxTabIndex; double _tabScrollOffset( int index, double viewportWidth, double minExtent, double maxExtent) { if (!widget.isScrollable) return 0.0; double tabCenter = _indicatorPainter!.centerOf(index); switch (Directionality.of(context)) { case TextDirection.rtl: tabCenter = _tabStripWidth - tabCenter; break; case TextDirection.ltr: break; } return (tabCenter - viewportWidth / 2.0).clamp(minExtent, maxExtent); } double _tabCenteredScrollOffset(int index) { final ScrollPosition position = _scrollController!.position; return _tabScrollOffset(index, position.viewportDimension, position.minScrollExtent, position.maxScrollExtent); } double _initialScrollOffset( double viewportWidth, double minExtent, double maxExtent) { return _tabScrollOffset( _currentIndex!, viewportWidth, minExtent, maxExtent); } void _scrollToCurrentIndex() { final double offset = _tabCenteredScrollOffset(_currentIndex!); _scrollController! .animateTo(offset, duration: kTabScrollDuration, curve: Curves.ease); } void _scrollToControllerValue() { final double? leadingPosition = _currentIndex! > 0 ? _tabCenteredScrollOffset(_currentIndex! - 1) : null; final double middlePosition = _tabCenteredScrollOffset(_currentIndex!); final double? trailingPosition = _currentIndex! < maxTabIndex ? _tabCenteredScrollOffset(_currentIndex! + 1) : null; final double index = _controller!.index.toDouble(); final double value = _controller!.animation!.value; final double offset; if (value == index - 1.0) offset = leadingPosition ?? middlePosition; else if (value == index + 1.0) offset = trailingPosition ?? middlePosition; else if (value == index) offset = middlePosition; else if (value < index) offset = leadingPosition == null ? middlePosition : lerpDouble(middlePosition, leadingPosition, index - value)!; else offset = trailingPosition == null ? middlePosition : lerpDouble(middlePosition, trailingPosition, value - index)!; _scrollController!.jumpTo(offset); } void _handleTabControllerAnimationTick() { assert(mounted); if (!_controller!.indexIsChanging && widget.isScrollable) { // Sync the CustomTabBar's scroll position with the TabBarView's PageView. _currentIndex = _controller!.index; _scrollToControllerValue(); } } void _handleTabControllerTick() { if (_controller!.index != _currentIndex) { _currentIndex = _controller!.index; if (widget.isScrollable) _scrollToCurrentIndex(); } setState(() { // Rebuild the tabs after a (potentially animated) index change // has completed. }); } // Called each time layout completes. void _saveTabOffsets( List<double> tabOffsets, TextDirection textDirection, double width) { _tabStripWidth = width; _indicatorPainter?.saveTabOffsets(tabOffsets, textDirection); } void _handleTap(int index) { assert(index >= 0 && index < widget.tabs.length); _controller!.animateTo(index); widget.onTap?.call(index); } Widget _buildStyledTab( Widget child, bool selected, Animation<double> animation) { return _TabStyle( animation: animation, selected: selected, labelColor: widget.labelColor, unselectedLabelColor: widget.unselectedLabelColor, labelStyle: widget.labelStyle, unselectedLabelStyle: widget.unselectedLabelStyle, child: child, ); } @override Widget build(BuildContext context) { assert(debugCheckHasMaterialLocalizations(context)); assert(() { if (_controller!.length != widget.tabs.length) { throw FlutterError( "Controller's length property (${_controller!.length}) does not match the " "number of tabs (${widget.tabs.length}) present in CustomTabBar's tabs property.", ); } return true; }()); final MaterialLocalizations localizations = MaterialLocalizations.of(context); if (_controller!.length == 0) { return Container( height: _kTabHeight, ); } final TabBarTheme tabBarTheme = TabBarTheme.of(context); final List<Widget> wrappedTabs = <Widget>[ for (int i = 0; i < widget.tabs.length; i += 1) Center( heightFactor: 1.0, child: Padding( padding: widget.labelPadding ?? tabBarTheme.labelPadding ?? kTabLabelPadding, child: KeyedSubtree( key: _tabKeys[i], child: widget.tabs[i], ), ), ), ]; // If the controller was provided by DefaultTabController and we're part // of a Hero (typically the AppBar), then we will not be able to find the // controller during a Hero transition. See https://github.com/flutter/flutter/issues/213. if (_controller != null) { final int previousIndex = _controller!.previousIndex; if (_controller!.indexIsChanging) { // The user tapped on a tab, the tab controller's animation is running. assert(_currentIndex != previousIndex); final Animation<double> animation = _ChangeAnimation(_controller!); wrappedTabs[_currentIndex!] = _buildStyledTab(wrappedTabs[_currentIndex!], true, animation); wrappedTabs[previousIndex] = _buildStyledTab(wrappedTabs[previousIndex], false, animation); } else { // The user is dragging the TabBarView's PageView left or right. final int tabIndex = _currentIndex!; final Animation<double> centerAnimation = _DragAnimation(_controller!, tabIndex); wrappedTabs[tabIndex] = _buildStyledTab(wrappedTabs[tabIndex], true, centerAnimation); if (_currentIndex! > 0) { final int tabIndex = _currentIndex! - 1; final Animation<double> previousAnimation = ReverseAnimation(_DragAnimation(_controller!, tabIndex)); wrappedTabs[tabIndex] = _buildStyledTab(wrappedTabs[tabIndex], false, previousAnimation); } if (_currentIndex! < widget.tabs.length - 1) { final int tabIndex = _currentIndex! + 1; final Animation<double> nextAnimation = ReverseAnimation(_DragAnimation(_controller!, tabIndex)); wrappedTabs[tabIndex] = _buildStyledTab(wrappedTabs[tabIndex], false, nextAnimation); } } } // Add the tap handler to each tab. If the tab bar is not scrollable, // then give all of the tabs equal flexibility so that they each occupy // the same share of the tab bar's overall width. final int tabCount = widget.tabs.length; for (int index = 0; index < tabCount; index += 1) { wrappedTabs[index] = InkWell( mouseCursor: widget.mouseCursor ?? SystemMouseCursors.click, onTap: () { _handleTap(index); }, enableFeedback: widget.enableFeedback ?? true, overlayColor: widget.overlayColor, borderRadius: widget.indicator?.borderRadius as BorderRadius?, child: Stack( children: <Widget>[ wrappedTabs[index], Semantics( selected: index == _currentIndex, label: localizations.tabLabel( tabIndex: index + 1, tabCount: tabCount), ), ], ), ); if (!widget.isScrollable) wrappedTabs[index] = Expanded(child: wrappedTabs[index]); } Widget tabBar = CustomPaint( painter: _indicatorPainter, child: _TabStyle( animation: kAlwaysDismissedAnimation, selected: false, labelColor: widget.labelColor, unselectedLabelColor: widget.unselectedLabelColor, labelStyle: widget.labelStyle, unselectedLabelStyle: widget.unselectedLabelStyle, child: _TabLabelBar( onPerformLayout: _saveTabOffsets, children: wrappedTabs, ), ), ); if (widget.isScrollable) { _scrollController ??= _TabBarScrollController(this); tabBar = SingleChildScrollView( dragStartBehavior: widget.dragStartBehavior, scrollDirection: Axis.horizontal, controller: _scrollController, physics: widget.physics, child: tabBar, ); if (widget.indicator?.borderRadius != null) tabBar = ClipRRect( borderRadius: widget.indicator?.borderRadius as BorderRadius?, child: tabBar, ); } return tabBar; } } class _SizeReportingWidget extends StatefulWidget { const _SizeReportingWidget({ Key? key, required this.child, required this.onSizeChange, }) : super(key: key); final Widget child; final ValueChanged<Size> onSizeChange; @override _SizeReportingWidgetState createState() => _SizeReportingWidgetState(); } class _SizeReportingWidgetState extends State<_SizeReportingWidget> { Size? _oldSize; @override Widget build(BuildContext context) { WidgetsBinding.instance?.addPostFrameCallback((_) => _notifySize()); return widget.child; } void _notifySize() { if (!this.mounted) return; final size = context.size; if (_oldSize != size) { _oldSize = size; widget.onSizeChange(size!); } } } /// A page view that displays the widget which corresponds to the currently /// selected tab. /// /// This widget is typically used in conjunction with a [TabBar]. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=POtoEH-5l40} /// /// If a [TabController] is not provided, then there must be a [DefaultTabController] /// ancestor. /// /// The tab controller's [TabController.length] must equal the length of the /// [children] list and the length of the [TabBar.tabs] list. /// /// To see a sample implementation, visit the [TabController] documentation. /// /// [stackoverflow - Flutter: adjust height of PageView/Horizontal ListView based on current child](https://stackoverflow.com/a/65332810) /// [Limbou/expandable_page_view/lib/expandable_page_view.dart](https://github.com/Limbou/expandable_page_view/blob/main/lib/expandable_page_view.dart) class FlexibleTabBarView extends StatefulWidget { /// Creates a page view with one child per tab. /// /// The length of [children] must be the same as the [controller]'s length. const FlexibleTabBarView({ Key? key, required this.children, this.controller, this.physics, this.dragStartBehavior = DragStartBehavior.start, this.duration = const Duration(milliseconds: 230), this.curve = Curves.easeInOutCubic, }) : super(key: key); /// This widget's selection and animation state. /// /// If [TabController] is not provided, then the value of [DefaultTabController.of] /// will be used. final TabController? controller; /// One widget per tab. /// /// Its length must match the length of the [TabBar.tabs] /// list, as well as the [controller]'s [TabController.length]. final List<Widget> children; /// How the page view should respond to user input. /// /// For example, determines how the page view continues to animate after the /// user stops dragging the page view. /// /// The physics are modified to snap to page boundaries using /// [PageScrollPhysics] prior to being used. /// /// Defaults to matching platform conventions. final ScrollPhysics? physics; /// {@macro flutter.widgets.scrollable.dragStartBehavior} final DragStartBehavior dragStartBehavior; final Duration duration; final Curve curve; @override _FlexibleTabBarViewState createState() => _FlexibleTabBarViewState(); } class _FlexibleTabBarViewState extends State<FlexibleTabBarView> { TabController? _controller; late PageController _pageController; late List<Widget> _children; late List<Widget> _childrenWithKey; int? _currentIndex; int? _previousIndex; late final List<double> _heights; int _warpUnderwayCount = 0; // If the FlexibleTabBarView is rebuilt with a new tab controller, the caller should // dispose the old one. In that case the old controller's animation will be // null and should not be accessed. bool get _controllerIsValid => _controller?.animation != null; double get _previousHeight => _heights[_previousIndex ?? 0]; double get _currentHeight => _heights[_currentIndex ?? 0]; List<Widget> get _sizeReportingChildren => _childrenWithKey .asMap() .map( (index, child) => MapEntry( index, OverflowBox( //needed, so that parent won't impose its constraints on the children, thus skewing the measurement results. minHeight: 0, maxHeight: double.infinity, alignment: Alignment.topCenter, child: _SizeReportingWidget( onSizeChange: (size) => setState(() => _heights[index] = size.height), child: Align(child: child), ), ), ), ) .values .toList(); void _updateTabController() { final TabController? newController = widget.controller ?? DefaultTabController.of(context); assert(() { if (newController == null) { throw FlutterError( 'No TabController for ${widget.runtimeType}.\n' 'When creating a ${widget.runtimeType}, you must either provide an explicit ' 'TabController using the "controller" property, or you must ensure that there ' 'is a DefaultTabController above the ${widget.runtimeType}.\n' 'In this case, there was neither an explicit controller nor a default controller.', ); } return true; }()); if (newController == _controller) return; if (_controllerIsValid) _controller!.animation!.removeListener(_handleTabControllerAnimationTick); _controller = newController; if (_controller != null) _controller!.animation!.addListener(_handleTabControllerAnimationTick); } void _updatePage() { final newPage = _pageController.page!.round(); if (_currentIndex != newPage) { setState(() { _previousIndex = _currentIndex; _currentIndex = newPage; }); } } @override void initState() { super.initState(); _heights = List.generate(widget.children.length, (_) => 0.0); _updateChildren(); } @override void didChangeDependencies() { super.didChangeDependencies(); _updateTabController(); _currentIndex = _controller?.index; _previousIndex = _controller?.previousIndex; _pageController = PageController(initialPage: _currentIndex ?? 0); _pageController.addListener(_updatePage); } @override void didUpdateWidget(FlexibleTabBarView oldWidget) { super.didUpdateWidget(oldWidget); if (widget.controller != oldWidget.controller) _updateTabController(); if (widget.children != oldWidget.children && _warpUnderwayCount == 0) _updateChildren(); } @override void dispose() { _pageController.removeListener(_updatePage); _pageController.dispose(); if (_controllerIsValid) _controller!.animation!.removeListener(_handleTabControllerAnimationTick); _controller = null; // We don't own the _controller Animation, so it's not disposed here. super.dispose(); } void _updateChildren() { _children = widget.children; _childrenWithKey = KeyedSubtree.ensureUniqueKeysForList(widget.children); } void _handleTabControllerAnimationTick() { if (_warpUnderwayCount > 0 || !_controller!.indexIsChanging) return; // This widget is driving the controller's animation. if (_controller!.index != _currentIndex) { _previousIndex = _currentIndex; _currentIndex = _controller!.index; _warpToCurrentIndex(); } } Future<void> _warpToCurrentIndex() async { if (!mounted) return Future<void>.value(); if (_pageController.page == _currentIndex!.toDouble()) return Future<void>.value(); final int previousIndex = _controller!.previousIndex; if ((_currentIndex! - previousIndex).abs() == 1) { _warpUnderwayCount += 1; await _pageController.animateToPage(_currentIndex!, duration: kTabScrollDuration, curve: Curves.ease); _warpUnderwayCount -= 1; return Future<void>.value(); } assert((_currentIndex! - previousIndex).abs() > 1); final int initialPage = _currentIndex! > previousIndex ? _currentIndex! - 1 : _currentIndex! + 1; final List<Widget> originalChildren = _childrenWithKey; setState(() { _warpUnderwayCount += 1; _childrenWithKey = List<Widget>.from(_childrenWithKey, growable: false); final Widget temp = _childrenWithKey[initialPage]; _childrenWithKey[initialPage] = _childrenWithKey[previousIndex]; _childrenWithKey[previousIndex] = temp; }); _pageController.jumpToPage(initialPage); await _pageController.animateToPage(_currentIndex!, duration: kTabScrollDuration, curve: Curves.ease); if (!mounted) return Future<void>.value(); setState(() { _warpUnderwayCount -= 1; if (widget.children != _children) { _updateChildren(); } else { _childrenWithKey = originalChildren; } }); } // Called when the PageView scrolls bool _handleScrollNotification(ScrollNotification notification) { if (_warpUnderwayCount > 0) return false; if (notification.depth != 0) return false; _warpUnderwayCount += 1; if (notification is ScrollUpdateNotification && !_controller!.indexIsChanging) { if ((_pageController.page! - _controller!.index).abs() > 1.0) { _previousIndex = _controller!.index; _controller!.index = _pageController.page!.floor(); _currentIndex = _controller!.index; // print("\nScrollUpdateNotification"); // print("_previousIndex: $_previousIndex"); // print("_currentIndex: $_currentIndex"); } _controller!.offset = (_pageController.page! - _controller!.index).clamp(-1.0, 1.0); } else if (notification is ScrollEndNotification) { _previousIndex = _controller!.index; _controller!.index = _pageController.page!.round(); _currentIndex = _controller!.index; // print("\nScrollEndNotification"); // print("_previousIndex: $_previousIndex"); // print("_currentIndex: $_currentIndex"); if (!_controller!.indexIsChanging) _controller!.offset = (_pageController.page! - _controller!.index).clamp(-1.0, 1.0); } _warpUnderwayCount -= 1; return false; } @override Widget build(BuildContext context) { assert(() { if (_controller!.length != widget.children.length) { throw FlutterError( "Controller's length property (${_controller!.length}) does not match the " "number of tabs (${widget.children.length}) present in TabBar's tabs property.", ); } return true; }()); return TweenAnimationBuilder<double>( curve: widget.curve, duration: widget.duration, tween: Tween<double>(begin: _previousHeight, end: _currentHeight), builder: (context, value, child) => SizedBox(height: value, child: child), child: NotificationListener<ScrollNotification>( onNotification: _handleScrollNotification, child: PageView( dragStartBehavior: widget.dragStartBehavior, controller: _pageController, physics: widget.physics == null ? const PageScrollPhysics().applyTo(const ClampingScrollPhysics()) : const PageScrollPhysics().applyTo(widget.physics), children: _sizeReportingChildren, ), ), ); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common/outline_text_form_field.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_mockup_bloc/common/theme/app_form_field.dart'; import 'package:flutter_mockup_bloc/resource/app_text_styles.dart'; const int _defaultMinLinesOnMultiline = 6; class OutlineTextFormField extends FormField<String> { /// Creates a [FormField] that contains a [TextField]. /// /// When a [controller] is specified, [initialValue] must be null (the /// default). If [controller] is null, then a [TextEditingController] /// will be constructed automatically and its `text` will be initialized /// to [initialValue] or the empty string. /// /// For documentation about the various parameters, see the [TextField] class /// and [new TextField], the constructor. OutlineTextFormField({ Key? key, required this.data, bool updateStateIfInternalDataChanged = false, this.controller, String? initialValue, FocusNode? focusNode, InputDecoration? decoration, String? hintText, TextInputType? keyboardType, TextCapitalization textCapitalization = TextCapitalization.none, TextInputAction? textInputAction, TextStyle? style, StrutStyle? strutStyle, TextDirection? textDirection, TextAlign textAlign = TextAlign.start, TextAlignVertical? textAlignVertical, bool autofocus = false, bool readOnly = false, ToolbarOptions? toolbarOptions, bool? showCursor, String obscuringCharacter = '•', bool obscureText = false, bool autocorrect = true, bool autoTrimWhenTyping = false, SmartDashesType? smartDashesType, SmartQuotesType? smartQuotesType, bool enableSuggestions = true, MaxLengthEnforcement? maxLengthEnforcement, int maxLines = 1, int? minLines, // when multiline = true, minLines = 6 bool expands = false, int? maxLength, bool multiline = false, ValueChanged<String>? onChanged, GestureTapCallback? onTap, VoidCallback? onEditingComplete, ValueChanged<String>? onFieldSubmitted, FormFieldSetter<String>? onSaved, FormFieldValidator<String>? validator, List<TextInputFormatter>? inputFormatters, bool? enabled, double cursorWidth = 2.0, double? cursorHeight, Radius? cursorRadius, Color? cursorColor, Brightness? keyboardAppearance, EdgeInsets scrollPadding = const EdgeInsets.all(20.0), bool enableInteractiveSelection = true, TextSelectionControls? selectionControls, InputCounterWidgetBuilder? buildCounter, ScrollPhysics? scrollPhysics, Iterable<String>? autofillHints, AutovalidateMode? autovalidateMode, ScrollController? scrollController, }) : assert(initialValue == null || controller == null), assert(obscuringCharacter.length == 1), assert( maxLengthEnforcement == null, 'maxLengthEnforced is deprecated, use only maxLengthEnforcement', ), assert( (minLines == null) || (maxLines >= minLines), "minLines can't be greater than maxLines", ), assert( !expands || minLines == null, 'minLines and maxLines must be null when expands is true.', ), assert(!obscureText || maxLines == 1, 'Obscured fields cannot be multiline.'), assert(maxLength == null || maxLength > 0), super( key: key, initialValue: controller != null ? controller.text : initialValue, onSaved: onSaved, validator: validator, enabled: enabled ?? decoration?.enabled ?? true, autovalidateMode: autovalidateMode ?? (validator != null ? AutovalidateMode.onUserInteraction : null), builder: (FormFieldState<String> field) { if (updateStateIfInternalDataChanged && field.value != data) { WidgetsBinding.instance?.addPostFrameCallback((timeStamp) { field.didChange(data); }); } final _OutlineTextFormFieldState state = field as _OutlineTextFormFieldState; final InputDecoration effectiveDecoration = (decoration ?? (multiline ? AppFormField.multilineShadowInputDecoration : AppFormField.shadowInputDecoration)) .copyWith(hintText: hintText); // .applyDefaults(Theme.of(field.context).inputDecorationTheme); void onChangedHandler(String value) { field.didChange(autoTrimWhenTyping ? value.trim() : value); if (onChanged != null) { onChanged(value); } } return TextField( controller: state._effectiveController, focusNode: focusNode, decoration: effectiveDecoration.copyWith(errorText: field.errorText), keyboardType: keyboardType, textInputAction: textInputAction, style: style ?? AppTextStyles.input, strutStyle: strutStyle, textAlign: textAlign, textAlignVertical: textAlignVertical, textDirection: textDirection, textCapitalization: textCapitalization, autofocus: autofocus, toolbarOptions: toolbarOptions, readOnly: readOnly, showCursor: showCursor, obscuringCharacter: obscuringCharacter, obscureText: obscureText, autocorrect: autocorrect, smartDashesType: smartDashesType ?? (obscureText ? SmartDashesType.disabled : SmartDashesType.enabled), smartQuotesType: smartQuotesType ?? (obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled), enableSuggestions: enableSuggestions, maxLengthEnforcement: maxLengthEnforcement, maxLines: multiline ? null : maxLines, minLines: minLines == null && multiline ? _defaultMinLinesOnMultiline : minLines, expands: expands, maxLength: maxLength, onChanged: onChangedHandler, onTap: onTap, onEditingComplete: onEditingComplete, onSubmitted: onFieldSubmitted, inputFormatters: inputFormatters, enabled: enabled ?? decoration?.enabled ?? true, cursorWidth: cursorWidth, cursorHeight: cursorHeight, cursorRadius: cursorRadius, cursorColor: cursorColor, scrollPadding: scrollPadding, scrollPhysics: scrollPhysics, keyboardAppearance: keyboardAppearance, enableInteractiveSelection: enableInteractiveSelection, selectionControls: selectionControls, buildCounter: buildCounter, autofillHints: autofillHints, scrollController: scrollController, ); }, ); /// Controls the text being edited. /// /// If null, this widget will create its own [TextEditingController] and /// initialize its [TextEditingController.text] with [initialValue]. final TextEditingController? controller; late String data; @override _OutlineTextFormFieldState createState() => _OutlineTextFormFieldState(); } class _OutlineTextFormFieldState extends FormFieldState<String> { TextEditingController? _controller; TextEditingController get _effectiveController => widget.controller ?? _controller!; late StreamSubscription<String> dataStreamSubscription; @override OutlineTextFormField get widget => super.widget as OutlineTextFormField; @override void initState() { super.initState(); if (widget.controller == null) { _controller = TextEditingController(text: widget.initialValue ?? widget.data); } setValue(widget.initialValue ?? widget.data); _effectiveController.addListener(_handleControllerChanged); dataStreamSubscription = Stream.value(widget.data).listen(_onData); } @override void didUpdateWidget(OutlineTextFormField oldWidget) { super.didUpdateWidget(oldWidget); if (widget.controller != oldWidget.controller) { oldWidget.controller?.removeListener(_handleControllerChanged); widget.controller?.addListener(_handleControllerChanged); if (oldWidget.controller != null && widget.controller == null) _controller = TextEditingController.fromValue(oldWidget.controller!.value); if (widget.controller != null) { setValue(widget.controller!.text); if (oldWidget.controller == null) _controller = null; } } } @override void dispose() { dataStreamSubscription.cancel(); _effectiveController.removeListener(_handleControllerChanged); super.dispose(); } @override void didChange(String? value) { super.didChange(value); if (_effectiveController.text != value) { _effectiveController.text = value ?? ''; _effectiveController.selection = TextSelection.collapsed(offset: value?.length ?? 0); } widget.data = _effectiveController.text; } @override void reset() { // setState will be called in the superclass, so even though state is being // manipulated, no setState call is needed here. _effectiveController.text = widget.initialValue ?? widget.data; super.reset(); } void _handleControllerChanged() { // Suppress changes that originated from within this class. // // In the case where a controller has been passed in to this widget, we // register this change listener. In these cases, we'll also receive change // notifications for changes originating from within this class -- for // example, the reset() method. In such cases, the FormField value will // already have been set. if (_effectiveController.text != value) didChange(_effectiveController.text); } void _onData(String value) { if (_effectiveController.text != value) _effectiveController.text = value; } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common/common_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/resource/app_colors.dart'; import 'package:flutter_mockup_bloc/resource/gaps.dart'; class CommonWidget { static const CircularProgressIndicator loadingCircle = CircularProgressIndicator( color: AppColors.primary, ); static const Center centerLoadingCircle = Center( child: CircularProgressIndicator( color: AppColors.primary, ), ); static const Padding sectionLoading = Padding( padding: EdgeInsets.only(top: 12), child: Center( child: loadingCircle, ), ); static const SizedBox screenBodyLoading = SizedBox.expand( child: Center( child: loadingCircle, ), ); static Widget getEmptySection(Text text, {double? verticalPadding = 30}) { final Widget current = Center(child: text); if (verticalPadding != null) return Padding( padding: EdgeInsets.symmetric(vertical: verticalPadding), child: current, ); return current; } static Padding getLoadingSection({ double verticalPadding = 60, double? bottomPadding, }) => Padding( padding: EdgeInsets.symmetric(vertical: verticalPadding) .copyWith(bottom: bottomPadding), child: Center(child: loadingCircle), ); static ListView getListViewBuilder({ EdgeInsetsGeometry? padding = const EdgeInsets.only(top: 40, bottom: 20), required List<Widget> children, }) => ListView.builder( padding: padding, itemCount: children.length, itemBuilder: (_, index) => children[index], ); static SingleChildScrollView getSingleChildScrollView({ EdgeInsetsGeometry? padding = const EdgeInsets.only(top: 40, bottom: 20), required List<Widget> children, CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.start, }) => SingleChildScrollView( padding: padding, child: Column( crossAxisAlignment: crossAxisAlignment, children: children, ), ); static Row getFormFieldPrefixIconPainter(CustomPaint icon) => Row( mainAxisSize: MainAxisSize.min, children: [ const SizedBox(width: 18), icon, ], ); static Row getFormFieldSuffixIconPainter(CustomPaint icon) => Row( mainAxisSize: MainAxisSize.min, children: [ icon, const SizedBox(width: 18), ], ); static Widget getRoundedImage( ImageProvider<Object> imageProvider, radius, [ BoxDecoration? imageDecoration, ]) => DecoratedBox( decoration: BoxDecoration( image: DecorationImage( image: imageProvider, fit: BoxFit.cover, ), borderRadius: imageDecoration?.shape == BoxShape.circle ? null : imageDecoration?.borderRadius ?? BorderRadius.all(Radius.circular((radius))), color: imageDecoration?.color, border: imageDecoration?.border, boxShadow: imageDecoration?.boxShadow, ).copyWith( shape: imageDecoration?.shape, ), ); /// Uniform width of all widgets in input list except SizedBox static List<Widget> uniformWidth(List<Widget> list) => list.map((e) => e is SizedBox ? e : Expanded(flex: 1, child: e)).toList(); static List<Widget> addPadding( List<Widget> list, EdgeInsetsGeometry padding) => list.length == 0 ? list : list.map((e) => Padding(padding: padding, child: e)).toList(); static List<Widget> addSizedBoxAsSeparator( SizedBox sizedBox, List<Widget> widgets) => widgets.length == 0 ? widgets : widgets.expand((element) => [element, sizedBox]).toList() ..removeLast(); static Size getResponsiveSizeBaseOnScreenWidth( BuildContext context, double delta) => Size( MediaQuery.of(context).size.width, (MediaQuery.of(context).size.width * delta).toDouble(), ); /// widthDelta = image's width / design screen's width /// /// heightDelta = image's height / image's width static Size getResponsiveSizeBaseOnWidth( BuildContext context, double widthDelta, double heightDelta) { final screenWidth = MediaQuery.of(context).size.width; final width = screenWidth * widthDelta; return Size( width, (width * heightDelta).toDouble(), ); } } extension WidgetListExtension<Widget> on List<Widget> { addHorizontalSpacing(double size) => this.length == 0 ? this : this .expand((element) => [ element, SizedBox(width: size), ]) .toList() ..removeLast(); addVerticalSpacing(double size) => this.length == 0 ? this : this .expand((element) => [ element, SizedBox(height: size), ]) .toList() ..removeLast(); addSizedBoxAsSeparator(SizedBox sizedBox) => this.length == 0 ? this : this.expand((element) => [element, sizedBox]).toList() ..removeLast(); // uniformWidth({ // BuildContext? context, // double? parentWidth, // double horizontalPadding = 16, // double spaceBetweenChildren = 20, // }) { // final double childrenWidth = // ((context != null ? MediaQuery.of(context).size.width : parentWidth!) / // 1.9) - // horizontalPadding - // spaceBetweenChildren; // return this // .map((e) => e is SizedBox // ? e // : SizedBox( // width: childrenWidth, // child: e, // )) // .toList(); // } // Error: The argument type 'Widget/*1*/' can't be assigned to the parameter type 'Widget/*2*/' // uniformWidth() => this // .map((e) => e is SizedBox // ? e // : Expanded( // flex: 1, // // ignore_for_file: argument_type_not_assignable // child: e, // )) // .toList(); } class SizedBoxExt { static const shrink = SizedBox.shrink(); static const w5 = SizedBox(width: 5); static const h10 = SizedBox(height: 10); static const w10 = SizedBox(width: 10); static const h12 = SizedBox(height: 12); static const w16 = SizedBox(width: 16); static const h15 = SizedBox(height: 15); static const h20 = SizedBox(height: 20); static const w20 = SizedBox(width: 20); static const h30 = SizedBox(height: 30); static const h40 = SizedBox(height: 40); static const h50 = SizedBox(height: 50); static const sliverH16 = SliverToBoxAdapter(child: SizedBox(height: 16)); static const sliverH20 = SliverToBoxAdapter(child: SizedBox(height: 20)); }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common/loading_button.dart
import 'package:flutter/material.dart'; class LoadingButton extends StatelessWidget { final String? title; Icon? icon; final bool? isLoading; final Function()? onSubmit; LoadingButton({Key? key, this.title, this.isLoading : false, this.onSubmit}) : super(key: key); @override Widget build(BuildContext context) { return ElevatedButton.icon( onPressed: isLoading! ? null : onSubmit!, style: ElevatedButton.styleFrom(padding: const EdgeInsets.all(16.0)), icon: isLoading! ? Container( width: 24, height: 24, padding: const EdgeInsets.all(2.0), child: const CircularProgressIndicator( color: Colors.white, strokeWidth: 3, ), ) : icon ?? SizedBox(), label: Text(title!), ); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common/load_image.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/utils/device/image_utils.dart'; class LoadImage extends StatelessWidget { const LoadImage(this.image, { Key? key, this.width, this.height, this.fit = BoxFit.cover, this.format = ImageFormat.png, this.holderImg = 'placeholder_image', this.cacheWidth, this.cacheHeight, }) : super(key: key); final String image; final double? width; final double? height; final BoxFit fit; final ImageFormat format; final String holderImg; final int? cacheWidth; final int? cacheHeight; @override Widget build(BuildContext context) { if (image.isEmpty || image.startsWith('http')) { final Widget holder = LoadAssetImage(holderImg, height: height, width: width, fit: fit); return CachedNetworkImage( imageUrl: image, placeholder: (_, __) => holder, errorWidget: (_, __, dynamic error) => holder, width: width, height: height, fit: fit, memCacheWidth: cacheWidth, memCacheHeight: cacheHeight, ); } else { return LoadAssetImage(image, height: height, width: width, fit: fit, format: format, cacheWidth: cacheWidth, cacheHeight: cacheHeight, ); } } } class LoadAssetImage extends StatelessWidget { const LoadAssetImage(this.image, { Key? key, this.width, this.height, this.cacheWidth, this.cacheHeight, this.fit, this.format = ImageFormat.png, this.color }): super(key: key); final String image; final double? width; final double? height; final int? cacheWidth; final int? cacheHeight; final BoxFit? fit; final ImageFormat format; final Color? color; @override Widget build(BuildContext context) { return Image.asset( ImageUtils.getImgPath(image, format: format), height: height, width: width, cacheWidth: cacheWidth, cacheHeight: cacheHeight, fit: fit, color: color, excludeFromSemantics: true, ); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common/custom_text_field.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class CustomTextField extends StatefulWidget { final TextEditingController? controller; final FocusNode? focusNode; final InputDecoration? decoration; final TextInputType? keyboardType; final TextInputAction? textInputAction; final TextCapitalization textCapitalization; final TextStyle? style; final StrutStyle? strutStyle; final TextAlign textAlign; final TextAlignVertical? textAlignVertical; final TextDirection? textDirection; final bool autofocus; final bool obscureText; final bool? autocorrect; final bool enableSuggestions; final int maxLines; final int? minLines; final bool expands; final bool readOnly; final ToolbarOptions? toolbarOptions; final bool? showCursor; final int? maxLength; final bool maxLengthEnforced; final ValueChanged<String>? onChanged; final VoidCallback? onEditingComplete; final ValueChanged<String>? onSubmitted; final List<TextInputFormatter>? inputFormatters; final bool? enabled; final double? cursorWidth; final Radius? cursorRadius; final Color? cursorColor; final Brightness? keyboardAppearance; final EdgeInsets? scrollPadding; final bool? enableInteractiveSelection; final DragStartBehavior? dragStartBehavior; final GestureTapCallback? onTap; final InputCounterWidgetBuilder? buildCounter; final ScrollPhysics? scrollPhysics; final ScrollController? scrollController; final FocusNode? nextNode; final Iterable<String>? autofillHints; final String? hintText; final VoidCallback? onCancel; /// Icon [Icons.visibility] at right of text field /// If true then [Icons.visibility] /// And if false then [Icons.visibility_off] /// Click icon to change show or hide password final bool showEyeIcon; /// Icon [Icons.cancel] at right of text field /// When text is not empty then icon will be shown /// And if text is empty then icon will be hide final bool showCancelIcon; const CustomTextField({ key, this.controller, this.focusNode, this.decoration, this.keyboardType, this.textInputAction, this.textCapitalization = TextCapitalization.none, this.style, this.strutStyle, this.textAlign = TextAlign.start, this.textAlignVertical, this.textDirection, this.readOnly = false, this.toolbarOptions, this.showCursor, this.autofocus = false, this.obscureText = false, this.autocorrect, this.enableSuggestions = true, this.maxLines = 1, this.minLines, this.expands = false, this.maxLength, this.maxLengthEnforced = true, this.onChanged, this.onEditingComplete, this.onSubmitted, this.inputFormatters, this.enabled, this.cursorWidth, this.cursorRadius, this.cursorColor, this.keyboardAppearance, this.scrollPadding, this.dragStartBehavior, this.enableInteractiveSelection, this.onTap, this.buildCounter, this.scrollController, this.scrollPhysics, this.nextNode, this.autofillHints, this.hintText, this.showCancelIcon = false, this.onCancel, this.showEyeIcon = false, }) : assert( !(showEyeIcon == showCancelIcon) || (!showEyeIcon || !showCancelIcon), 'only one of them', ), super(key: key); @override _CustomTextFieldState createState() => _CustomTextFieldState(); } class _CustomTextFieldState extends State<CustomTextField> with SingleTickerProviderStateMixin { final _defaultTextController = TextEditingController(); TextEditingController get controller => widget.controller ?? _defaultTextController; FocusNode? get focusNode => widget.focusNode; TextInputType? get keyboardType => widget.keyboardType; TextInputAction? get textInputAction => widget.textInputAction; TextCapitalization get textCapitalization => widget.textCapitalization; TextStyle? get style => widget.style; StrutStyle? get strutStyle => widget.strutStyle; TextAlign get textAlign => widget.textAlign; TextAlignVertical? get textAlignVertical => widget.textAlignVertical; TextDirection? get textDirection => widget.textDirection; bool get autofocus => widget.autofocus; bool get obscureText => widget.obscureText; bool? get autocorrect => widget.autocorrect; bool get enableSuggestions => widget.enableSuggestions; bool get expands => widget.expands; bool get readOnly => widget.readOnly; ToolbarOptions? get toolbarOptions => widget.toolbarOptions; bool? get showCursor => widget.showCursor; int? get maxLength => widget.maxLength; bool get maxLengthEnforced => widget.maxLengthEnforced; ValueChanged<String>? get onChanged => widget.onChanged; VoidCallback? get onEditingComplete => widget.onEditingComplete; ValueChanged<String>? get onSubmitted => widget.onSubmitted; List<TextInputFormatter>? get inputFormatters => widget.inputFormatters; bool? get enabled => widget.enabled; double? get cursorWidth => widget.cursorWidth; Radius? get cursorRadius => widget.cursorRadius; Brightness? get keyboardAppearance => widget.keyboardAppearance; EdgeInsets? get scrollPadding => widget.scrollPadding; bool? get enableInteractiveSelection => widget.enableInteractiveSelection; DragStartBehavior? get dragStartBehavior => widget.dragStartBehavior; GestureTapCallback? get onTap => widget.onTap; InputCounterWidgetBuilder? get buildCounter => widget.buildCounter; ScrollPhysics? get scrollPhysics => widget.scrollPhysics; ScrollController? get scrollController => widget.scrollController; InputDecoration? get decoration => widget.decoration; FocusNode? get nextNode => widget.nextNode; Iterable<String>? get autofillHints => widget.autofillHints; int get maxLines => widget.maxLines; int? get minLines => widget.minLines; Color? get cursorColor => widget.cursorColor; bool get showCancelIcon => widget.showCancelIcon; bool get showEyeIcon => widget.showEyeIcon; bool _showCancelIconInState = false; bool? _showPasswordInState; @override void initState() { super.initState(); controller.addListener(handleHideCancelIcon); if (showEyeIcon) { _showPasswordInState = true; } } void handleHideCancelIcon() { if (controller.text.isEmpty && showCancelIcon) { if (_showCancelIconInState) { setState(() { _showCancelIconInState = false; }); } } else { if (!_showCancelIconInState && showCancelIcon) { setState(() { _showCancelIconInState = true; }); } } } void handleHidePassword() { if (showEyeIcon) { setState(() { _showPasswordInState = !_showPasswordInState!; }); } } @override void dispose() { if (widget.controller == null) controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return TextField( controller: controller, focusNode: focusNode, decoration: decoration != null ? decoration!.copyWith( suffixIcon: buildSuffixIconDecoration(), ) : const InputDecoration(), keyboardType: keyboardType, textInputAction: nextNode != null ? TextInputAction.next : (textInputAction ?? TextInputAction.done), textCapitalization: textCapitalization, style: style, strutStyle: strutStyle, textAlign: TextAlign.start, textAlignVertical: textAlignVertical, textDirection: textDirection, readOnly: false, toolbarOptions: toolbarOptions, showCursor: showCursor, autofocus: autofocus, obscureText: _showPasswordInState ?? obscureText, autocorrect: autocorrect ?? true, enableSuggestions: enableSuggestions, maxLines: maxLines, minLines: minLines, expands: expands, maxLength: maxLength, onChanged: onChanged, onEditingComplete: onEditingComplete, onSubmitted: nextNode == null ? onSubmitted : (value) { FocusScope.of(context).requestFocus(nextNode); if (onSubmitted != null) { onSubmitted!(value); } }, inputFormatters: inputFormatters, autofillHints: autofillHints, enabled: enabled, cursorWidth: cursorWidth ?? 2.0, cursorRadius: cursorRadius, cursorColor: cursorColor, keyboardAppearance: keyboardAppearance, scrollPadding: scrollPadding ?? const EdgeInsets.all(20.0), dragStartBehavior: dragStartBehavior ?? DragStartBehavior.start, enableInteractiveSelection: enableInteractiveSelection ?? true, onTap: onTap, buildCounter: buildCounter, scrollController: scrollController, scrollPhysics: scrollPhysics, ); } Widget? buildSuffixIconDecoration() { if (_showCancelIconInState) { return buildCloseIcon(); } else if (showEyeIcon) { if (_showPasswordInState!) { return buildEyeShowIcon(); } return buildEyeHideIcon(); } return decoration!.suffixIcon; } Widget buildCloseIcon() { return GestureDetector( onTap: () { controller.clear(); widget.onCancel?.call(); }, child: Container( color: Colors.transparent, child: const Icon(Icons.cancel), ), ); } Widget buildEyeShowIcon() { return GestureDetector( onTap: handleHidePassword, child: Container( color: Colors.transparent, child: const Icon( Icons.visibility_off, color: Colors.grey, ), ), ); } Widget buildEyeHideIcon() { return GestureDetector( onTap: handleHidePassword, child: Container( color: Colors.transparent, child: const Icon( Icons.visibility, color: Colors.grey, ), ), ); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common/custom_text_field_label.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/common/theme/app_padding.dart'; import 'package:flutter_mockup_bloc/presentation/widgets/common/custom_text_field.dart'; import 'package:flutter_mockup_bloc/resource/app_colors.dart'; import 'package:flutter_mockup_bloc/resource/app_text_styles.dart'; class CustomTextFieldLabel extends StatelessWidget { const CustomTextFieldLabel( this.textField, this.data, { Key? key, this.isRequire = false, this.autoMarginTop = true, }) : super(key: key); final String data; final bool isRequire; final bool autoMarginTop; final CustomTextField textField; @override Widget build(BuildContext context) { return Padding( padding: AppPad.a20.copyWith( top: autoMarginTop ? null : 0, bottom: 7, ), child: Column( children: [ isRequire ? Text.rich(TextSpan( style: AppTextStyles.formFieldLabel, children: [ TextSpan(text: data), TextSpan( text: ' *', style: AppTextStyles.formFieldLabel.copyWith( color: AppColors.red, ), ), ], )) : Text(data, style: AppTextStyles.formFieldLabel), textField ], ), ); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common/widget_utils.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/common/theme/app_border_and_radius.dart'; import 'package:flutter_mockup_bloc/common/theme/app_decoration.dart'; import 'package:flutter_mockup_bloc/common/theme/app_padding.dart'; import 'package:flutter_mockup_bloc/presentation/widgets/common/custom_tab_bar.dart'; import 'package:flutter_mockup_bloc/presentation/widgets/dialog/app_dialogs.dart'; import 'package:flutter_mockup_bloc/resource/app_colors.dart'; import 'package:flutter_mockup_bloc/resource/app_text_styles.dart'; class WidgetUtils { static const CircularProgressIndicator loadingCircle = CircularProgressIndicator( color: AppColors.primary, ); static const Center centerLoadingCircle = Center( child: CircularProgressIndicator( color: AppColors.primary, ), ); static const Padding sectionLoading = Padding( padding: AppPad.a20, child: Center( child: loadingCircle, ), ); static const SizedBox screenBodyLoading = SizedBox.expand( child: Center( child: loadingCircle, ), ); static Widget getEmptySection(Text text, {double? verticalPadding = 30}) { final Widget current = Center(child: text); if (verticalPadding != null) return Padding( padding: EdgeInsets.symmetric(vertical: verticalPadding), child: current, ); return current; } static Padding getLoadingSection({ double verticalPadding = 60, double? bottomPadding, }) => Padding( padding: EdgeInsets.symmetric(vertical: verticalPadding) .copyWith(bottom: bottomPadding), child: Center(child: loadingCircle), ); static WillPopScope getWillPopScope( BuildContext context, Widget child, { bool Function()? shouldShowToast, }) => WillPopScope( onWillPop: () async { if (shouldShowToast != null && !shouldShowToast.call()) return false; return await AppDialogs.showToast(context, 'Ấn lần nữa để thoát') .then<bool>((value) async { // if (value == true) await system_shortcuts.home(); // if (value == true) return true; return false; }); }, child: child, ); static ListView getListViewBuilder({ EdgeInsetsGeometry? padding = const EdgeInsets.only(top: 40, bottom: 20), required List<Widget> children, }) => ListView.builder( padding: padding, itemCount: children.length, itemBuilder: (_, index) => children[index], ); static SingleChildScrollView getSingleChildScrollView({ EdgeInsetsGeometry? padding = const EdgeInsets.only(top: 40, bottom: 20), required List<Widget> children, CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.start, }) => SingleChildScrollView( padding: padding, child: Column( crossAxisAlignment: crossAxisAlignment, children: children, ), ); static Row getFormFieldPrefixIconPainter(CustomPaint icon) => Row( mainAxisSize: MainAxisSize.min, children: [ const SizedBox(width: 18), icon, ], ); static Row getFormFieldSuffixIconPainter(CustomPaint icon) => Row( mainAxisSize: MainAxisSize.min, children: [ icon, const SizedBox(width: 18), ], ); static Padding getCustomTabBar(List<String> tabsLabel) => Padding( padding: AppPad.horiz16, child: DecoratedBox( decoration: AppDecoration.tabBar, child: CustomTabBar( unselectedLabelColor: AppColors.primary, unselectedLabelStyle: AppTextStyles.text, isScrollable: true, indicator: BoxDecoration( borderRadius: AppBorderAndRadius.defaultBorderRadius, color: AppColors.primary, ), labelPadding: AppPad.customTabBarLabel, labelStyle: AppTextStyles.tabTitle, tabs: tabsLabel .map((e) => CustomTab( text: e, iconMargin: EdgeInsets.zero, )) .toList(), ), ), ); static Widget getRoundedImage( ImageProvider<Object> imageProvider, radius, [ BoxDecoration? imageDecoration, ]) => DecoratedBox( decoration: BoxDecoration( image: DecorationImage( image: imageProvider, fit: BoxFit.cover, ), borderRadius: imageDecoration?.shape == BoxShape.circle ? null : imageDecoration?.borderRadius ?? BorderRadius.all(Radius.circular((radius))), color: imageDecoration?.color, border: imageDecoration?.border, boxShadow: imageDecoration?.boxShadow, ).copyWith( shape: imageDecoration?.shape, ), ); /// Uniform width of all widgets in input list except SizedBox static List<Widget> uniformWidth(List<Widget> list) => list.map((e) => e is SizedBox ? e : Expanded(flex: 1, child: e)).toList(); static List<Widget> addPadding( List<Widget> list, EdgeInsetsGeometry padding) => list.length == 0 ? list : list.map((e) => Padding(padding: padding, child: e)).toList(); static List<Widget> addSizedBoxAsSeparator( SizedBox sizedBox, List<Widget> widgets) => widgets.length == 0 ? widgets : widgets.expand((element) => [element, sizedBox]).toList() ..removeLast(); static Size getResponsiveSizeBaseOnScreenWidth( BuildContext context, double delta) => Size( MediaQuery.of(context).size.width, (MediaQuery.of(context).size.width * delta).toDouble(), ); /// widthDelta = image's width / design screen's width /// /// heightDelta = image's height / image's width static Size getResponsiveSizeBaseOnWidth( BuildContext context, double widthDelta, double heightDelta) { final screenWidth = MediaQuery.of(context).size.width; final width = screenWidth * widthDelta; return Size( width, (width * heightDelta).toDouble(), ); } } extension WidgetListExtension<Widget> on List<Widget> { addHorizontalSpacing(double size) => this.length == 0 ? this : this .expand((element) => [ element, SizedBox(width: size), ]) .toList() ..removeLast(); addVerticalSpacing(double size) => this.length == 0 ? this : this .expand((element) => [ element, SizedBox(height: size), ]) .toList() ..removeLast(); addSizedBoxAsSeparator(SizedBox sizedBox) => this.length == 0 ? this : this.expand((element) => [element, sizedBox]).toList() ..removeLast(); // uniformWidth({ // BuildContext? context, // double? parentWidth, // double horizontalPadding = 16, // double spaceBetweenChildren = 20, // }) { // final double childrenWidth = // ((context != null ? MediaQuery.of(context).size.width : parentWidth!) / // 1.9) - // horizontalPadding - // spaceBetweenChildren; // return this // .map((e) => e is SizedBox // ? e // : SizedBox( // width: childrenWidth, // child: e, // )) // .toList(); // } // Error: The argument type 'Widget/*1*/' can't be assigned to the parameter type 'Widget/*2*/' // uniformWidth() => this // .map((e) => e is SizedBox // ? e // : Expanded( // flex: 1, // // ignore_for_file: argument_type_not_assignable // child: e, // )) // .toList(); } class SizedBoxExt { static const shrink = SizedBox.shrink(); static const w5 = SizedBox(width: 5); static const h10 = SizedBox(height: 10); static const w10 = SizedBox(width: 10); static const h12 = SizedBox(height: 12); static const w16 = SizedBox(width: 16); static const h15 = SizedBox(height: 15); static const h20 = SizedBox(height: 20); static const w20 = SizedBox(width: 20); static const h30 = SizedBox(height: 30); static const h40 = SizedBox(height: 40); static const h50 = SizedBox(height: 50); static const sliverH16 = SliverToBoxAdapter(child: SizedBox(height: 16)); static const sliverH20 = SliverToBoxAdapter(child: SizedBox(height: 20)); }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common/scafold/bottom_container.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/common/theme/app_border_and_radius.dart'; import 'package:flutter_mockup_bloc/presentation/widgets/common/widget_utils.dart'; import 'package:flutter_mockup_bloc/resource/app_colors.dart'; class BottomContainer extends StatelessWidget { const BottomContainer({ Key? key, required this.children, required this.padding, required this.seperator, }) : super(key: key); final EdgeInsetsGeometry padding; final List<Widget> children; final SizedBox seperator; @override Widget build(BuildContext context) { return Container( padding: padding, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topLeft: AppBorderAndRadius.defaultRadius, topRight: AppBorderAndRadius.defaultRadius, ), boxShadow: [ BoxShadow( offset: Offset(0, -1), blurRadius: 4, color: AppColors.shadow10, ), ], ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: WidgetUtils.addSizedBoxAsSeparator( seperator, WidgetUtils.uniformWidth(children), ), ), ); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common/scafold/custom_scaffold.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/common/theme/app_border_and_radius.dart'; import 'package:flutter_mockup_bloc/presentation/widgets/button/app_bar_back_button.dart'; import 'package:flutter_mockup_bloc/presentation/widgets/common/scafold/bottom_container.dart'; import 'package:flutter_mockup_bloc/presentation/widgets/common/scafold/will_unfocus_form_scope.dart'; import 'package:flutter_mockup_bloc/presentation/widgets/common/widget_utils.dart'; import 'package:flutter_mockup_bloc/resource/app_colors.dart'; import 'package:flutter_mockup_bloc/resource/app_text_styles.dart'; class CustomScaffold extends StatelessWidget { const CustomScaffold({ Key? key, this.resizeToAvoidBottomInset = false, this.automaticallyHandleBackButtonPress = false, required this.title, this.showBackBtn = true, this.bottomAppBar, this.extendBodyBehindAppBar = false, this.extendBody = false, required this.body, this.bottomNavigationBar, this.onBackBtnPressed, this.bottomContainer, }) : super(key: key); final bool resizeToAvoidBottomInset; /// if you provide [onBackBtnPressed], /// so [automaticallyHandleBackButtonPress] must be false final bool automaticallyHandleBackButtonPress; final String title; final bool showBackBtn; final PreferredSizeWidget? bottomAppBar; final bool extendBodyBehindAppBar; final bool extendBody; final Widget body; final Widget? bottomNavigationBar; final void Function()? onBackBtnPressed; final BottomContainer? bottomContainer; @override Widget build(BuildContext context) { // final double height = AppPadding.defaultAppBarHeight + // (bottomAppBar != null ? bottomAppBar!.preferredSize.height : 0); Widget current = Scaffold( resizeToAvoidBottomInset: resizeToAvoidBottomInset, appBar: AppBar( // toolbarHeight: height, leading: showBackBtn == false ? null : AppBarBackButton(onBackBtnPressed: onBackBtnPressed), centerTitle: true, title: Text( title.toUpperCase(), style: AppTextStyles.appbarTitle, overflow: TextOverflow.ellipsis, ), bottom: bottomAppBar, shape: AppBorderAndRadius.defaultAppBarBorder, elevation: 4, shadowColor: AppColors.appBarShadow, ), // backgroundColor: AppColors.white, extendBodyBehindAppBar: extendBodyBehindAppBar, backgroundColor: Colors.white, extendBody: extendBody, body: Padding( padding: extendBodyBehindAppBar ? EdgeInsets.only( top: bottomAppBar == null ? 5 : bottomAppBar!.preferredSize.height + 30, bottom: 0, ) : const EdgeInsets.all(0), child: body, ), bottomNavigationBar: bottomContainer, ); if (automaticallyHandleBackButtonPress) current = WidgetUtils.getWillPopScope(context, current); else if (onBackBtnPressed != null) current = WillPopScope( child: current, onWillPop: () async { if (onBackBtnPressed == null) return true; onBackBtnPressed!(); return false; }, ); return ColoredBox( color: AppColors.primary, child: SafeArea( child: WillUnfocusFormScope( child: current, ), ), ); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/common/scafold/will_unfocus_form_scope.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/utils/extension/system_chrome_extension.dart'; class WillUnfocusFormScope extends StatelessWidget { const WillUnfocusFormScope({ Key? key, required this.child, this.willUnfocusCallback, }) : super(key: key); final Widget child; final VoidCallback? willUnfocusCallback; @override Widget build(BuildContext context) { return GestureDetector( onTap: () { SystemChromeExtension.hideKeyboardIfVisible(); willUnfocusCallback?.call(); }, child: child, ); } }
0
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets
mirrored_repositories/flutter_mockup_bloc/lib/presentation/widgets/dialog/base_dialog.dart
import 'package:flutter/material.dart'; import 'package:flutter_mockup_bloc/presentation/widgets/common/my_button.dart'; import 'package:flutter_mockup_bloc/resource/app_colors.dart'; import 'package:flutter_mockup_bloc/resource/app_text_styles.dart'; import 'package:flutter_mockup_bloc/resource/gaps.dart'; import 'package:flutter_mockup_bloc/utils/device/device_utils.dart'; class BaseDialog extends StatelessWidget { const BaseDialog({ Key? key, this.title, this.onPressed, this.hiddenTitle = false, required this.child }) : super(key : key); final String? title; final VoidCallback? onPressed; final Widget child; final bool hiddenTitle; @override Widget build(BuildContext context) { final Widget dialogTitle = Visibility( visible: !hiddenTitle, child: Padding( padding: const EdgeInsets.only(bottom: 8.0), child: Text( hiddenTitle ? '' : title ?? '', style: AppTextStyles.appbarTitle, ), ), ); final Widget bottomButton = Row( children: <Widget>[ _DialogButton( text: 'Cancel', textColor: AppColors.text_gray, onPressed: () => Navigator.pop(context), ), const SizedBox( height: 48.0, width: 0.6, child: VerticalDivider(), ), _DialogButton( text: 'OK', textColor: Theme.of(context).primaryColor, onPressed: onPressed, ), ], ); final Widget content = Material( borderRadius: BorderRadius.circular(8.0), child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Gaps.vGap24, dialogTitle, Flexible(child: child), Gaps.vGap8, Gaps.line, bottomButton, ], ), ); final Widget body = MediaQuery.removeViewInsets( removeLeft: true, removeTop: true, removeRight: true, removeBottom: true, context: context, child: Center( child: SizedBox( width: 270.0, child: content, ), ), ); if (Device.getAndroidSdkInt() >= 30) { return Padding( padding: MediaQuery.of(context).viewInsets, child: body, ); } else { return AnimatedPadding( padding: MediaQuery.of(context).viewInsets, duration: const Duration(milliseconds: 120), curve: Curves.easeInCubic, // easeOutQuad child: body, ); } } } class _DialogButton extends StatelessWidget { const _DialogButton({ Key? key, required this.text, this.textColor, this.onPressed, }): super(key: key); final String text; final Color? textColor; final VoidCallback? onPressed; @override Widget build(BuildContext context) { return Expanded( child: MyButton( text: text, textColor: textColor, onPressed: onPressed, backgroundColor: Colors.transparent, ), ); } }
0