repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero/lib
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero/lib/components/white_page_route.dart
import 'package:flutter/material.dart'; //Create a transition that fades in the new view, while fading out a white background class WhitePageRoute extends PageRouteBuilder { final Widget enterPage; WhitePageRoute({this.enterPage}) : super( transitionDuration: Duration(milliseconds: 1700), pageBuilder: (context, animation, secondaryAnimation) => enterPage, transitionsBuilder: (context, animation, secondaryAnimation, child) { var fadeIn = Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(curve: Interval(.7, 1), parent: animation)); var fadeOut = Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(curve: Interval(0, .2), parent: animation)); return Stack(children: <Widget>[ FadeTransition(opacity: fadeOut, child: Container(color: Colors.white)), FadeTransition(opacity: fadeIn, child: child) ]); }); }
0
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero/lib
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero/lib/components/rotation_3d.dart
import 'dart:math'; import 'package:flutter/material.dart'; //Takes a x,y or z rotation, in degrees, and rotates. Good for spins & 3d flip effects class Rotation3d extends StatelessWidget { //Degrees to rads constant static const double degrees2Radians = pi/180; final Widget child; final double rotationX; final double rotationY; final double rotationZ; const Rotation3d({Key key, @required this.child, this.rotationX=0, this.rotationY=0, this.rotationZ=0}) : super(key: key); @override Widget build(BuildContext context) { return Transform( alignment: FractionalOffset.center, transform: Matrix4.identity() ..setEntry(3, 2, 0.001) ..rotateX(rotationX * degrees2Radians) ..rotateY(rotationY * degrees2Radians) ..rotateZ(rotationZ * degrees2Radians), child: child); } }
0
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list/lib/hotel_list.dart
import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'demo_data.dart'; import 'styles.dart'; class HotelList extends StatefulWidget { final List<Hotel> hotels; HotelList(this.hotels); @override _HotelListViewState createState() => _HotelListViewState(); } class _HotelListViewState extends State<HotelList> with SingleTickerProviderStateMixin { AnimationController _anim; List<Hotel> _oldHotels; @override void initState() { _anim = AnimationController(vsync: this, duration: Duration(milliseconds: 700)); _anim.addListener(() => setState(() {})); super.initState(); } @override Widget build(BuildContext context) { if (_oldHotels != widget.hotels) { _anim.forward(from: 0); } _oldHotels = widget.hotels; Size size = MediaQuery.of(context).size; return Opacity( opacity: _anim.value, child: Padding( padding: EdgeInsets.symmetric(horizontal: Styles.hzScreenPadding * 1.5, vertical: 10), child: Container( width: 400, height: size.height * .25, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text('Hotels'.toUpperCase(), style: Styles.hotelsTitleSection), Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[for (Hotel hotel in widget.hotels) _buildHotelData(hotel)], ), ) ], ), ), ), ); } Widget _buildHotelData(Hotel hotel) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text(hotel.name, style: Styles.hotelTitle), SizedBox(height: 3), Row( children: <Widget>[ _buildStars(hotel.rate.toInt()), Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: Text(hotel.rate.toString(), style: Styles.hotelScore), ), Text('(${hotel.reviews})', style: Styles.hotelData), ], ) ], ), Text('\$${hotel.price}', style: Styles.hotelPrice) ], ); } Widget _buildStars(int count) { List<Widget> stars = []; for (int i = 0; i < count; i++) { stars.add(Icon(Icons.star, color: Color(0xFFfeda7d), size: 13)); } return Row(children: stars); } }
0
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list/lib/rotation_3d.dart
import 'dart:math'; import 'package:flutter/material.dart'; //Takes a x,y or z rotation, in degrees, and rotates. Good for spins & 3d flip effects class Rotation3d extends StatelessWidget { //Degrees to rads constant static const double degrees2Radians = pi/180; final Widget child; final double rotationX; final double rotationY; final double rotationZ; const Rotation3d({Key key, @required this.child, this.rotationX=0, this.rotationY=0, this.rotationZ=0}) : super(key: key); @override Widget build(BuildContext context) { return Transform( alignment: FractionalOffset.center, transform: Matrix4.identity() ..setEntry(3, 2, 0.001) ..rotateX(rotationX * degrees2Radians) ..rotateY(rotationY * degrees2Radians) ..rotateZ(rotationZ * degrees2Radians), child: child); } }
0
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list/lib/travel_card_renderer.dart
import 'package:flutter/material.dart'; import 'demo_data.dart'; import 'main.dart'; import 'styles.dart'; class TravelCardRenderer extends StatelessWidget { final double offset; final double cardWidth; final double cardHeight; final City city; const TravelCardRenderer(this.offset, {Key key, this.cardWidth = 250, @required this.city, this.cardHeight}) : super(key: key); @override Widget build(BuildContext context) { return Container( width: cardWidth, margin: EdgeInsets.only(top: 8), child: Stack( overflow: Overflow.visible, alignment: Alignment.center, children: <Widget>[ // Card background color & decoration Container( margin: EdgeInsets.only(top: 30, left: 12, right: 12, bottom: 12), decoration: BoxDecoration( color: city.color, borderRadius: BorderRadius.circular(8), boxShadow: [ BoxShadow(color: Colors.black12, blurRadius: 4 * offset.abs()), BoxShadow(color: Colors.black12, blurRadius: 10 + 6 * offset.abs()), ], ), ), // City image, out of card by 15px Positioned(top: -15, child: _buildCityImage()), // City information _buildCityData() ], ), ); } Widget _buildCityImage() { double maxParallax = 30; double globalOffset = offset * maxParallax * 2; double cardPadding = 28; double containerWidth = cardWidth - cardPadding; return Container( height: cardHeight, width: containerWidth, child: Stack( alignment: Alignment.bottomCenter, children: <Widget>[ _buildPositionedLayer("images/${city.name}/${city.name}-Back.png", containerWidth * .8, maxParallax * .1, globalOffset), _buildPositionedLayer("images/${city.name}/${city.name}-Middle.png", containerWidth * .9, maxParallax * .6, globalOffset), _buildPositionedLayer("images/${city.name}/${city.name}-Front.png", containerWidth * .9, maxParallax, globalOffset), ], ), ); } Widget _buildCityData() { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ // The sized box mock the space of the city image SizedBox(width: double.infinity, height: cardHeight * .57), Padding( padding: const EdgeInsets.symmetric(horizontal: 12.0), child: Text(city.title, style: Styles.cardTitle, textAlign: TextAlign.center), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 25.0), child: Text(city.description, style: Styles.cardSubtitle, textAlign: TextAlign.center), ), Expanded(child: SizedBox(),), FlatButton( disabledColor: Colors.transparent, color: Colors.transparent, child: Text('Learn More'.toUpperCase(), style: Styles.cardAction), onPressed: null, ), SizedBox(height: 8) ], ); } Widget _buildPositionedLayer(String path, double width, double maxOffset, double globalOffset) { double cardPadding = 24; double layerWidth = cardWidth - cardPadding; return Positioned( left: ((layerWidth * .5) - (width / 2) - offset * maxOffset) + globalOffset, bottom: cardHeight * .45, child: Image.asset( path, width: width, package: App.pkg, )); } }
0
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list/lib/styles.dart
import 'package:flutter/material.dart'; import 'main.dart'; class Styles { static const double hzScreenPadding = 18; static final TextStyle baseTitle = TextStyle(fontSize: 11, fontFamily: 'DMSerifDisplay', package: App.pkg); static final TextStyle baseBody = TextStyle(fontSize: 11, fontFamily: 'OpenSans', package: App.pkg); static final TextStyle appHeader = baseTitle.copyWith(color: Color(0xFF0e0e0e), fontSize: 36, height: 1); static final TextStyle cardTitle = baseTitle.copyWith(height: 1, color: Color(0xFF1a1a1a), fontSize: 25); static final TextStyle cardSubtitle = baseBody.copyWith(color: Color(0xFF666666), height: 1.5, fontSize: 12); static final TextStyle cardAction = baseBody.copyWith(color: Color(0xFFa6998b), fontSize: 10, height: 1, fontWeight: FontWeight.w600, letterSpacing: 0.1); static final TextStyle hotelsTitleSection = baseBody.copyWith(color: Colors.black, fontSize: 14, fontWeight: FontWeight.bold, height: 2); static final TextStyle hotelTitle = baseBody.copyWith(color: Colors.black, fontSize: 14, fontWeight: FontWeight.w600); static final TextStyle hotelPrice = baseBody.copyWith(color: Color(0xff4d4d4d), fontSize: 13); static final TextStyle hotelScore = baseBody.copyWith(color: Color(0xff0e0e0e)); static final TextStyle hotelData = baseBody.copyWith(color: Colors.grey[700]); }
0
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list/lib/demo_data.dart
import 'package:flutter/material.dart'; class City { final String name; final String title; final String description; final Color color; final List<Hotel> hotels; City({ this.title, this.name, this.description, this.color, this.hotels, }); } class Hotel { final String name; double rate; final int reviews; final int price; Hotel(this.name, {this.reviews, this.price}) : rate = 5.0; } class DemoData { List<City> _cities = [ City( name: 'Pisa', title: 'Pisa, Italy', description: 'Discover a beautiful city where ancient and modern meet', color: Color(0xffdee5cf), hotels: [ Hotel('Hotel Bologna', reviews: 201, price: 120), Hotel('Tree House', reviews: 85, price: 98), Hotel('Allegroitalia Pisa Tower Plaza', reviews: 128, price: 119), ]), City( name: 'Budapest', title: 'Budapest, Hungary', description: 'Meet the city with rich history and indescribable culture', color: Color(0xffdaf3f7), hotels: [ Hotel('Hotel Estilo Budapest', reviews: 762, price: 87), Hotel('Danubius Hotel', reviews: 3122, price: 196), Hotel('Golden Budapest Condominium', reviews: 213, price: 217), ]), City( name: 'London', title: 'London, England', description: 'A diverse and exciting city with the world’s best sights and attractions!', color: Color(0xfff9d9e2), hotels: [ Hotel('InterContinental London Hotel', reviews: 1624, price: 418), Hotel('Brick Lane Hotel', reviews: 101, price: 101), Hotel('Park Villa Boutique House', reviews: 161, price: 128), ]), ]; List<City> getCities() => _cities; List<Hotel> getHotels(City city) => city.hotels; }
0
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list/lib/travel_card_list.dart
import 'package:flutter/material.dart'; import 'demo_data.dart'; import 'rotation_3d.dart'; import 'travel_card_renderer.dart'; class TravelCardList extends StatefulWidget { final List<City> cities; final Function onCityChange; const TravelCardList({Key key, this.cities, @required this.onCityChange}) : super(key: key); @override TravelCardListState createState() => TravelCardListState(); } class TravelCardListState extends State<TravelCardList> with SingleTickerProviderStateMixin { final double _maxRotation = 20; PageController _pageController; double _cardWidth = 160; double _cardHeight = 200; double _normalizedOffset = 0; double _prevScrollX = 0; bool _isScrolling = false; //int _focusedIndex = 0; AnimationController _tweenController; Tween<double> _tween; Animation<double> _tweenAnim; @override Widget build(BuildContext context) { Size size = MediaQuery.of(context).size; _cardHeight = (size.height * .48).clamp(300.0, 400.0); _cardWidth = _cardHeight * .8; //Calculate the viewPort fraction for this aspect ratio, since PageController does not accept pixel based size values _pageController = PageController(initialPage: 1, viewportFraction: _cardWidth / size.width); //Create our main list Widget listContent = Container( //Wrap list in a container to control height and padding height: _cardHeight, //Use a ListView.builder, calls buildItemRenderer() lazily, whenever it need to display a listItem child: PageView.builder( //Use bounce-style scroll physics, feels better with this demo physics: BouncingScrollPhysics(), controller: _pageController, itemCount: 8, scrollDirection: Axis.horizontal, itemBuilder: (context, i) => _buildItemRenderer(i), ), ); //Wrap our list content in a Listener to detect PointerUp events, and a NotificationListener to detect ScrollStart and ScrollUpdate //We have to use both, because NotificationListener does not inform us when the user has lifted their finger. //We can not use GestureDetector like we normally would, ListView suppresses it while scrolling. return Listener( onPointerUp: _handlePointerUp, child: NotificationListener( onNotification: _handleScrollNotifications, child: listContent, ), ); } //Create a renderer for each list item Widget _buildItemRenderer(int itemIndex) { return Container( //Vertically pad all the non-selected items, to make them smaller. AnimatedPadding widget handles the animation. child: Rotation3d( rotationY: _normalizedOffset * _maxRotation, //Create the actual content renderer for our list child: TravelCardRenderer( //Pass in the offset, renderer can update it's own view from there _normalizedOffset, //Pass in city path for the image asset links city: widget.cities[itemIndex % widget.cities.length], cardWidth: _cardWidth, cardHeight: _cardHeight, ), ), ); } //Check the notifications bubbling up from the ListView, use them to update our currentOffset and isScrolling state bool _handleScrollNotifications(Notification notification) { //Scroll Update, add to our current offset, but clamp to -1 and 1 if (notification is ScrollUpdateNotification) { if (_isScrolling) { double dx = notification.metrics.pixels - _prevScrollX; double scrollFactor = .01; double newOffset = (_normalizedOffset + dx * scrollFactor); _setOffset(newOffset.clamp(-1.0, 1.0)); } _prevScrollX = notification.metrics.pixels; //Calculate the index closest to middle //_focusedIndex = (_prevScrollX / (_itemWidth + _listItemPadding)).round(); widget.onCityChange(widget.cities.elementAt(_pageController.page.round() % widget.cities.length)); } //Scroll Start else if (notification is ScrollStartNotification) { _isScrolling = true; _prevScrollX = notification.metrics.pixels; if (_tween != null) { _tweenController.stop(); } } return true; } //If the user has released a pointer, and is currently scrolling, we'll assume they're done scrolling and tween our offset to zero. //This is a bit of a hack, we can't be sure this event actually came from the same finger that was scrolling, but should work most of the time. void _handlePointerUp(PointerUpEvent event) { if (_isScrolling) { _isScrolling = false; _startOffsetTweenToZero(); } } //Helper function, any time we change the offset, we want to rebuild the widget tree, so all the renderers get the new value. void _setOffset(double value) { setState(() { _normalizedOffset = value; }); } //Tweens our offset from the current value, to 0 void _startOffsetTweenToZero() { //The first time this runs, setup our controller, tween and animation. All 3 are required to control an active animation. int tweenTime = 1000; if (_tweenController == null) { //Create Controller, which starts/stops the tween, and rebuilds this widget while it's running _tweenController = AnimationController(vsync: this, duration: Duration(milliseconds: tweenTime)); //Create Tween, which defines our begin + end values _tween = Tween<double>(begin: -1, end: 0); //Create Animation, which allows us to access the current tween value and the onUpdate() callback. _tweenAnim = _tween.animate(new CurvedAnimation(parent: _tweenController, curve: Curves.elasticOut)) //Set our offset each time the tween fires, triggering a rebuild ..addListener(() { _setOffset(_tweenAnim.value); }); } //Restart the tweenController and inject a new start value into the tween _tween.begin = _normalizedOffset; _tweenController.reset(); _tween.end = 0; _tweenController.forward(); } }
0
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:shared/env.dart'; import 'demo.dart'; void main() => runApp(App()); class App extends StatelessWidget { static String _pkg = "parallax_travel_cards_list"; static String get pkg => Env.getPackage(_pkg); @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitDown, DeviceOrientation.portraitUp, ]); return MaterialApp( home: TravelCardDemo(), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_list/lib/demo.dart
import 'package:flutter/material.dart'; import 'demo_data.dart'; import 'hotel_list.dart'; import 'styles.dart'; import 'travel_card_list.dart'; class TravelCardDemo extends StatefulWidget { @override _TravelCardDemoState createState() => _TravelCardDemoState(); } class _TravelCardDemoState extends State<TravelCardDemo> { List<City> _cityList; City _currentCity; @override void initState() { super.initState(); var data = DemoData(); _cityList = data.getCities(); _currentCity = _cityList[1]; } @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; return Scaffold( appBar: _buildAppBar(), body: Container( color: Colors.white, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Expanded(child: SizedBox()), Padding( padding: EdgeInsets.symmetric(horizontal: Styles.hzScreenPadding), child: Text( 'Where are you going next?', overflow: TextOverflow.ellipsis, style: Styles.appHeader, maxLines: 2, ), ), TravelCardList( cities: _cityList, onCityChange: _handleCityChange, ), HotelList(_currentCity.hotels), Expanded(child: SizedBox()), ], ), ), ); } void _handleCityChange(City city) { setState(() { this._currentCity = city; }); } Widget _buildAppBar() { return AppBar( elevation: 0.0, leading: Icon(Icons.menu, color: Colors.black), backgroundColor: Colors.white, brightness: Brightness.light, actions: <Widget>[ Padding( padding: const EdgeInsets.symmetric(horizontal: Styles.hzScreenPadding), child: Icon(Icons.search, color: Colors.black), ) ], ); } }
0
mirrored_repositories/flutter_showcase/example/apps/gooey_edge
mirrored_repositories/flutter_showcase/example/apps/gooey_edge/lib/content_card.dart
import 'package:flutter/material.dart'; import 'dart:math'; import 'package:flutter/scheduler.dart'; import 'main.dart'; class ContentCard extends StatefulWidget { final String color; final Color altColor; final String title; final String subtitle; ContentCard({this.color, this.title = "", this.subtitle, this.altColor}) : super(); @override _ContentCardState createState() => _ContentCardState(); } class _ContentCardState extends State<ContentCard> { Ticker _ticker; @override void initState() { _ticker = Ticker((d) { setState(() {}); }) ..start(); super.initState(); } @override void dispose() { _ticker.dispose(); super.dispose(); } @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; var time = DateTime.now().millisecondsSinceEpoch / 2000; var scaleX = 1.2 + sin(time) * .05; var scaleY = 1.2 + cos(time) * .07; var offsetY = 20 + cos(time) * 20; return Stack( alignment: Alignment.center, fit: StackFit.expand, children: <Widget>[ Transform( transform: Matrix4.diagonal3Values(scaleX, scaleY, 1), child: Transform.translate( offset: Offset(-(scaleX - 1) / 2 * size.width, -(scaleY - 1) / 2 * size.height + offsetY), child: Image.asset('images/Bg-${widget.color}.png', fit: BoxFit.cover, package: App.pkg), ), ), Container( alignment: Alignment.center, child: Padding( padding: const EdgeInsets.only(top: 75.0, bottom: 25.0), child: Column( children: <Widget>[ //Top Image Expanded( flex: 3, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20.0), child: Image.asset('images/Illustration-${widget.color}.png', fit: BoxFit.contain, package: App.pkg), ), ), //Slider circles Container(height: 14, child: Image.asset('images/Slider-${widget.color}.png', package: App.pkg)), //Bottom content Expanded( flex: 2, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 18.0), child: _buildBottomContent(), ), ), ], ), ), ) ], ); } Widget _buildBottomContent() { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text(widget.title, textAlign: TextAlign.center, style: TextStyle(height: 1.2, fontSize: 30.0, fontFamily: 'DMSerifDisplay', color: Colors.white, package: App.pkg)), Text(widget.subtitle, textAlign: TextAlign.center, style: TextStyle(fontSize: 14.0, fontWeight: FontWeight.w300, fontFamily: 'OpenSans', color: Colors.white, package: App.pkg)), Padding( padding: const EdgeInsets.symmetric(horizontal: 36.0), child: MaterialButton( elevation: 0, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)), color: widget.altColor, child: Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: Text( 'Get Started', style: TextStyle( fontSize: 16, letterSpacing: .8, fontFamily: 'OpenSans', fontWeight: FontWeight.w600, color: Colors.white, package: App.pkg) ), ), onPressed: () {}, ), ) ], ); } }
0
mirrored_repositories/flutter_showcase/example/apps/gooey_edge
mirrored_repositories/flutter_showcase/example/apps/gooey_edge/lib/gooey_edge.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'side.dart'; class GooeyEdge { List<_GooeyPoint> points; Side side; double edgeTension = 0.01; double farEdgeTension = 0.0; double touchTension = 0.1; double pointTension = 0.25; double damping = 0.9; double maxTouchDistance = 0.15; int lastT = 0; FractionalOffset touchOffset; GooeyEdge({count=10, this.side=Side.left}) { points = []; for (int i=0; i<count; i++) { points.add(_GooeyPoint(0.0, i/(count-1))); } } void reset() { points.forEach((pt) => pt.x = pt.velX = pt.velY = 0.0); } void applyTouchOffset([Offset offset, Size size]) { if (offset == null) { touchOffset = null; return; } FractionalOffset o = FractionalOffset.fromOffsetAndSize(offset, size); if (side == Side.left) { touchOffset = o; } else if (side == Side.right) { touchOffset = FractionalOffset(1.0 - o.dx, 1.0 - o.dy); } else if (side == Side.top) { touchOffset = FractionalOffset(o.dy, 1.0 - o.dx); } else { touchOffset = FractionalOffset(1.0 - o.dy, o.dx); } } Path buildPath(Size size, {double margin = 0.0}) { if (points == null || points.length == 0) { return null; } Matrix4 mtx = _getTransform(size, margin); Path path = Path(); int l = points.length; Offset pt = _GooeyPoint(-margin, 1.0).toOffset(mtx), pt1; path.moveTo(pt.dx, pt.dy); // bl pt = _GooeyPoint(-margin, 0.0).toOffset(mtx); path.lineTo(pt.dx, pt.dy); // tl pt = points[0].toOffset(mtx); path.lineTo(pt.dx, pt.dy); // tr pt1 = points[1].toOffset(mtx); path.lineTo(pt.dx + (pt1.dx - pt.dx) / 2, pt.dy + (pt1.dy - pt.dy) / 2); for (int i=2; i < l; i++) { pt = pt1; pt1 = points[i].toOffset(mtx); double midX = pt.dx + (pt1.dx - pt.dx) / 2; double midY = pt.dy + (pt1.dy - pt.dy) / 2; path.quadraticBezierTo(pt.dx, pt.dy, midX, midY); } path.lineTo(pt1.dx, pt1.dy); // br path.close(); // bl return path; } void tick(Duration duration) { if (points == null || points.length == 0) { return; } int l = points.length; double t = min(1.5, (duration.inMilliseconds - lastT) / 1000 * 60); lastT = duration.inMilliseconds; double dampingT = pow(damping, t); for (int i=0; i<l; i++) { _GooeyPoint pt = points[i]; pt.velX -= pt.x * edgeTension * t; pt.velX += (1.0 - pt.x) * farEdgeTension * t; if (touchOffset != null) { double ratio = max(0.0, 1.0 - (pt.y - touchOffset.dy).abs() / maxTouchDistance); pt.velX += (touchOffset.dx - pt.x) * touchTension * ratio * t; } if (i > 0) { _addPointTension(pt, points[i-1].x, t); } if (i < l-1) { _addPointTension(pt, points[i+1].x, t); } pt.velX *= dampingT; } for (int i=0; i<l; i++) { _GooeyPoint pt = points[i]; pt.x += pt.velX * t; } } Matrix4 _getTransform(Size size, double margin) { bool vertical = side == Side.top || side == Side.bottom; double w = (vertical ? size.height : size.width) + margin *2; double h = (vertical ? size.width : size.height) + margin *2; Matrix4 mtx = Matrix4.identity()..translate(-margin, 0.0)..scale(w, h); if (side == Side.top) { mtx..rotateZ(pi/2)..translate(0.0, -1.0); } else if (side == Side.right) { mtx..rotateZ(pi)..translate(-1.0, -1.0); } else if (side == Side.bottom) { mtx..rotateZ(pi*3/2)..translate(-1.0, 0.0); } return mtx; } void _addPointTension(_GooeyPoint pt0, double x, double t) { pt0.velX += (x - pt0.x) * pointTension * t; } } class _GooeyPoint { double x; double y; double velX = 0.0; double velY = 0.0; _GooeyPoint([this.x = 0.0, this.y = 0.0]); Offset toOffset ([Matrix4 transform]) { Offset o = Offset(x, y); if (transform == null) { return o; } return MatrixUtils.transformPoint(transform, o); } }
0
mirrored_repositories/flutter_showcase/example/apps/gooey_edge
mirrored_repositories/flutter_showcase/example/apps/gooey_edge/lib/gooey_edge_clipper.dart
import 'package:flutter/material.dart'; import 'gooey_edge.dart'; class GooeyEdgeClipper extends CustomClipper<Path> { GooeyEdge edge; double margin; GooeyEdgeClipper(this.edge, {this.margin=0.0}) : super(); @override Path getClip(Size size) { return edge.buildPath(size, margin:margin); } @override bool shouldReclip(CustomClipper<Path> oldClipper) { return true; // TODO: optimize? } }
0
mirrored_repositories/flutter_showcase/example/apps/gooey_edge
mirrored_repositories/flutter_showcase/example/apps/gooey_edge/lib/gooey_carousel.dart
import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'side.dart'; import 'sun_moon.dart'; import 'gooey_edge.dart'; import 'gooey_edge_clipper.dart'; class GooeyCarousel extends StatefulWidget { final List<Widget> children; GooeyCarousel({@required this.children}) : super(); @override GooeyCarouselState createState () => GooeyCarouselState(); } class GooeyCarouselState extends State<GooeyCarousel> with SingleTickerProviderStateMixin { int _index = 0; // index of the base (bottom) child int _dragIndex; // index of the top child Offset _dragOffset; // starting offset of the drag double _dragDirection; // +1 when dragging left to right, -1 for right to left bool _dragCompleted; // has the drag successfully resulted in a swipe GooeyEdge _edge; Ticker _ticker; GlobalKey _key = GlobalKey(); @override void initState() { _edge = GooeyEdge(count: 25); _ticker = createTicker(_tick)..start(); super.initState(); } @override void dispose() { _ticker.dispose(); super.dispose(); } void _tick(Duration duration) { _edge.tick(duration); setState((){}); } @override Widget build(BuildContext context) { int l = widget.children.length; return GestureDetector( key: _key, onPanDown: (details) => _handlePanDown(details, _getSize()), onPanUpdate: (details) => _handlePanUpdate(details, _getSize()), onPanEnd: (details) => _handlePanEnd(details, _getSize()), child: Stack(children: <Widget>[ widget.children[_index % l], _dragIndex == null ? SizedBox() : ClipPath( child: widget.children[_dragIndex % l], clipBehavior: Clip.hardEdge, clipper: GooeyEdgeClipper(_edge, margin: 10.0), ), SunAndMoon( index: _dragIndex, isDragComplete: _dragCompleted, ) ],) ); } Size _getSize() { final RenderBox box = _key.currentContext.findRenderObject(); return box.size; } void _handlePanDown(DragDownDetails details, Size size) { if (_dragIndex != null && _dragCompleted) { _index = _dragIndex; } _dragIndex = null; _dragOffset = details.localPosition; _dragCompleted = false; _dragDirection = 0; _edge.farEdgeTension = 0.0; _edge.edgeTension = 0.01; _edge.reset(); } void _handlePanUpdate(DragUpdateDetails details, Size size) { // TODO: Temporal fix: Changed global Position to localPosition double dx = details.localPosition.dx - _dragOffset.dx; if (!_isSwipeActive(dx)) { return; } if (_isSwipeComplete(dx, size.width)) { return; } if (_dragDirection == -1) { dx = size.width + dx; } _edge.applyTouchOffset(Offset(dx, details.localPosition.dy), size); } bool _isSwipeActive(double dx) { // check if a swipe is just starting: if (_dragDirection == 0.0 && dx.abs() > 20.0) { _dragDirection = dx.sign; _edge.side = _dragDirection == 1.0 ? Side.left : Side.right; setState(() { _dragIndex = _index - _dragDirection.toInt(); }); } return _dragDirection != 0.0; } bool _isSwipeComplete(double dx, double width) { if (_dragDirection == 0.0) { return false; } // haven't started if (_dragCompleted) { return true; } // already done // check if swipe is just completed: double availW = _dragOffset.dx; if (_dragDirection == 1) { availW = width - availW; } double ratio = dx * _dragDirection / availW; if (ratio > 0.8 && availW / width > 0.5) { _dragCompleted = true; _edge.farEdgeTension = 0.01; _edge.edgeTension = 0.0; _edge.applyTouchOffset(); } return _dragCompleted; } void _handlePanEnd(DragEndDetails details, Size size) { _edge.applyTouchOffset(); } }
0
mirrored_repositories/flutter_showcase/example/apps/gooey_edge
mirrored_repositories/flutter_showcase/example/apps/gooey_edge/lib/side.dart
enum Side { left, top, right, bottom }
0
mirrored_repositories/flutter_showcase/example/apps/gooey_edge
mirrored_repositories/flutter_showcase/example/apps/gooey_edge/lib/gooey_edge_painter.dart
import 'package:flutter/material.dart'; import 'gooey_edge.dart'; // This isn't used in the example, but it can be used to quickly paint a GooeyEdge to a canvas. class GooeyEdgePainter extends CustomPainter { GooeyEdge edge; GooeyEdgePainter({@required this.edge}); @override void paint(Canvas canvas, Size size) { Paint fill = new Paint()..color = Colors.blue; canvas.drawPath(edge.buildPath(size), fill); } @override bool shouldRepaint(GooeyEdgePainter oldPainter) { return true; } }
0
mirrored_repositories/flutter_showcase/example/apps/gooey_edge
mirrored_repositories/flutter_showcase/example/apps/gooey_edge/lib/main.dart
import 'package:flutter/material.dart'; import 'package:shared/env.dart'; import 'demo.dart'; void main() => runApp(App()); class App extends StatelessWidget { static String _pkg = "gooey_edge"; static String get pkg => Env.getPackage(_pkg); @override Widget build(BuildContext context) { return MaterialApp( home: GooeyEdgeDemo(title: 'Gooey Edge Demo'), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/gooey_edge
mirrored_repositories/flutter_showcase/example/apps/gooey_edge/lib/demo.dart
import 'package:flutter/material.dart'; import 'content_card.dart'; import 'gooey_carousel.dart'; class GooeyEdgeDemo extends StatefulWidget { GooeyEdgeDemo({Key key, this.title}) : super(key: key); final String title; @override _GooeyEdgeDemoState createState() => _GooeyEdgeDemoState(); } class _GooeyEdgeDemoState extends State<GooeyEdgeDemo> { @override Widget build(BuildContext context) { return Scaffold( body: GooeyCarousel( children: <Widget>[ ContentCard( color: 'Red', altColor: Color(0xFF4259B2), title: "Wake up gently \nwith sounds of nature", subtitle: 'Relax your mind and create inner peace with soothing sounds of nature.', ), ContentCard( color: 'Yellow', altColor: Color(0xFF904E93), title: "Clear your mind \nwith breathing exercises", subtitle: 'Melt your stresses and anxieties away with 50+ breathing exercises.', ), ContentCard( color: 'Blue', altColor: Color(0xFFFFB138), title: "Fall asleep \nwith bedtime stories", subtitle: 'Enjoy a restful night’s sleep with relaxing activities and calm bedtime stories.', ), ], ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/gooey_edge
mirrored_repositories/flutter_showcase/example/apps/gooey_edge/lib/sun_moon.dart
import 'dart:math'; import 'package:flutter/widgets.dart'; import 'main.dart'; class SunAndMoon extends StatefulWidget { final bool isDragComplete; final List<String> assetPaths; final int index; SunAndMoon( {Key key, this.isDragComplete = false, this.assetPaths = const ['images/Sun-Yellow.png', 'images/Sun-Red.png', 'images/Moon-Crescent.png'], this.index}) : super(key: key); @override State<StatefulWidget> createState() => _SunAndMoonState(); } class _SunAndMoonState extends State<SunAndMoon> with SingleTickerProviderStateMixin { AnimationController _animationController; Animation _rotationAnimation; int _rotationRadius = 300; int _currentIndex; @override void initState() { super.initState(); //Create unbounded controller so we can animate the rotation in positive or negative direction _animationController = AnimationController.unbounded(vsync: this); _rotationAnimation = Tween<double>(begin: 1, end: 0).animate(_animationController); } @override void dispose() { _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { bool isDragComplete = widget.isDragComplete ?? false; //Rotate 1/3 turn, each time index changes if (isDragComplete && widget.index != _currentIndex) { _currentIndex = widget.index; double nextAnimState = widget.index / 3; _animationController.animateTo(nextAnimState, duration: Duration(milliseconds: 350), curve: Curves.easeOut); } return Container( width: double.infinity, height: double.infinity, child: Stack( alignment: Alignment.center, children: <Widget>[ _buildAssetWithDefaultAngle(0, 240), _buildAssetWithDefaultAngle(1, 30), _buildAssetWithDefaultAngle(2, 180), ], ), ); } Widget _buildAssetWithDefaultAngle(int index, double degreeAngle) { double radianAngle = degreeAngle / 180 * pi; double currentAngle = radianAngle + _rotationAnimation.value * (2 * pi); return Opacity( opacity: sin(currentAngle) < 0 ? 1 : 0, child: RotationTransition( turns: _rotationAnimation, child: Transform.translate( offset: Offset(_rotationRadius * cos(radianAngle), _rotationRadius * sin(radianAngle)), child: Image.asset( widget.assetPaths.elementAt(index), width: 60, height: 60, package: App.pkg, ), ), ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/spending_date_range.dart
import 'package:flutter/material.dart'; import 'chart/chart.dart'; import 'components/text_transition.dart'; import 'app_colors.dart'; class SpendingDateRange extends StatelessWidget { static const int startYear = 2018; final Chart chart; SpendingDateRange({this.chart}); @override Widget build(context) { const monthNames = <String>[ 'January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]; final range = chart.domainEnd - chart.domainStart; final start = chart.domainStart.ceil(); final startYearOffset = start ~/ 12; final startMonth = monthNames[start % 12]; final end = (chart.domainEnd - 0.1 * range).floor(); final endYearOffset = end ~/ 12; final endMonth = monthNames[end % 12]; final titleStyle = TextStyle( color: AppColors.colorText2, fontFamily: 'Lato', fontWeight: FontWeight.w200, fontSize: 13, ); final dateStyle = TextStyle( color: AppColors.colorText1, fontFamily: 'Lato', fontWeight: FontWeight.w200, fontSize: 14, ); return Padding( padding: EdgeInsets.only(bottom: 0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text('From', style: titleStyle), Padding(padding: EdgeInsets.all(3)), TextTransition( text: '${startYear + startYearOffset} $startMonth', textStyle: dateStyle, duration: Duration(milliseconds: 400), width: 120, ), ], ), Padding(padding: EdgeInsets.all(15)), Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text('To', style: titleStyle), Padding(padding: EdgeInsets.all(3)), TextTransition( text: '${startYear + endYearOffset} $endMonth', textStyle: dateStyle, duration: Duration(milliseconds: 400), width: 120, ), ], ), ], ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/spending_graph.dart
import 'package:flutter/material.dart'; import 'interact_notification.dart'; import 'components/scaling_info.dart'; import 'chart/chart.dart'; import 'chart/chart_painter.dart'; import 'chart/chart_background_painter.dart'; import 'globals.dart'; class SpendingGraph extends StatefulWidget { final Chart chart; SpendingGraph({this.chart}); @override State createState() => _SpendingGraphState(); } class _SpendingGraphState extends State<SpendingGraph> with SingleTickerProviderStateMixin { AnimationController _controller; double _startRange; @override void initState() { _controller = AnimationController(vsync: this, duration: Duration(milliseconds: 600), value: 1.0); _controller.addListener(() { setState(() {}); }); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(context) { final textStyle = TextStyle( color: Color(0xFFC4C8D9), fontSize: 12, fontFamily: 'Lato', fontWeight: FontWeight.w200, ); final labelStyle = TextStyle( color: Color(0xFFDCE2F5), fontFamily: 'Lato', fontSize: 10, ); final List<String> yAxisLabels = [ '\$8k', '\$6k', '\$4k', '\$2k', '0', ]; String label0Text, label1Text; double label0Y, label1Y; if (widget.chart.selectedDataPoint != -1) { label0Text = numberToPriceString((widget.chart.dataSets[0].values[widget.chart.selectedDataPoint] * 1000).round()); label1Text = numberToPriceString((widget.chart.dataSets[1].values[widget.chart.selectedDataPoint] * 1000).round()); label0Y = 150 * ScalingInfo.scaleY * (1.0 - widget.chart.selectedY(0)) + 10; label1Y = 150 * ScalingInfo.scaleY * (1.0 - widget.chart.selectedY(1)) + 10; // Resolve label intersection final d = label1Y - label0Y; if (d.abs() < 12) { label1Y += 24; } } final appSize = MediaQuery.of(context).size; return GestureDetector( onTapUp: (details) => _handleTap(appSize, details), onHorizontalDragStart: (_) => _handleStartInteract(context), onHorizontalDragUpdate: _handleDrag, onHorizontalDragEnd: (_) => _handleEndInteract(context), onScaleStart: (details) { _handleStartInteract(context); _handleStartZoom(details); }, onScaleUpdate: _handleZoom, onScaleEnd: (_) => _handleEndInteract(context), child: Container( //width: 320 * ScalingInfo.scaleX, height: 160 * ScalingInfo.scaleY, child: Stack( overflow: Overflow.visible, children: [ Container( width: appSize.width, height: 150 * ScalingInfo.scaleY, child: CustomPaint( painter: ChartBackgroundPainter(widget.chart), foregroundPainter: ChartPainter( widget.chart, _controller, [ Color(0x4C4AC3E5), Color(0x005290C7), Color(0x4CDEACD0), Color(0x00DEACD0), ], [ Color(0xFF4A78ED), Color(0xFF5DB391), Color(0xFFA74CBA), Color(0xFFF287A6), ], )), ), Positioned( left: 4, height: 150 * ScalingInfo.scaleY, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: yAxisLabels.map((label) => Text(label, style: textStyle)).toList(), ), ), Positioned( left: appSize.width - 24, height: 150 * ScalingInfo.scaleY, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: yAxisLabels.map((label) => Text(label, style: textStyle)).toList(), ), ), if (widget.chart.selectedDataPoint != -1) ...{ _buildLabel(appSize, label0Text, labelStyle, label0Y), _buildLabel(appSize, label1Text, labelStyle, label1Y), }, ], ), ), ); } Widget _buildLabel(Size appSize, String text, TextStyle style, double y) { return Positioned( left: appSize.width * widget.chart.selectedX() + 8, top: y, width: 40, child: Container( color: Color(0x99252B40).withOpacity(_controller.value < 0.6 ? _controller.value : 0.6), padding: EdgeInsets.all(4), child: Text(text, textAlign: TextAlign.center, style: style.copyWith(color: Color(0xFFDCE2F5).withOpacity(_controller.value))), ), ); } void _handleTap(Size appSize, TapUpDetails details) { final x = (details.localPosition.dx - 28) / appSize.width; final offset = lerp(widget.chart.domainStart, widget.chart.domainEnd, x); if (offset.round() != widget.chart.selectedDataPoint) { widget.chart.selectedDataPoint = offset.round(); _controller.forward(from: 0.0); } } void _handleStartInteract(BuildContext context) { InteractNotification(false)..dispatch(context); } void _handleEndInteract(BuildContext context) { InteractNotification(true)..dispatch(context); } void _handleStartZoom(ScaleStartDetails details) { _startRange = widget.chart.domainEnd - widget.chart.domainStart; } void _handleZoom(ScaleUpdateDetails details) { double d = 1.0 / details.scale; if (d == 0) return; final targetRange = _startRange * d; final range = widget.chart.domainEnd - widget.chart.domainStart; final scale = targetRange - range; if (range + scale < 13.0) { if (widget.chart.domainEnd != widget.chart.maxDomain) { widget.chart.domainEnd += scale; } else { widget.chart.domainStart -= scale; } } _controller.reverse(); } void _handleDrag(DragUpdateDetails details) { final d = -details.primaryDelta / 200 * (widget.chart.domainEnd - widget.chart.domainStart); if (widget.chart.domainStart + d < 0 || widget.chart.domainEnd + d >= widget.chart.maxDomain) return; if (d < 0) { widget.chart.domainStart += d; widget.chart.domainEnd += d; } else { widget.chart.domainEnd += d; widget.chart.domainStart += d; } _controller.reverse(); } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/interact_notification.dart
import 'package:flutter/material.dart'; class InteractNotification extends Notification { final bool end; InteractNotification(this.end); }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/globals.dart
double lerp(double x, double y, double s) { return x * (1 - s) + y * s; } String numberToPriceString(num value) { return value.toString().replaceAllMapped(new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'), (Match m) => '${m[1]},'); }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/app_colors.dart
import 'package:flutter/material.dart'; class AppColors { static final Color colorBg0 = Color(0xFF252B40); static final Color colorBg1 = Color(0xFF313852); static final Color colorAccent0 = Color(0xFF4A78ED); static final Color colorAccent1 = Color(0xFF4C5780); static final Color colorText0 = Color(0xFFC3C8D9); static final Color colorText1 = Color(0xFFDCE2F5); static final Color colorText2 = Color(0xFF98A7D9); static final Color colorText3 = Color(0xFF67ABDF); }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/demo_data.dart
import 'chart/chart_data_set.dart'; class ChartData { ChartDataSet dataSet1 = ChartDataSet( [7.0, 7.2, 7.3, 7.0, 6.5, 6.8, 7.1, 6.8, 7.0, 7.0, 7.0, 7.1, 6.8, 6.8, 7.0, 7.0, 7.0, 7.1, 7.1, 7.2, 7.2]); ChartDataSet dataSet2 = ChartDataSet( [5.8, 5.0, 5.0, 4.5, 4.6, 4.7, 5.6, 5.2, 4.6, 4.7, 4.6, 4.7, 4.6, 4.5, 4.5, 5.2, 5.1, 5.0, 5.0, 4.6, 4.7]); }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/spending_category_list.dart
import 'dart:math' as math; import 'package:flutter/material.dart'; import 'chart/chart.dart'; import 'components/scaling_info.dart'; import 'app_colors.dart'; import 'components/circle_percentage_widget.dart'; class SpendingCategoryList extends StatefulWidget { final Listenable updateNotifier; SpendingCategoryList({this.updateNotifier}); @override State createState() => _SpendingCategoryListState(); } class _SpendingCategoryListState extends State<SpendingCategoryList> { int _currentStart = 0; @override void initState() { widget.updateNotifier?.addListener(() { if (widget.updateNotifier is Chart) { if ((widget.updateNotifier as Chart).domainStart.round() != _currentStart) { setState(() { _currentStart = (widget.updateNotifier as Chart).domainStart.round(); }); } } }); super.initState(); } @override Widget build(context) { final rng = math.Random(); double percent0 = rng.nextDouble(); double percent1 = rng.nextDouble(); double percent2 = rng.nextDouble(); double sum = percent0 + percent1 + percent2; percent0 /= sum; percent1 /= sum; percent2 /= sum; return Container( height: 120 * ScalingInfo.scaleY, color: AppColors.colorBg1, child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text( 'EXPENSE CATEGORIES', style: TextStyle( color: Colors.white, fontFamily: 'Lato', fontWeight: FontWeight.bold, fontSize: 13, ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ CirclePercentageWidget( title: 'Bills', percent: percent0, color0: Color(0xFFA577E4), color1: Color(0xFF775F99), ), CirclePercentageWidget( title: 'Personal', percent: percent1, color0: Color(0xFF8DE4CA), color1: Color(0xFF509983), ), CirclePercentageWidget( title: 'Restaurants', percent: percent2, color0: Color(0xFFE38C8C), color1: Color(0xFF995E5E), ), ], ), ], ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/main.dart
import 'package:flutter/material.dart'; import 'package:shared/env.dart'; import './demo.dart'; void main() => runApp(App()); class App extends StatelessWidget { static final String _pkg = 'spending_tracker'; static String get pkg => Env.getPackage(_pkg); static String get bundle => Env.getBundle(_pkg); @override Widget build(BuildContext context) { return MaterialApp( home: SpendingTrackerDemo(), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/demo.dart
import 'package:flutter/material.dart'; import 'package:spending_tracker/spending_income_expenses_header.dart'; import 'app_colors.dart'; import 'chart/chart.dart'; import 'components/scaling_info.dart'; import 'demo_data.dart'; import 'interact_notification.dart'; import 'spending_app_bar.dart'; import 'spending_category_list.dart'; import 'spending_date_range.dart'; import 'spending_graph.dart'; class SpendingTrackerDemo extends StatefulWidget { @override _SpendingTrackerDemoState createState() => _SpendingTrackerDemoState(); } class _SpendingTrackerDemoState extends State<SpendingTrackerDemo> with SingleTickerProviderStateMixin { AnimationController _controller; Chart _chart; @override void initState() { var data = ChartData(); _chart = Chart([data.dataSet1, data.dataSet2], '', '\$'); _chart.domainStart = 0; _chart.domainEnd = 13; _chart.rangeStart = 0; _chart.rangeEnd = 8; _chart.selectedDataPoint = 4; _chart.addListener(() => setState(() {})); _controller = AnimationController(vsync: this, duration: Duration(milliseconds: 12000), upperBound: _chart.maxDomain); _controller.addListener(() { final d = _controller.value - _chart.domainStart; if (d < 0) { _chart.domainStart += d; _chart.domainEnd += d; } else { _chart.domainEnd += d; _chart.domainStart += d; } }); super.initState(); } @override Widget build(context) { if (!ScalingInfo.initialized) { ScalingInfo.init(context); } return Scaffold( appBar: SpendingAppBar(), body: Container( color: AppColors.colorBg0, child: Column( children: [ NotificationListener<InteractNotification>( onNotification: _handleInteract, child: Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ //Top area with text fields and incom/expense summary SpendingIncomeExpensesHeader(chart: _chart), Flexible( child: SingleChildScrollView( child: Column( children: <Widget>[ SpendingGraph(chart: _chart), SizedBox(height: 24), SpendingDateRange(chart: _chart), ], ), ), ) ], ), ), ), SpendingCategoryList(updateNotifier: _chart), ], ), )); } bool _handleInteract(InteractNotification notification) { if (notification.end) { _controller.value = _chart.domainStart; double target = _chart.domainStart.round().toDouble(); _controller.animateTo(target, curve: Curves.easeIn); } else { //_controller.stop(); } return false; } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/spending_app_bar.dart
import 'package:flutter/material.dart'; import 'app_colors.dart'; import 'components/header_row.dart'; import 'components/profile_icon.dart'; class SpendingAppBar extends StatelessWidget with PreferredSizeWidget { SpendingAppBar({Key key}) : super(key: key); @override Widget build(context) { return Container( height: preferredSize.height, color: AppColors.colorBg1, child: SafeArea( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: EdgeInsets.symmetric(vertical: 8, horizontal: 18), child: Icon( Icons.menu, color: Colors.white, size: 28, ), ), HeaderRow(), ProfileIcon(), ], ), ), ); } Size get preferredSize => Size(double.infinity, 88); } class Foo extends StatelessWidget { @override Widget build(BuildContext context) { return Container(); } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/spending_income_expenses_header.dart
import 'package:flutter/material.dart'; import 'chart/chart.dart'; import 'components/text_transition.dart'; import 'globals.dart'; import 'app_colors.dart'; class SpendingIncomeExpensesHeader extends StatelessWidget { final Chart chart; SpendingIncomeExpensesHeader({this.chart}); @override Widget build(context) { final start = chart.domainStart.round(); final end = chart.domainEnd.round(); final values0 = chart.dataSets[0].values.sublist(start, end); final values1 = chart.dataSets[1].values.sublist(start, end); final sum0 = values0.fold(0, (a, b) => a + b) * 1000; final sum1 = values1.fold(0, (a, b) => a + b) * 1000; return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ _SummaryColumn( title: 'Income', colors: [ Color(0xFF4A78ED), Color(0xFF5DB391), ], sum: sum0.round(), mean: (sum0 / values0.length).round()), Padding(padding: EdgeInsets.all(8)), Container(width: 1, height: 32, color: AppColors.colorAccent1), Padding(padding: EdgeInsets.all(8)), _SummaryColumn( title: 'Expense', colors: [ Color(0xFFA74CBA), Color(0xFFF287A6), ], sum: sum1.round(), mean: (sum1 / values1.length).round()), ], ); } } class _SummaryColumn extends StatelessWidget { final String title; final List<Color> colors; final int sum; final int mean; _SummaryColumn({this.title, this.colors, this.sum, this.mean}); @override Widget build(context) { return Column(children: [ Row(children: [ Container( width: 8, height: 8, margin: EdgeInsets.only(right: 8), decoration: BoxDecoration( gradient: LinearGradient(colors: colors), ), ), Text( title, style: TextStyle( color: AppColors.colorText2, fontFamily: 'Lato', fontWeight: FontWeight.w200, fontSize: 11, ), ), ]), Padding(padding: EdgeInsets.all(2)), TextTransition( text: '\$${numberToPriceString(sum)}', textStyle: TextStyle( color: AppColors.colorText1, fontFamily: 'Lato', fontWeight: FontWeight.w200, fontSize: 19, letterSpacing: 0.7, ), duration: Duration(milliseconds: 400), ), Padding(padding: EdgeInsets.all(4)), Text( 'Monthly Average: \$${numberToPriceString(mean)}', style: TextStyle( color: AppColors.colorText1, fontFamily: 'Lato', fontWeight: FontWeight.w200, fontSize: 8, ), ), ]); } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/components/circle_percentage_painter.dart
import 'dart:math' as math; import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'scaling_info.dart'; class SpendingCategoryChartPainter extends CustomPainter { final double percent; final Color color0; final Color color1; SpendingCategoryChartPainter(this.percent, this.color0, this.color1); @override void paint(canvas, size) { final paint = Paint(); paint.color = Color(0xFF5B668C); paint.style = PaintingStyle.stroke; paint.strokeWidth = 5 * ScalingInfo.scaleY; paint.strokeCap = StrokeCap.square; canvas.drawArc(Rect.fromLTWH(0, 0, size.width, size.height), 0, math.pi * 2, false, paint); paint.shader = ui.Gradient.linear(Offset.zero, Offset(0, size.height), [color0, color1]); canvas.drawArc(Rect.fromLTWH(0, 0, size.width, size.height), -math.pi / 2, -2 * math.pi * percent, false, paint); } @override bool shouldRepaint(SpendingCategoryChartPainter oldCategory) { return percent != oldCategory.percent || color0 != oldCategory.color0 || color1 != oldCategory.color1; } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/components/header_row.dart
import 'package:flutter/material.dart'; import '../app_colors.dart'; class HeaderRow extends StatelessWidget { @override Widget build(context) { return Container( width: 140, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text("Budget", style: TextStyle(color: Colors.white, fontSize: 17, fontFamily: 'TitilliumWeb')), Text("Tracker", style: TextStyle(color: AppColors.colorText3, fontSize: 17, fontFamily: 'TitilliumWeb')), ], ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/components/profile_icon.dart
import 'package:flutter/material.dart'; import 'package:spending_tracker/main.dart'; class ProfileIcon extends StatelessWidget { @override Widget build(context) { return Padding( padding: EdgeInsets.all(16), child: Image.asset('images/headshot.png', package: App.pkg), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/components/scaling_info.dart
import 'package:flutter/material.dart'; class ScalingInfo { static double scaleX; static double scaleY; static bool get initialized => scaleX != null; static void init(BuildContext context) { final queryData = MediaQuery.of(context); final appSize = queryData.size; scaleX = appSize.width / 320; scaleY = appSize.height / 480; if (scaleX > 2.0) { scaleX = 2.0; } } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/components/specific_rect_clipper.dart
import 'package:flutter/material.dart'; class SpecificRectClipper extends CustomClipper<Rect> { final Rect clipRect; SpecificRectClipper(this.clipRect); @override Rect getClip(Size size) { return clipRect; } @override bool shouldReclip(SpecificRectClipper oldClipper) { return clipRect != oldClipper.clipRect; } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/components/circle_percentage_widget.dart
import 'package:flutter/material.dart'; import 'scaling_info.dart'; import '../app_colors.dart'; import 'circle_percentage_painter.dart'; class CirclePercentageWidget extends StatefulWidget { final String title; final double percent; final Color color0; final Color color1; CirclePercentageWidget( {this.title = "", this.percent = 0.0, this.color0 = Colors.white, this.color1 = Colors.transparent}); @override State createState() => _CirclePercentageWidgetState(); } class _CirclePercentageWidgetState extends State<CirclePercentageWidget> with SingleTickerProviderStateMixin { AnimationController _controller; @override void initState() { _controller = AnimationController(vsync: this, duration: Duration(milliseconds: 2400)); _controller.addListener(() { setState(() {}); }); _controller.animateTo(widget.percent); super.initState(); } @override void dispose() { super.dispose(); } @override void didUpdateWidget(CirclePercentageWidget oldWidget) { if (oldWidget.percent != widget.percent) { _controller.animateTo(widget.percent); } super.didUpdateWidget(oldWidget); } @override Widget build(context) { final titleStyle = TextStyle( color: AppColors.colorText0, fontFamily: 'Lato', fontWeight: FontWeight.w200, fontSize: 14, ); final labelStyle = TextStyle( color: AppColors.colorText1, fontFamily: 'Lato', fontWeight: FontWeight.w200, fontSize: 14, ); return Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text(widget.title, style: titleStyle), Container( width: 42 * ScalingInfo.scaleY, height: 42 * ScalingInfo.scaleY, margin: EdgeInsets.all(12), child: CustomPaint( isComplex: false, painter: SpendingCategoryChartPainter(_controller.value, widget.color0, widget.color1), child: Center(child: Text('${(_controller.value * 100).toInt()}%', style: labelStyle)), ), ), ], ); } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/components/text_transition.dart
import 'package:flutter/material.dart'; class TextTransition extends StatefulWidget { final String text; final TextStyle textStyle; final Duration duration; final double width; TextTransition({this.text, this.textStyle, this.duration, this.width}); @override State createState() => _TextTransitionState(text); } class _TextTransitionState extends State<TextTransition> with SingleTickerProviderStateMixin { AnimationController _controller; String _string0; String _string1; _TextTransitionState(this._string0); @override void initState() { _controller = AnimationController(vsync: this, duration: widget.duration); _controller.addListener(() { setState(() {}); }); _controller.addStatusListener((status) { if (status == AnimationStatus.completed) { setState(() { _string0 = _string1; _string1 = null; _controller.reset(); }); } }); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override void didUpdateWidget(TextTransition oldWidget) { if (widget.text != oldWidget.text) { setState(() { _string1 = widget.text; _controller.forward(); }); } super.didUpdateWidget(oldWidget); } @override Widget build(context) { final double width = widget.width != null ? widget.width : _string0.length * widget.textStyle.fontSize / 1.4; return Container( width: width, height: widget.textStyle.fontSize * 1.2, child: Stack( children: [ Positioned( top: 0 - _controller.value * widget.textStyle.fontSize, width: width, child: Text( _string0, textAlign: TextAlign.center, style: widget.textStyle, ), ), if (_string1 != null) ...{ Positioned( top: widget.textStyle.fontSize - (_controller.value * widget.textStyle.fontSize), width: width, height: widget.textStyle.fontSize, child: Text( _string1, textAlign: TextAlign.center, style: widget.textStyle, ), ), }, ], ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/chart/chart_background_painter.dart
import 'package:flutter/material.dart'; import 'chart.dart'; class ChartBackgroundPainter extends CustomPainter { Chart _chart; ChartBackgroundPainter(Chart chart) : _chart = chart, super(repaint: chart); @override void paint(canvas, size) { const monthNames = <String>[ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]; final List<String> xAxisLabels = []; for (int i = _chart.domainStart.round(); i <= _chart.domainEnd.round(); ++i) { xAxisLabels.add(monthNames[i % 12]); } final double start = _chart.domainStart; final double end = _chart.domainEnd; for (int i = start.round(); i <= end.round(); ++i) { final x = (i.toDouble() - start.round()) / (end - start) * size.width + 28; canvas.drawLine( Offset(x + 0.5, 0), Offset(x, size.height), Paint() ..color = Color(0xFF3D4666) ..strokeWidth = 1.0); } canvas.clipRect(Rect.fromLTRB(16, size.height, size.width - 16, size.height + 24)); for (int i = start.round(); i <= end.round(); ++i) { final x = (i.toDouble() - start) / (end - start) * size.width + 28; final textPainter = TextPainter( text: TextSpan( text: xAxisLabels[i - start.round()], style: TextStyle( color: i == _chart.selectedDataPoint ? Color(0xFFC3C8D9) : Color(0xFFC4C8D9), fontFamily: 'Lato', fontWeight: i == _chart.selectedDataPoint ? FontWeight.bold : FontWeight.w200, fontSize: 12, ), ), textAlign: TextAlign.left, textDirection: TextDirection.ltr, )..layout(); textPainter.paint(canvas, Offset(x - 10, size.height + 10)); } } @override bool shouldRepaint(ChartBackgroundPainter oldPainter) { return false; } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/chart/chart.dart
import 'package:flutter/material.dart'; import 'chart_data_set.dart'; class Chart extends ChangeNotifier { List<ChartDataSet> _dataSets; double _domainStart, _domainEnd, _maxDomain; double _rangeStart, _rangeEnd; final String xAxisUnit; final String yAxisUnit; int _selectedDataPoint; Chart(List<ChartDataSet> dataSets, this.xAxisUnit, this.yAxisUnit) : _dataSets = dataSets, _domainStart = 0, _domainEnd = 0 { _maxDomain = double.maxFinite; for (var dataSet in _dataSets) { if (dataSet.values.length < _maxDomain) _maxDomain = dataSet.values.length.toDouble(); } _domainEnd = _maxDomain; _selectedDataPoint = -1; _rangeStart = min(); _rangeEnd = max(); } double min() { double result = double.maxFinite; for (var dataSet in _dataSets) for (var value in dataSet.values.sublist(_domainStart.round(), _domainEnd.round())) if (value < result) result = value; return result; } double max() { double result = 0; for (var dataSet in _dataSets) for (var value in dataSet.values.sublist(_domainStart.round(), _domainEnd.round())) if (value > result) result = value; return result; } double mean(int setIndex) { final values = _dataSets[setIndex].values.sublist(_domainStart.round(), _domainEnd.round()); return values.fold(0.0, (a, b) => a + b) / values.length; } double median(int setIndex) { assert(setIndex >= 0 && setIndex < _dataSets.length); final sortedValues = _dataSets[setIndex].values.sublist(_domainStart.round(), _domainEnd.round())..sort(); double result; if (sortedValues.length < 2) { result = sortedValues[0]; } else { final int mid = sortedValues.length ~/ 2; result = sortedValues[mid]; if (sortedValues.length & 1 == 0) { result += sortedValues[mid - 1]; result /= 2; } } return result; } set domainStart(double domainStart) { if (domainStart == _domainStart) return; _domainStart = domainStart.clamp(0, _domainEnd - 1.2); notifyListeners(); } set domainEnd(double domainEnd) { if (domainEnd == _domainEnd) return; _domainEnd = domainEnd.clamp(_domainStart + 1.2, _maxDomain); notifyListeners(); } set rangeStart(double rangeStart) { if (rangeStart < _rangeEnd) { _rangeStart = rangeStart; notifyListeners(); } } set rangeEnd(double rangeEnd) { if (rangeEnd > _rangeStart) { _rangeEnd = rangeEnd; notifyListeners(); } } set selectedDataPoint(int index) { if (index >= 0 && index < _maxDomain) { _selectedDataPoint = index; notifyListeners(); } } double get domainStart => _domainStart; double get domainEnd => _domainEnd; double get maxDomain => _maxDomain; double get rangeStart => _rangeStart; double get rangeEnd => _rangeEnd; List<ChartDataSet> get dataSets => _dataSets; int get selectedDataPoint => _selectedDataPoint; double selectedX() { if (_selectedDataPoint == -1) return 0; final range = _domainEnd - _domainStart; final x = ((_selectedDataPoint.toDouble() - _domainStart) / range); return x; } double selectedY(int dataSetIndex) { if (_selectedDataPoint == -1) return 0; final y = ((_dataSets[dataSetIndex].values[_selectedDataPoint] - rangeStart) / rangeEnd); return y; } }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/chart/chart_data_set.dart
class ChartDataSet { List<double> _values; ChartDataSet(List<double> values) : _values = values; List<double> valuesInDomain(double domainStart, double domainEnd) { final start = domainStart < 0 ? 0 : domainStart; final end = domainEnd > _values.length ? _values.length : domainEnd; if (end <= start) { return <double>[]; } return _values.sublist(start.round(), end.round()); } List<double> get values => _values; }
0
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib
mirrored_repositories/flutter_showcase/example/apps/spending_tracker/lib/chart/chart_painter.dart
import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'chart.dart'; import '../globals.dart'; class ChartPainter extends CustomPainter { Chart _chart; Animation<double> _selectedFade; List<Color> _backgroundColors; List<Color> _foregroundColors; ChartPainter(Chart chart, Animation<double> selectedFade, List<Color> backgroundColors, List<Color> foregroundColors) : _chart = chart, _selectedFade = selectedFade, _backgroundColors = backgroundColors, _foregroundColors = foregroundColors, super(repaint: Listenable.merge([chart, selectedFade])); double dataY(List<double> values, int index) { final y = ((values[index] - _chart.rangeStart) / _chart.rangeEnd); return y; } void paintChartData(Chart chart, int dataSetIndex, List<Color> backgroundColors, List<Color> foregroundColors, ui.Canvas canvas, Size size) { final range = chart.domainEnd - chart.domainStart; final dataOffset = (int index) { final x = ((index.toDouble() - chart.domainStart) / range) * size.width + 28; final y = dataY(chart.dataSets[dataSetIndex].values, index) * size.height; return Offset(x, y); }; final path = Path(); final start = chart.domainStart; final end = chart.domainEnd; Offset offset0; if (start.floor() > 0) { offset0 = dataOffset(start.floor() - 1); path.moveTo(offset0.dx, offset0.dy); } else { offset0 = dataOffset(0); path.moveTo(0, offset0.dy); } for (int i = start.floor(); i < end.ceil(); ++i) { var offset1 = dataOffset(i); path.cubicTo(lerp(offset0.dx, offset1.dx, 0.5), offset0.dy, lerp(offset0.dx, offset1.dx, 0.5), offset1.dy, offset1.dx, offset1.dy); offset0 = offset1; } if (end.ceil() < chart.maxDomain.floor()) { var offset1 = dataOffset(end.ceil()); path.cubicTo(lerp(offset0.dx, offset1.dx, 0.5), offset0.dy, lerp(offset0.dx, offset1.dx, 0.5), offset1.dy, offset1.dx, offset1.dy); offset0 = offset1; } else { var offset1 = dataOffset(end.ceil() - 1); path.lineTo(size.width, offset1.dy); offset0 = offset1; } canvas.drawPath( path, Paint() ..style = PaintingStyle.stroke ..strokeWidth = 4 ..shader = ui.Gradient.linear( Offset(0, 0), Offset(size.width, 0), foregroundColors, )); path.lineTo(size.width, 0); path.lineTo(0, 0); offset0 = dataOffset(0); path.lineTo(0, offset0.dy); canvas.drawPath( path, Paint() ..style = PaintingStyle.fill ..shader = ui.Gradient.linear( Offset(0, size.height), Offset(0, 0), backgroundColors, [ 0.5, 1.0, ], )); } @override void paint(canvas, size) { canvas.translate(0.0, size.height); canvas.scale(1.0, -1.0); for (int i = 0; i < _chart.dataSets.length; ++i) { paintChartData(_chart, i, _backgroundColors.sublist(i * 2, i * 2 + 2), _foregroundColors.sublist(i * 2, i * 2 + 2), canvas, size); } if (_chart.selectedDataPoint != -1) { double maxY = 0; for (var dataSet in _chart.dataSets) { final y = dataY(dataSet.values, _chart.selectedDataPoint); if (y > maxY) maxY = y; } final range = _chart.domainEnd - _chart.domainStart; final x = ((_chart.selectedDataPoint.toDouble() - _chart.domainStart) / range) * size.width + 28; canvas.drawLine( Offset(x, 0), Offset(x, maxY * size.height), Paint()..color = Colors.white.withOpacity(_selectedFade.value)); for (var dataSet in _chart.dataSets) { final y = dataY(dataSet.values, _chart.selectedDataPoint); final offset = Offset(x, y * size.height); canvas.drawCircle( offset, 12.0, Paint() ..blendMode = BlendMode.plus ..shader = ui.Gradient.radial( offset, 12.0, [Colors.white.withOpacity(_selectedFade.value), Colors.transparent], )); canvas.drawCircle(offset, 4.8, Paint()..color = Colors.white.withOpacity(_selectedFade.value)); } } } @override bool shouldRepaint(ChartPainter oldPainter) { return true; } }
0
mirrored_repositories/flutter_showcase/example/apps/constellations_list
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib/constellation_title_card.dart
import 'demo_data.dart'; import 'main.dart'; import 'styles.dart'; import 'package:flutter/material.dart'; class ConstellationTitleCard extends StatelessWidget { final ConstellationData data; final bool redMode; const ConstellationTitleCard({Key key, this.data, this.redMode}) : super(key: key); @override Widget build(BuildContext context) { //Create paint for our text var color = redMode ? Color(0xffcd4b4b) : Colors.white; var paint = Paint()..color = color; if (redMode) { paint.style = PaintingStyle.stroke; paint.strokeWidth = 1; } //Need to wrap the title with spaces, to prevent a flicker during the Hero animation. known issue: https://github.com/flutter/flutter/issues/42988 var titleText = Text(" ${data.title} ", style: TextStyle(fontSize: 42, fontFamily: Fonts.Title, foreground: paint, height: 1.3, package: App.pkg)); var subTitleText = Text("${data.subTitle}", style: TextStyle(fontSize: 16, fontFamily: Fonts.Content, color: color, package: App.pkg)); return Hero( tag: "${data.title}${data.key}", //Need to wrap hero content in a Material so we don't lose text styling while hero is animating. Known issue: https://github.com/flutter/flutter/issues/30647#issuecomment-509712719 child: Material( color: Colors.transparent, child: Column( children: <Widget>[ titleText, subTitleText ], )), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/constellations_list
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib/styles.dart
class Fonts { static const String Content = "Montserrat"; static const String Title = "DMSerif"; static const String Header = "Playfair"; }
0
mirrored_repositories/flutter_showcase/example/apps/constellations_list
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib/demo_data.dart
import 'package:flutter/material.dart'; class ConstellationData { final String title; final String subTitle; final String image; final UniqueKey key = UniqueKey(); ConstellationData(this.title, this.subTitle, this.image); } class DemoData { static final List<ConstellationData> _constellations = [ ConstellationData("Aries", "The Ram", "Aries"), ConstellationData("Cassiopeia", "The Queen", "Cassiopeia"), ConstellationData("Camelopardalis", "The Giraffe", "Camelopardalis"), ConstellationData("Cetus", "The Whale", "Cetus"), ConstellationData("Pisces", "The Fishes", "Pisces"), ConstellationData("Aries", "The Ram", "Aries"), ConstellationData("Cassiopeia", "The Queen", "Cassiopeia"), ConstellationData("Camelopardalis", "The Giraffe", "Camelopardalis"), ConstellationData("Cetus", "The Whale", "Cetus"), ConstellationData("Pisces", "The Fishes", "Pisces"), ConstellationData("Aries", "The Ram", "Aries"), ConstellationData("Cassiopeia", "The Queen", "Cassiopeia"), ConstellationData("Camelopardalis", "The Giraffe", "Camelopardalis"), ConstellationData("Cetus", "The Whale", "Cetus"), ConstellationData("Pisces", "The Fishes", "Pisces"), ]; List<ConstellationData> getConstellations() => _constellations; }
0
mirrored_repositories/flutter_showcase/example/apps/constellations_list
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib/constellation_list_renderer.dart
import 'dart:math'; import 'demo_data.dart'; import 'constellation_title_card.dart'; import 'package:flutter/material.dart'; class ConstellationListRenderer extends StatefulWidget { final ConstellationData data; final bool redMode; final Function(ConstellationData, bool) onTap; final double hzPadding; const ConstellationListRenderer({Key key, this.data, this.redMode = false, this.onTap, this.hzPadding = 0}) : super(key: key); @override _ConstellationListRendererState createState() => _ConstellationListRendererState(); } class _ConstellationListRendererState extends State<ConstellationListRenderer> { @override Widget build(BuildContext context) { double leftPadding = widget.redMode ? 0 : widget.hzPadding; double rightPadding = widget.redMode ? widget.hzPadding : 0; double vtPadding = 24; return GestureDetector( onTap: () => _handleTap(), child: Transform.translate( offset: Offset(widget.redMode? 25 : -25, 0), child: Container( padding: EdgeInsets.only(top: vtPadding, bottom: vtPadding, left: leftPadding, right: rightPadding), alignment: widget.redMode ? Alignment.centerRight : Alignment.centerLeft, child: ConstellationTitleCard( data: widget.data, redMode: widget.redMode, ), ), ), ); } void _handleTap() { if(widget.onTap != null){ widget.onTap(widget.data, widget.redMode); } } }
0
mirrored_repositories/flutter_showcase/example/apps/constellations_list
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib/constellation_detail_view.dart
import 'main.dart'; import 'demo_data.dart'; import 'constellation_title_card.dart'; import 'styles.dart'; import 'package:flutter/material.dart'; class ConstellationDetailView extends StatefulWidget { static const route = "ConstellationDetailView"; final ConstellationData data; final bool redMode; final int contentDelay; final Function onBackTap; const ConstellationDetailView({Key key, this.data, this.redMode, this.contentDelay = 1000, @required this.onBackTap}) : super(key: key); @override _ConstellationDetailViewState createState() => _ConstellationDetailViewState(); } class _ConstellationDetailViewState extends State<ConstellationDetailView> with SingleTickerProviderStateMixin { AnimationController _animController; Animation<double> _contentScaleTween; Animation<double> _textAlphaTween; @override void initState() { _animController = AnimationController(vsync: this, duration: Duration(milliseconds: widget.contentDelay)) ..addListener(() { setState(() {}); }); _contentScaleTween = Tween<double>(begin: 0, end: 1).animate( CurvedAnimation(parent: _animController, curve: Interval(.4, .8, curve: Curves.easeOutQuad)), ); _textAlphaTween = Tween<double>(begin: 0, end: 1).animate( CurvedAnimation(parent: _animController, curve: Interval(.6, 1, curve: Curves.easeOutQuad)), ); _animController.forward(from: 0); super.initState(); } @override void dispose() { _animController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Container( alignment: Alignment.topCenter, padding: EdgeInsets.only(top: 24), child: Column( children: <Widget>[ ConstellationTitleCard( data: widget.data, redMode: widget.redMode, ), Expanded( child: Transform.scale( scale: _contentScaleTween.value, child: Stack( children: <Widget>[ Image.asset("images/${widget.data.image}-Constellation@2x.png", filterQuality: FilterQuality.high, package: App.pkg, ), Opacity( opacity: _textAlphaTween.value, child: Image.asset("images/${widget.data.image}-Text@2x.png", fit: BoxFit.contain, package: App.pkg), ), ], ), ), ), RaisedButton( padding: EdgeInsets.symmetric(horizontal: 48, vertical: 12), splashColor: Colors.white24, color: Colors.black, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40), side: BorderSide(color: Color(0xffc9c9c9))), //Dispatch our tap event to the parent of this widget, and let them handle it. onPressed: () => widget.onBackTap(), child: Text("Return to List", style: TextStyle(fontFamily: Fonts.Content, color: Colors.white, package: App.pkg)), ), SizedBox( height: 36, ) ], )); } }
0
mirrored_repositories/flutter_showcase/example/apps/constellations_list
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:shared/env.dart'; import 'demo.dart'; void main() => runApp(App()); class App extends StatelessWidget { static String _pkg = "constellations_list"; static String get pkg => Env.getPackage(_pkg); static String get bundle => Env.getBundle(_pkg); @override Widget build(BuildContext context) { SystemChrome.setEnabledSystemUIOverlays(const []); return MaterialApp( home: ConstellationsListDemo(), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/constellations_list
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib/demo.dart
import 'demo_data.dart'; import 'constellation_detail_view.dart'; import 'star_field/star_field.dart'; import 'widgets/fade_route_builder.dart'; import 'widgets/nested_navigator.dart'; import 'constellation_list_view.dart'; import 'package:flutter/material.dart'; class ConstellationsListDemo extends StatefulWidget { @override _ConstellationsListDemoState createState() => _ConstellationsListDemoState(); } class _ConstellationsListDemoState extends State<ConstellationsListDemo> with TickerProviderStateMixin { static const double idleSpeed = .2; static const double maxSpeed = 10; static const int starAnimDurationIn = 4500; //double _speed = idleSpeed; GlobalKey<NavigatorState> _navigationStackKey = GlobalKey<NavigatorState>(); ValueNotifier<double> _speedValue = ValueNotifier(idleSpeed); AnimationController _starAnimController; Animation<double> _starAnimSequence; List<ConstellationData> _constellationsData; @override void initState() { _constellationsData = DemoData().getConstellations(); _starAnimController = AnimationController( vsync: this, duration: Duration(milliseconds: starAnimDurationIn), reverseDuration: Duration(milliseconds: starAnimDurationIn ~/ 3), ); _starAnimController.addListener(() { _speedValue.value = _starAnimSequence.value; }); //Create an animation sequence that moves our stars back, then forwards, then to rest at 0. //This will be played each time we load a detail page, to create a flying through space transition effect _starAnimSequence = TweenSequence([ TweenSequenceItem<double>( tween: Tween<double>(begin: idleSpeed, end: -2).chain(CurveTween(curve: Curves.easeOut)), weight: 20.0, ), TweenSequenceItem<double>( tween: Tween<double>(begin: -2, end: 20).chain(CurveTween(curve: Curves.easeOut)), weight: 30.0, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 20, end: 0).chain(CurveTween(curve: Curves.easeOut)), weight: 50.0, ) ]).animate(_starAnimController); super.initState(); } @override void dispose() { _starAnimController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { int starCount = 400; //The main content for the app is a Stack, with the StarField as a constant background element, and a Nested Navigator to handle content transitions return Scaffold( body: Stack( children: <Widget>[ //Wrap stars in a ValueListenableBuilder so it will get rebuilt whenever the _speedValue changes ValueListenableBuilder<double>( valueListenable: _speedValue, builder: (context, value, child) { //Scrolling star background return StarField(starSpeed: value, starCount: starCount ); }, ), //Main content SafeArea( child: NestedNavigator( //Need to assign a key to our navigator, so we can pop/push it later navKey: _navigationStackKey, routeBuilder: _buildPageRoute, //When nested navigator has been popped, reverse the star anim back to start onBackPop: _reverseStarAnim, ), ), ], ), ); } //Create a PageRoute to handle the new page transition Route _buildPageRoute(RouteSettings route) { Widget page; //DetailView if (route.name == ConstellationDetailView.route) { //Get the data for the new view from the .arguments property var args = route.arguments as _DetailViewRouteArguments; page = ConstellationDetailView( data: args.data, redMode: args.redMode, //Pass a time value into the content view, so it knows how long to delay the fadeIn. This allows us to choreograph the star animation, with the page content, without a direct dependency contentDelay: starAnimDurationIn + 1000, //When the back button is tapped in the detail view, pop the nested navigator and reverse the animation controller for the stars onBackTap: (){ _navigationStackKey.currentState.pop(); _reverseStarAnim(); } ); } //Default to ListView as our home route else { page = ConstellationListView( constellations: _constellationsData, onItemTap: _handleListItemTap, onScrolled: _handleListScroll, ); } //Use a FadeRouteBuilder which fades the new view in, while fading the old page out. Necessary as the content pages have transparent backgrounds. return FadeRouteBuilder(page: page); } //When the list is scrolled, use it's velocity to control the speed of the starfield void _handleListScroll(delta) { setState(() { if (delta == 0) { _speedValue.value = idleSpeed; //If we've stopped scrolling, revert to the idle speed } else { _speedValue.value = delta.clamp(-maxSpeed, maxSpeed); //clamp scrollDelta to min/max values } }); } //When an item in the list is tapped, push a Detail view onto the navigator. Pass along the data as as route argument. void _handleListItemTap(ConstellationData data, bool redMode) { //Add details page to Navigator _navigationStackKey.currentState.pushNamed( ConstellationDetailView.route, arguments: _DetailViewRouteArguments(data, redMode), ); //Start star transition _starAnimController.forward(from: 0); } void _reverseStarAnim() { if (_starAnimController.isAnimating) { _starAnimController.reverse(); } else { _speedValue.value = idleSpeed; } } } class _DetailViewRouteArguments { final ConstellationData data; final bool redMode; _DetailViewRouteArguments(this.data, this.redMode); }
0
mirrored_repositories/flutter_showcase/example/apps/constellations_list
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib/constellation_list_view.dart
import 'dart:math'; import 'demo_data.dart'; import 'constellation_list_renderer.dart'; import 'main.dart'; import 'styles.dart'; import 'package:flutter/material.dart'; class ConstellationListView extends StatefulWidget { static const route = "ConstellationListView"; final List<ConstellationData> constellations; final void Function(double) onScrolled; final void Function(ConstellationData, bool) onItemTap; const ConstellationListView({Key key, this.onScrolled, this.onItemTap, @required this.constellations}) : super(key: key); @override _ConstellationListViewState createState() => _ConstellationListViewState(); } class _ConstellationListViewState extends State<ConstellationListView> { double _prevScrollPos = 0; double _scrollVel = 0; @override Widget build(BuildContext context) { //Build list using data return Align( child: Container( width: 600, child: Stack( children: [ //Scrolling list, draw this first so it's under the other content _buildScrollingList(), //Cover the list with black gradients on top & bottom _buildGradientOverlay(), //Top left text _buildHeaderText(), //Top right text _buildLocationText() ], ), ), ); } Container _buildScrollingList() { var data = widget.constellations; //Seed our random number generator, so the padding is always consistent between runs (Designers are picky!) var rand = Random(1); return Container( //Wrap list in a NotificationListener, so we can detect scroll updates child: NotificationListener<ScrollNotification>( onNotification: _handleScrollNotification, child: ListView.builder( physics: BouncingScrollPhysics(), itemCount: data.length, //Add some extra padding to the top & bottom of the list padding: EdgeInsets.only(top: 150, bottom: 200), itemBuilder: (context, index) { //Calculate random padding for each renderer as per the design. Design requested that the first item is not random, all others are double padding = (index == 0) ? 20 : rand.nextInt(4) * 20.0; //Create the list renderer, injecting it with some ConstellationData return ConstellationListRenderer( //Re-dispatch our tap event to anyone who is listening onTap: widget.onItemTap, redMode: index % 2 == 1, data: data[index], hzPadding: padding, ); }, ), ), ); } Widget _buildHeaderText() { return Positioned( width: 180, left: 16, top: 16, child: Text( "GUIDE TO THE STARS", style: TextStyle(color: Colors.white, fontSize: 28, fontFamily: Fonts.Header, height: 1.05, package: App.pkg), ), ); } Widget _buildGradientOverlay() { double firstGradientStop = .2; return IgnorePointer( child: Container( decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.black, Color(0x0), Color(0x0), Colors.black], stops: [0, firstGradientStop, 1 - firstGradientStop, 1], begin: Alignment.topCenter, end: Alignment.bottomCenter)), ), ); } Positioned _buildLocationText() { return Positioned( width: 120, right: 16, top: 12, child: Text( "New York City (USA, NY) 40.71 °N - 74.01 °W", textAlign: TextAlign.right, style: TextStyle(color: Colors.grey, fontSize: 10, fontFamily: Fonts.Content, height: 1.8, package: App.pkg), ), ); } bool _handleScrollNotification(ScrollNotification notification) { //Determine scrollVelocity and dispatch it to any listeners _scrollVel = notification.metrics.pixels - _prevScrollPos; if (widget.onScrolled != null) { widget.onScrolled(_scrollVel); } //print(notification.metrics.pixels - _prevScroll); _prevScrollPos = notification.metrics.pixels; //Return true to cancel the notification bubbling, we've handled it here. return true; } }
0
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib/widgets/nested_navigator.dart
import 'package:flutter/material.dart'; class NestedNavigator extends StatefulWidget { final Route Function(RouteSettings route) routeBuilder; final GlobalKey<NavigatorState> navKey; final Function onBackPop; const NestedNavigator({Key key, this.routeBuilder, this.navKey, this.onBackPop}) : super(key: key); @override _NestedNavigatorState createState() => _NestedNavigatorState(); } class _NestedNavigatorState extends State<NestedNavigator> { @override Widget build(BuildContext context) { //Wrap navigator in a WillPop widget, so we can intercept the hardware back button event return WillPopScope( onWillPop: () async { var navigator = widget.navKey.currentState; if (navigator.canPop()) { if(widget.onBackPop != null) widget.onBackPop(); return false; } return true; }, child: Navigator( key: widget.navKey, //Generate a page, in response to a route request onGenerateRoute: (routeSettings) => widget.routeBuilder(routeSettings), //In order for the nested-navigator to handle hero animations, we must pass it an Observer of type HeroController observers: [ HeroController( //Optional: Use a nice arc'd tween instead of the default linear createRectTween: (begin, end) => MaterialRectArcTween(begin: begin, end: end), ) ], ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib/widgets/fade_route_builder.dart
import 'package:flutter/material.dart'; class FadeRouteBuilder extends PageRouteBuilder { final Widget page; final int duration; FadeRouteBuilder({this.page, this.duration=1000}) : super( transitionDuration: Duration(milliseconds: duration), //Page builder doesn't do anything special, just return the page we were passed in. pageBuilder: (context, animation, secondaryAnimation) => page, //transitionsBuilder builds 2 nested transitions, one for transitionIn (animation), and one for transitionOut (secondaryAnimation) transitionsBuilder: (context, animation, secondaryAnimation, child) { return FadeTransition( //Transition from 0 - 1 when coming on the screen opacity: Tween<double>(begin: 0, end: 1).animate(animation), child: FadeTransition( //Transition from 1 to 0 when leaving the screen opacity: Tween<double>(begin: 1, end: 0).animate(secondaryAnimation), child: child, )); }, ); }
0
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib/star_field/star_field.dart
import 'dart:math'; import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import '../main.dart'; import 'star_field_painter.dart'; class StarField extends StatefulWidget { final double starSpeed; final int starCount; const StarField({Key key, this.starSpeed = 3, this.starCount = 500 }) : super(key: key); @override _StarFieldState createState() => _StarFieldState(); } class _StarFieldState extends State<StarField> { List<Star> _stars; double _maxZ = 500; double _minZ = 1; ui.Image _glowImage; Ticker _ticker; void _initStars(BuildContext context) { //Start async image load _loadGlowImage(); //Create stars, randomize their starting values _stars = []; for (var i = widget.starCount; i-- > 0;) { var s = _randomizeStar(Star(), true); _stars.add(s); } _ticker = new Ticker(_handleStarTick)..start(); } @override void dispose() { _ticker.dispose(); super.dispose(); } @override Widget build(BuildContext context) { if (_stars == null) { _initStars(context); } return Container( width: double.infinity, height: double.infinity, color: Colors.black, child: CustomPaint( painter: StarFieldPainter( _stars, glowImage: _glowImage, ), ), ); } void _handleStarTick(Duration elapsed) { setState(() { advanceStars(widget.starSpeed); }); } void advanceStars(double distance) { _stars.forEach((s) { //Move stars on the z, and reset them when they reach the viewport s.z -= distance; // * elapsed.inMilliseconds; if (s.z < _minZ) { _randomizeStar(s, false); } else if (s.z > _maxZ) { s.z = _minZ; } }); } Star _randomizeStar(Star star, bool randomZ) { Random rand = Random(); star.x = (-1 + rand.nextDouble() * 2) * 75; star.y = (-1 + rand.nextDouble() * 2) * 75; star.z = randomZ ? rand.nextDouble() * _maxZ : _maxZ; star.rotation = rand.nextDouble() * pi * 2; //Some fraction of stars are purple, and bigger than the rest if (rand.nextDouble() < .1) { star.color = Color(0xffD4A1FF); star.size = 2 + rand.nextDouble() * 2; } else { star.color = Colors.white; star.size = .5 + rand.nextDouble() * 2; } return star; } void _loadGlowImage() async { final ByteData data = await rootBundle.load('${App.bundle}/assets/glow.png'); ui.decodeImageFromList(new Uint8List.view(data.buffer), (img) => _glowImage = img); } }
0
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib
mirrored_repositories/flutter_showcase/example/apps/constellations_list/lib/star_field/star_field_painter.dart
import 'dart:math'; import 'dart:ui' as ui; import 'package:flutter/material.dart'; class StarFieldPainter extends CustomPainter { final List<Star> stars; final ui.Image glowImage; StarFieldPainter(this.stars, {this.glowImage }); @override void paint(Canvas canvas, Size canvasSize) { if (stars == null || canvasSize == null) return; canvas.translate(canvasSize.width / 2, canvasSize.height / 2); var paint = Paint()..color = Colors.white; stars.forEach((s) { var scale = .1 + map(s.z, 0, canvasSize.width, s.size, 0); var sx = map(s.x / s.z, 0, 1, 0, canvasSize.width); var sy = map(s.y / s.z, 0, 1, 0, canvasSize.height); var time = DateTime.now().millisecondsSinceEpoch/200; paint.color = s.color; var pos = Offset(sx,sy); canvas.drawCircle( pos, scale, paint,); if(glowImage != null && s.color != Colors.white){ var glowSizeX = scale * 6 + 2 * (sin(time * .5)); var glowSizeY = scale * 6 + 2 * (cos(time * .75)); var src = Rect.fromPoints(Offset.zero, Offset(glowImage.width.toDouble(), glowImage.height.toDouble())); var rect = Rect.fromCenter(center: pos, width: glowSizeX, height: glowSizeY); canvas.drawImageRect(glowImage, src, rect, paint); } }); } @override bool shouldRepaint(CustomPainter oldDelegate) { return true; } double map(double value, double from1, double to1, double from2, double to2) { return (value - from1) / (to1 - from1) * (to2 - from2) + from2; } } class Star { double x; double y; double z; double size = 1; double rotation = 0; Color color = Colors.white; Star({this.x = 0, this.y = 0, this.z = 0}); }
0
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib/rotation_3d.dart
import 'dart:math'; import 'package:flutter/material.dart'; //Takes a x,y or z rotation, in degrees, and rotates. Good for spins & 3d flip effects class Rotation3d extends StatelessWidget { //Degrees to rads constant static const double degrees2Radians = pi/180; final Widget child; final double rotationX; final double rotationY; final double rotationZ; const Rotation3d({Key key, @required this.child, this.rotationX=0, this.rotationY=0, this.rotationZ=0}) : super(key: key); @override Widget build(BuildContext context) { return Transform( alignment: FractionalOffset.center, transform: Matrix4.identity() ..setEntry(3, 2, 0.001) ..rotateX(rotationX * degrees2Radians) ..rotateY(rotationY * degrees2Radians) ..rotateZ(rotationZ * degrees2Radians), child: child); } }
0
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib/clipped_view.dart
import 'package:flutter/material.dart'; //Hides the overflow of a child, preventing the Flutter framework from throwing errors class ClippedView extends StatelessWidget { final Widget child; final Axis clipDirection; const ClippedView({Key key, this.child, this.clipDirection = Axis.horizontal}) : super(key: key); @override Widget build(BuildContext context) { return SingleChildScrollView( physics: NeverScrollableScrollPhysics(), scrollDirection: clipDirection, child: child, ); } }
0
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib/navbar.dart
import 'clipped_view.dart'; import 'navbar_button.dart'; import 'package:flutter/material.dart'; class NavBar extends StatelessWidget { final ValueChanged<int> itemTapped; final int currentIndex; final List<NavBarItemData> items; const NavBar({this.items, this.itemTapped, this.currentIndex = 0}); NavBarItemData get selectedItem => currentIndex >= 0 && currentIndex < items.length ? items[currentIndex] : null; @override Widget build(BuildContext context) { //For each item in our list of data, create a NavBtn widget List<Widget> buttonWidgets = items.map((data) { //Create a button, and add the onTap listener return NavbarButton(data, data == selectedItem, onTap: () { //Get the index for the clicked data var index = items.indexOf(data); //Notify any listeners that we've been tapped, we rely on a parent widget to change our selectedIndex and redraw itemTapped(index); }); }).toList(); //Create a container with a row, and add our btn widgets into the row return Container( decoration: BoxDecoration( color: Colors.white, //Add some drop-shadow to our navbar, use 2 for a slightly nicer effect boxShadow: [ BoxShadow(blurRadius: 16, color: Colors.black12), BoxShadow(blurRadius: 24, color: Colors.black12), ], ), alignment: Alignment.center, height: 80, //Clip the row of widgets, to suppress any overflow errors that might occur during animation child: ClippedView( child: Row( //Center buttons horizontally mainAxisAlignment: MainAxisAlignment.center, // Inject a bunch of btn instances into our row children: buttonWidgets, ), ), ); } } class NavBarItemData { final String title; final IconData icon; final Color selectedColor; final double width; NavBarItemData(this.title, this.icon, this.width, this.selectedColor); }
0
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib/navbar_button.dart
import 'dart:core'; import 'package:flutter/material.dart'; import 'clipped_view.dart'; import 'main.dart'; import 'navbar.dart'; import 'rotation_3d.dart'; // Handle the transition between selected and de-deselected, by animating it's own width, // and modifying the color/visibility of some child widgets class NavbarButton extends StatefulWidget { final NavBarItemData data; final bool isSelected; final VoidCallback onTap; const NavbarButton(this.data, this.isSelected, {@required this.onTap }); @override _NavbarButtonState createState() => _NavbarButtonState(); } class _NavbarButtonState extends State<NavbarButton> with SingleTickerProviderStateMixin { AnimationController _iconAnimController; bool _wasSelected; double _animScale = 1; @override void initState() { //Create a tween + controller which will drive the icon rotation int duration = (350 / _animScale).round(); _iconAnimController = AnimationController( duration: Duration(milliseconds: duration), vsync: this, ); Tween<double>(begin: 0, end: 1).animate(_iconAnimController) //Listen for tween updates, and rebuild the widget tree on each tick ..addListener(() { setState(() {}); }); super.initState(); } @override Widget build(BuildContext context) { _startAnimIfSelectedChanged(widget.isSelected); //Create our main button, a Row, with an icon and some text //Inject the data from our widget.data property var content = Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ //Rotate the icon using the current animation value Rotation3d( rotationY: 180 * _iconAnimController.value, child: Icon( widget.data.icon, size: 24, color: widget.isSelected ? Colors.white : Color(0xffcccccc), ), ), //Add some hz spacing SizedBox(width: 12), //Label Text( widget.data.title, style: TextStyle(color: Colors.white, fontFamily: "Montserrat", package: App.pkg), ), ], ); //Wrap btn in GestureDetector so we can listen to taps return GestureDetector( onTap: () => widget.onTap(), //Wrap in a bit of extra padding to make it easier to tap child: Container( padding: EdgeInsets.only(top: 16, bottom: 16, right: 4, left: 4), //Wrap in an animated container, so changes to width & color automatically animate into place child: AnimatedContainer( alignment: Alignment.center, //Determine target width, selected item is wider width: widget.isSelected ? widget.data.width : 56, curve: Curves.easeOutCubic, padding: EdgeInsets.all(12), duration: Duration(milliseconds: (700 / _animScale).round()), //Use BoxDecoration top create a rounded container decoration: BoxDecoration( color: widget.isSelected ? widget.data.selectedColor : Colors.white, borderRadius: BorderRadius.all(Radius.circular(24)), ), //Wrap the row in a ClippedView to suppress any overflow errors if we momentarily exceed the screen size child: ClippedView( child: content, ), ), ), ); } void _startAnimIfSelectedChanged(bool isSelected) { if (_wasSelected != widget.isSelected) { //Go forward or reverse, depending on the isSelected state widget.isSelected ? _iconAnimController.forward() : _iconAnimController.reverse(); } _wasSelected = widget.isSelected; } }
0
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib/main.dart
import 'package:flutter/material.dart'; import 'package:shared/env.dart'; import 'demo.dart'; void main() => runApp(App()); class App extends StatelessWidget { static String _pkg = "bubble_tab_bar"; static String get pkg => Env.getPackage(_pkg); @override Widget build(BuildContext context) { return MaterialApp( home: BubbleTabBarDemo(), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib/demo.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:outline_material_icons/outline_material_icons.dart'; import 'content/gallery_page.dart'; import 'content/home_page.dart'; import 'content/camera_page.dart'; import 'content/likes_page.dart'; import 'content/save_page.dart'; import 'navbar.dart'; class BubbleTabBarDemo extends StatefulWidget { @override _BubbleTabBarDemoState createState() => _BubbleTabBarDemoState(); } class _BubbleTabBarDemoState extends State<BubbleTabBarDemo> { List<NavBarItemData> _navBarItems; int _selectedNavIndex = 0; List<Widget> _viewsByIndex; @override void initState() { //Declare some buttons for our tab bar _navBarItems = [ NavBarItemData("Home", OMIcons.home, 110, Color(0xff01b87d)), NavBarItemData("Gallery", OMIcons.image, 110, Color(0xff594ccf)), NavBarItemData("Camera", OMIcons.camera, 115, Color(0xff09a8d9)), NavBarItemData("Likes", OMIcons.favoriteBorder, 100, Color(0xffcf4c7a)), NavBarItemData("Saved", OMIcons.save, 105, Color(0xfff2873f)), ]; //Create the views which will be mapped to the indices for our nav btns _viewsByIndex = <Widget>[ HomePage(), GalleryPage(), CameraPage(), LikesPage(), SavePage(), ]; super.initState(); } @override Widget build(BuildContext context) { var accentColor = _navBarItems[_selectedNavIndex].selectedColor; //Create custom navBar, pass in a list of buttons, and listen for tap event var navBar = NavBar( items: _navBarItems, itemTapped: _handleNavBtnTapped, currentIndex: _selectedNavIndex, ); //Display the correct child view for the current index var contentView = _viewsByIndex[min(_selectedNavIndex, _viewsByIndex.length - 1)]; //Wrap our custom navbar + contentView with the app Scaffold return Scaffold( backgroundColor: Color(0xffE6E6E6), body: SafeArea( child: Container( width: double.infinity, //Wrap the current page in an AnimatedSwitcher for an easy cross-fade effect child: AnimatedSwitcher( duration: Duration(milliseconds: 350), //Pass the current accent color down as a theme, so our overscroll indicator matches the btn color child: Theme( data: ThemeData(accentColor: accentColor), child: contentView, ), ), ), ), bottomNavigationBar: navBar, //Pass our custom navBar into the scaffold ); } void _handleNavBtnTapped(int index) { //Save the new index and trigger a rebuild setState(() { //This will be passed into the NavBar and change it's selected state, also controls the active content page _selectedNavIndex = index; }); } }
0
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib/content/likes_page.dart
import 'package:shared/ui/placeholder/placeholder_card_short.dart'; import 'package:flutter/material.dart'; class LikesPage extends StatelessWidget { @override Widget build(BuildContext context) { return Container( child: ListView.builder( itemCount: 9, itemBuilder: (content, index) { return Container( padding: EdgeInsets.symmetric(vertical: 12, horizontal: 12), child: PlaceholderCardShort(), ); }, ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib/content/home_page.dart
import 'package:shared/ui/placeholder/placeholder_card_tall.dart'; import 'package:flutter/material.dart'; class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Container( child: ListView.builder( itemCount: 9, itemBuilder: (content, index) { return Container( padding: EdgeInsets.symmetric(vertical: 12), child: PlaceholderCardTall(height: 200,), ); }, ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib/content/camera_page.dart
import 'package:flutter/material.dart'; class CameraPage extends StatelessWidget { @override Widget build(BuildContext context) { double fabSize = 90; //Main list content return Container( alignment: Alignment.bottomCenter, color: Colors.black, padding: EdgeInsets.only(bottom: 32), // Create a floating action button (FAB), with a circle inside of it // To size a FAB, nest it in a Container, wrapped in a SizedBox child: Container( width: fabSize, height: fabSize, child: SizedBox( child: FloatingActionButton( onPressed: () {}, //Create circle inside our FAB child: Container( margin: EdgeInsets.all(8), decoration: BoxDecoration( color: Colors.white30, shape: BoxShape.circle, ), ), ), ), ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib/content/content_box.dart
import 'package:flutter/material.dart'; class ContentBox extends StatelessWidget { final double width; final double height; const ContentBox({Key key, this.width = 240, this.height = 80}) : super(key: key); @override Widget build(BuildContext context) { return SizedBox( width: width, height: height, child: Container( margin: EdgeInsets.all(6), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(8)), ), ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib/content/gallery_page.dart
import 'package:shared/ui/placeholder/placeholder_image.dart'; import 'package:flutter/material.dart'; class GalleryPage extends StatelessWidget { @override Widget build(BuildContext context) { bool isLandscape = MediaQuery.of(context).size.aspectRatio > 1; var columnCount = isLandscape ? 4 : 2; return Container( child: GridView.count( crossAxisCount: columnCount, children: List.generate(20, (index) { return PlaceholderImage(); }), ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib
mirrored_repositories/flutter_showcase/example/apps/bubble_tab_bar/lib/content/save_page.dart
import 'package:shared/ui/placeholder/placeholder_image_with_text.dart'; import 'package:flutter/material.dart'; class SavePage extends StatelessWidget { @override Widget build(BuildContext context) { bool isLandscape = MediaQuery.of(context).size.aspectRatio > 1; var columnCount = isLandscape ? 3 : 2; return Container( child: GridView.count( crossAxisCount: columnCount, children: List.generate(20, (index) { return PlaceholderImageWithText(); }), ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition/lib/sync_scroll_controller.dart
import 'package:flutter/widgets.dart'; class SyncScrollController extends TrackingScrollController { SyncScrollController({ double initialScrollOffset: 0.0, bool keepScrollOffset: true, String debugLabel }) : super( initialScrollOffset: initialScrollOffset, keepScrollOffset: keepScrollOffset, debugLabel: debugLabel) { this.addListener(_handleScroll); } void _handleScroll() { // Find scrolling position ScrollPosition scrollPosition; for (var sp in positions) { if (sp.isScrollingNotifier.value) { scrollPosition = sp; break; } } for (var sp in positions) { if (!identical(sp, scrollPosition)) sp.jumpTo(scrollPosition.pixels); } } }
0
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition/lib/dark_ink_bar.dart
import 'package:flutter/material.dart'; import 'main.dart'; class DarkInkBar extends StatefulWidget { final ValueNotifier<bool> darkModeValue; DarkInkBar({ this.darkModeValue }); @override State createState() { return _DarkInkBarState(darkModeValue); } } class _DarkInkBarState extends State<DarkInkBar> with SingleTickerProviderStateMixin { static final Color darkColor = Color(0xFF171137); static final Color lightColor = Color(0xFF67ECDC); ValueNotifier<bool> _darkModeValue; AnimationController _controller; Animation<double> _iconOpacityAnimation; Animation<double> _backgroundColorAnimation; Animation<double> _foregroundColorAnimation; ImageProvider _darkModeToggleIconImage; _DarkInkBarState(this._darkModeValue) { _darkModeValue.addListener(_handleDarkModeChange); } @override void initState() { _controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 500)); _iconOpacityAnimation = TweenSequence<double>( [ TweenSequenceItem( tween: Tween<double>(begin: 1.0, end: 0.0), weight: .20, ), TweenSequenceItem( tween: Tween<double>(begin: 0.0, end: 0.0), weight: .2, ), TweenSequenceItem( tween: Tween<double>(begin: 0.0, end: 1.0), weight: .20, ), ], ).animate(_controller); _backgroundColorAnimation = TweenSequence<double>( [ TweenSequenceItem( tween: Tween<double>(begin: 0.0, end: 0.0), weight: .20, ), TweenSequenceItem( tween: Tween<double>(begin: 0.0, end: 1.0), weight: .1, ), TweenSequenceItem( tween: Tween<double>(begin: 1.0, end: 1.0), weight: .20, ), ], ).animate(_controller); _foregroundColorAnimation = TweenSequence<double>( [ TweenSequenceItem( tween: Tween<double>(begin: 1.0, end: 1.0), weight: .35, ), TweenSequenceItem( tween: Tween<double>(begin: 1.0, end: 0.0), weight: .1, ), TweenSequenceItem( tween: Tween<double>(begin: 0.0, end: 0.0), weight: .55, ), ], ).animate(_controller); _iconOpacityAnimation.addListener( () { setState(() { _updateIcon(); }); }); _darkModeToggleIconImage = AssetImage('assets/images/icon-moon.png', package: App.pkg); _updateIcon(); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(context) { final appSize = MediaQuery.of(context).size; final backgroundColor = HSVColor.lerp( HSVColor.fromColor(lightColor), HSVColor.fromColor(darkColor), _backgroundColorAnimation.value).toColor(); final foregroundColor = HSVColor.lerp( HSVColor.fromColor(lightColor), HSVColor.fromColor(darkColor), _foregroundColorAnimation.value).toColor(); // Build a simple bar with 3 animated buttons and a bottom border return Positioned( left: 0, top: 0, width: appSize.width, child: Column( children: [ Container( color: backgroundColor, child: SafeArea( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, // Use flat buttons so we don't have to deal with the drop shadows children: [ FlatButton( onPressed: () => {}, splashColor: Colors.transparent, highlightColor: Colors.transparent, textColor: foregroundColor, child: Icon(Icons.arrow_back_ios), ), FlatButton( onPressed: () => {}, splashColor: Colors.transparent, highlightColor: Colors.transparent, textColor: foregroundColor, child: ImageIcon(AssetImage('assets/images/icon-r.png', package: App.pkg)), ), FlatButton( onPressed: () => _darkModeValue?.value = !(_darkModeValue?.value ?? true), splashColor: Colors.transparent, highlightColor: Colors.transparent, textColor: foregroundColor, child: Opacity( opacity: _iconOpacityAnimation.value, child: ImageIcon(_darkModeToggleIconImage), ), ), ] ), ), ), Container( height: 2, color: _darkModeValue.value ? Color(0xFF0098A3) : Color(0xFF2B777E), ), ] ), ); } void _handleDarkModeChange() { if (_darkModeValue.value) { _controller.forward(from: 0.0); } else { _controller.reverse(from: 1.0); } setState(() {}); } void _updateIcon() { if (_controller.value > 0.5) { _darkModeToggleIconImage = AssetImage('assets/images/icon-sun.png', package: App.pkg); } else { _darkModeToggleIconImage = AssetImage('assets/images/icon-moon.png', package: App.pkg); } } }
0
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition/lib/transition_container.dart
import 'package:flutter/material.dart'; import 'package:shared/ui/widget_mask.dart'; import 'package:shared/ui/animated_sprite.dart'; import 'main.dart'; class TransitionContainer extends StatefulWidget { final ValueNotifier<bool> darkModeValue; final Widget child; TransitionContainer({ this.darkModeValue, this.child }); @override State createState() { return _TransitionContainerState(darkModeValue, child); } } class _TransitionContainerState extends State<TransitionContainer> with SingleTickerProviderStateMixin { AnimationController _controller; Animation<double> _animation; List<ImageProvider> _images; int _currentImageIndex = 0; Widget _childForeground; Widget _childBackground; _TransitionContainerState(ValueNotifier<bool> darkModeValue, this._childBackground) { darkModeValue?.addListener(() { _handleDarkModeChange(darkModeValue.value); }); } @override void initState() { _images = [ AssetImage('assets/images/ink_mask.png', package: App.pkg), AssetImage('assets/images/wipe_mask.png', package: App.pkg), AssetImage('assets/images/tendril_mask.png', package: App.pkg), ]; _controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 1500)); _animation = TweenSequence( <TweenSequenceItem<double>>[ TweenSequenceItem<double>( tween: Tween<double>(begin: 0.0, end: 0.0), weight: 30, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 0.0, end: 34.0), weight: 70, ), ], ).animate(_controller); _controller.addListener(() { setState(() { }); }); _controller.addStatusListener((status) { if (status == AnimationStatus.completed) { setState(() { _childBackground = _childForeground; _childForeground = null; }); _controller.reset(); } }); super.initState(); } @override void didUpdateWidget(TransitionContainer oldWidget) { if (widget.child != oldWidget.child) { setState(() { _childForeground = widget.child; }); _controller.forward(); } super.didUpdateWidget(oldWidget); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(context) { final appSize = MediaQuery.of(context).size; final width = appSize.width; final height = appSize.height; List<Widget> children = <Widget>[ Container( width: width, height: height, child: _childBackground, ), ]; // If we swapped the child then add the foreground to the list of children when animating if (_childForeground != null) { children.add( // Draw the foreground masked over the background WidgetMask( maskChild: Container( width: width, height: height, // Draw the transition animation as the mask child: AnimatedSprite( image: _images[_currentImageIndex], frameWidth: 360, frameHeight: 720, animation: _animation, ), ), child: Container( width: width, height: height, child: _childForeground, ), ), ); } return Positioned( left: 0, width: width, height: height, child: Stack( children: children, ), ); } void _handleDarkModeChange(bool darkMode) { if (darkMode) { setState(() { ++_currentImageIndex; if (_currentImageIndex >= _images.length) { _currentImageIndex = 0; } }); } } }
0
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition/lib/dark_ink_controls.dart
import 'package:flutter/material.dart'; class DarkInkControls extends StatefulWidget { final ValueNotifier<bool> darkModeValue; DarkInkControls({this.darkModeValue}); @override State createState() { return _DarkInkControlsState(darkModeValue); } } class _DarkInkControlsState extends State<DarkInkControls> with SingleTickerProviderStateMixin { ValueNotifier<bool> _darkModeValue; AnimationController _controller; Animation<double> _buttonAnimation0; Animation<double> _buttonAnimation1; Animation<double> _buttonAnimation2; Color _backgroundColor; Color _foregroundColor; _DarkInkControlsState(ValueNotifier<bool> darkModeValue) : _darkModeValue = darkModeValue { _darkModeValue.addListener(_handleDarkModeChange); _updateColor(); } @override void initState() { _controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 2000)); _buttonAnimation0 = TweenSequence( <TweenSequenceItem<double>>[ TweenSequenceItem<double>( tween: Tween<double>(begin: 0.0, end: 100.0), weight: 10, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 100.0, end: 100.0), weight: 76, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 100.0, end: 0.0), weight: 10, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 0.0, end: 0.0), weight: 4, ), ], ).animate(_controller); _buttonAnimation1 = TweenSequence( <TweenSequenceItem<double>>[ TweenSequenceItem<double>( tween: Tween<double>(begin: 0.0, end: 0.0), weight: 2, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 0.0, end: 100.0), weight: 10, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 100.0, end: 100.0), weight: 76, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 100.0, end: 0.0), weight: 10, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 0.0, end: 0.0), weight: 2, ), ], ).animate(_controller); _buttonAnimation2 = TweenSequence( <TweenSequenceItem<double>>[ TweenSequenceItem<double>( tween: Tween<double>(begin: 0.0, end: 0.0), weight: 4, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 0.0, end: 100.0), weight: 10, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 100.0, end: 100.0), weight: 76, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 100.0, end: 0.0), weight: 10, ), ], ).animate(_controller); _buttonAnimation0.addListener(() { setState(() { if (_controller.value > 0.5) { _updateColor(); } }); }); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(context) { final appSize = MediaQuery.of(context).size; // Show some animated control buttons return Positioned( left: 0, top: appSize.height - 80, width: appSize.width, height: 60, child: Row( mainAxisAlignment: MainAxisAlignment.center, // Animate the controls moving offscreen using slightly offset animations children: [ Transform( transform: Matrix4.translationValues(0, _buttonAnimation0.value, 0), child: FloatingActionButton( mini: true, heroTag: 0, onPressed: () => {}, backgroundColor: _backgroundColor, foregroundColor: _foregroundColor, child: Icon(Icons.bookmark_border), ), ), Padding(padding: EdgeInsets.all(10)), Transform( transform: Matrix4.translationValues(0, _buttonAnimation1.value, 0), child: FloatingActionButton( mini: true, heroTag: 1, onPressed: () => {}, backgroundColor: _backgroundColor, foregroundColor: _foregroundColor, child: Icon(Icons.more_horiz), ), ), Padding(padding: EdgeInsets.all(10)), Transform( transform: Matrix4.translationValues(0, _buttonAnimation2.value, 0), child: FloatingActionButton( heroTag: 2, mini: true, onPressed: () => {}, backgroundColor: _backgroundColor, foregroundColor: _foregroundColor, child: Icon(Icons.arrow_forward), ), ), ], ), ); } void _handleDarkModeChange() { _controller.forward(from: 0.0); setState(() {}); } void _updateColor() { final darkColor = Color(0xFF171137); final lightColor = Color(0xFF67ECDC); _backgroundColor = _darkModeValue.value ? darkColor : lightColor; _foregroundColor = _darkModeValue.value ? lightColor : darkColor; } }
0
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition/lib/main.dart
import 'package:flutter/material.dart'; import 'package:shared/env.dart'; import './demo.dart'; void main() => runApp(App()); class App extends StatelessWidget { static String _pkg = "dark_ink_transition"; static String get pkg => Env.getPackage(_pkg); @override Widget build(context) { return MaterialApp( home: DarkInkDemo(), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition/lib/demo.dart
import 'package:flutter/material.dart'; import 'dark_ink_bar.dart'; import 'dark_ink_content.dart'; import 'dark_ink_controls.dart'; import 'sync_scroll_controller.dart'; import 'transition_container.dart'; class DarkInkDemo extends StatefulWidget { @override State createState() { return _DarkInkDemoState(); } } class _DarkInkDemoState extends State<DarkInkDemo> { ValueNotifier<bool> _darkModeValue; ScrollController _scrollController; @override void initState() { _darkModeValue = ValueNotifier<bool>(false); _darkModeValue.addListener(() { setState(() { }); }); _scrollController = SyncScrollController(); super.initState(); } @override void dispose() { _darkModeValue.dispose(); _scrollController.dispose(); super.dispose(); } @override Widget build(context) { //Wrap the entire demo is a gestureDetector, just to more easily show off the darkMode transition. return GestureDetector( onTap: (){ _darkModeValue.value = !_darkModeValue.value; }, // Build a simple scaffold that shows the top bar and controls over the content child: Stack( children: [ TransitionContainer( darkModeValue: _darkModeValue, child: DarkInkContent( darkMode: _darkModeValue.value, scrollController: _scrollController ), ), DarkInkBar(darkModeValue: _darkModeValue), DarkInkControls(darkModeValue: _darkModeValue), ], ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition
mirrored_repositories/flutter_showcase/example/apps/dark_ink_transition/lib/dark_ink_content.dart
import 'package:flutter/material.dart'; import 'main.dart'; class DarkInkContent extends StatelessWidget { static const String headerText = 'The Private History of a Campaign That Failed'; static const String subHeaderText = '5 minute read'; static const String bodyText = 'You have heard from a great many people who did something in the war, is it not fair and right that you listen a little moment to one who started out to do something in it but didn\'t? Thousands entered the war, got just a taste of it, and then stepped out again permanently.\n\nThese, by their very numbers, are respectable and therefore entitled to a sort of voice, not a loud one, but a modest one, not a boastful one but an apologetic one. They ought not be allowed much space among better people, people who did something. I grant that, but they ought at least be allowed to state why they didn\'t do anything and also to explain the process by which they didn\'t do anything. Surely this kind of light must have some sort of value.\n\nOut west there was a good deal of confusion in men\'s minds during the first months of the great trouble, a good deal of unsettledness, of leaning first this way then that, and then the other way. It was hard for us to get our bearings. I call to mind an example of this. I was piloting on the Mississippi when the news came that South Carolina had gone out of the Union on the 20th of December, 1860. My pilot mate was a New Yorker. He was strong for the Union; so was I. But he would not listen to me with any patience, my loyalty was smirched, to his eye, because my father had owned slaves. I said in palliation of this dark fact that I had heard my father say, some years before he died, that slavery was a great wrong and he would free the solitary Negro he then owned if he could think it right to give away the property of the family when he was so straitened in means. My mate retorted that a mere impulse was nothing, anyone could pretend to a good impulse, and went on decrying my Unionism and libelling my ancestry. A month later the secession atmosphere had considerably thickened on the Lower Mississippi and I became a rebel; so did he. We were together in New Orleans the 26th of January, when Louisiana went out of the Union. He did his fair share of the rebel shouting but was opposed to letting me do mine. He said I came of bad stock, of a father who had been willing to set slaves free. In the following summer he was piloting a Union gunboat and shouting for the Union again and I was in the Confederate army. I held his note for some borrowed money. He was one of the most upright men I ever knew but he repudiated that note without hesitation because I was a rebel and the son of a man who owned slaves. '; final bool darkMode; final ScrollController scrollController; DarkInkContent({this.darkMode, this.scrollController}); @override Widget build(context) { final lightTextColor = Color(0xFFBCFEEA); final darkTextColor = Color(0xFF210A3B); final lightSubHeaderColor = Color(0xFF00EBAC); final darkSubHeaderColor = Color(0xFF008F9C); // Build a simple scroll view that just displays content with the passed scroll controller return SingleChildScrollView( controller: scrollController, scrollDirection: Axis.vertical, child: Container( color: darkMode ? Color(0xFF313466) : Color(0xFFFFFFFF), padding: EdgeInsets.all(37), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( headerText, style: TextStyle( fontSize: 36, fontFamily: 'Merriweather', fontWeight: FontWeight.bold, color: darkMode ? lightTextColor : darkTextColor, decoration: TextDecoration.none, package: App.pkg), ), Padding(padding: EdgeInsets.only(top: 24)), Text( subHeaderText, style: TextStyle( fontSize: 12, fontFamily: 'Merriweather', color: darkMode ? lightSubHeaderColor : darkSubHeaderColor, decoration: TextDecoration.none, package: App.pkg), ), Padding(padding: EdgeInsets.only(top: 12)), Container( height: 1, color: darkMode ? Color(0x510098A3) : Color(0x512B777E), ), Padding(padding: EdgeInsets.only(top: 24)), Text( bodyText, style: TextStyle( fontSize: 16, fontFamily: 'Barlow', letterSpacing: 0.5, height: 1.5, fontWeight: FontWeight.w500, color: darkMode ? lightTextColor : darkTextColor, decoration: TextDecoration.none, package: App.pkg), ), Padding(padding: EdgeInsets.only(top: 64)), ]), ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/indie_3d
mirrored_repositories/flutter_showcase/example/apps/indie_3d/lib/indie_3d_model_controller.dart
import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:vector_math/vector_math.dart' as vec32; import 'package:shared/ui/widget_model.dart'; import 'main.dart'; class Indie3dModelController extends ChangeNotifier { VertexMesh _meshTorus; VertexMesh _meshStar; VertexMesh _meshCube; List<vec32.Vector3> _positions; List<vec32.Quaternion> _rotations; List<vec32.Vector3> _scales; List<vec32.Vector3> _linearVelocities; List<vec32.Vector3> _angularVelocities; List<vec32.Vector3> _constantAngularVelocities; List<VertexMeshInstance> _meshInstances; vec32.Matrix4 matProj; vec32.Matrix4 matView; double _cameraOffset = 0.0; double _targetCameraOffset = 0.0; double _lastTime; Ticker _ticker; math.Random _rng; void init(BuildContext context) { final appSize = MediaQuery.of(context).size; _setCamera(0.0); setView(appSize); _rng = math.Random.secure(); _loadMeshs(context); } bool get initialized => _ticker != null; List<VertexMeshInstance> get meshInstances => _meshInstances; Future<void> _loadMeshs(BuildContext context) async { _meshTorus = await loadVertexMeshFromOBJAsset(context, "${App.bundle}/assets", 'torus.obj'); _meshStar = await loadVertexMeshFromOBJAsset(context, "${App.bundle}/assets", 'star.obj'); _meshCube = await loadVertexMeshFromOBJAsset(context, "${App.bundle}/assets", 'cube.obj'); _initInstances(); _ticker = Ticker(_handleTick); _ticker.start(); } void _initInstances() { _meshInstances = List<VertexMeshInstance>(); _positions = List<vec32.Vector3>(); _rotations = List<vec32.Quaternion>(); _scales = List<vec32.Vector3>(); _linearVelocities = List<vec32.Vector3>(); _angularVelocities = List<vec32.Vector3>(); _constantAngularVelocities = List<vec32.Vector3>(); for (int i = 0; i < 36; ++i) { VertexMesh mesh; if (i < 12) { mesh = _meshTorus; } else if (i < 24) { mesh = _meshStar; } else { mesh = _meshCube; } _meshInstances.add(VertexMeshInstance(mesh)); _positions.add(vec32.Vector3.zero()); _rotations.add(vec32.Quaternion.identity()); _scales.add(vec32.Vector3.all(1.0)); _linearVelocities.add(vec32.Vector3.zero()); _angularVelocities.add(vec32.Vector3.zero()); _constantAngularVelocities.add(vec32.Vector3.zero()); } // Set initial values for (var p in _positions) { p.x = _rng.nextDouble() * 8 - 4; p.y = _rng.nextDouble() * 28 - 19; p.z = _rng.nextDouble() * 4 - 4; } // Distribute better for (int i = 0; i < 200; ++i) { for (int j = 0; j < _positions.length; ++j) { for (int k = j + 1; k < _positions.length; ++k) { final p0 = _positions[j]; final p1 = _positions[k]; final p0p1 = p1 - p0; final dist = p0p1.xy.length; if (dist < 5.0) { // Push both objects in a random direction final norm = vec32.Vector3( _rng.nextDouble() * 2 - 1, _rng.nextDouble() * 2 - 1, 0.0).normalized(); p0.add(-norm * 0.2); p1.add(norm * 0.2); // Clamp values p0.x = p0.x.clamp(-5.0, 5.0); p1.x = p1.x.clamp(-5.0, 5.0); } } } } _rotations.forEach((vec32.Quaternion quaternion) => quaternion.setAxisAngle( vec32.Vector3( _rng.nextDouble() * 2.0 - 1.0, _rng.nextDouble() * 2.0 - 1.0, _rng.nextDouble() * 2.0 - 1.0, ), _rng.nextDouble() * math.pi * 2.0, )); _constantAngularVelocities.forEach((vec32.Vector3 vel) { vel.x = _rng.nextDouble() * 1.0 - 0.5; vel.y = _rng.nextDouble() * 1.0 - 0.5; vel.z = _rng.nextDouble() * 1.0 - 0.5; }); _setTransform(); } set cameraOffset(double offset) => _targetCameraOffset = offset; void triggerTap(BuildContext context, Offset position, int page) { // Convert the position into ndc coords then into world space coords to compare // with the meshs position // Calculate world space (0, 0, 0) in ndc space double cameraZ = 0.0; { final camNDC = (matProj * matView).transform(vec32.Vector4(0.0, 0.0, -2.0, 1.0)); if (camNDC.w != 0.0) { camNDC.x /= camNDC.w; camNDC.y /= camNDC.w; camNDC.z /= camNDC.w; } cameraZ = camNDC.z; } final appSize = MediaQuery.of(context).size; final ndc = vec32.Vector4( position.dx / appSize.width * 2.0 - 1.0, (position.dy / appSize.height * 2.0 - 1.0) * -1.0, cameraZ, 1.0 ); vec32.Matrix4 matrix = vec32.Matrix4.inverted(matProj * matView); vec32.Vector4 world = matrix.transform(ndc); if (world.w != 0.0) { world.x /= world.w; world.y /= world.w; world.z /= world.w; } print(world); // Apply forces to objects for (int i = page * 12; i < page * 12 + 12; ++i) { final force = _positions[i] - vec32.Vector3(world.x, world.y, _positions[i].z); final tangentForce = force.cross(vec32.Vector3(0.0, 0.0, -1.0)); _linearVelocities[i] += force.normalized() * (8.0 / force.length).clamp(0.0, 24.0); _angularVelocities[i] += tangentForce.normalized() * 4.0; } } void _setCamera(double xOffset) { matView = vec32.makeViewMatrix( vec32.Vector3(-xOffset, 0.0, 5.2), vec32.Vector3(-xOffset, 0.0, 0.0), vec32.Vector3(0.0, 1.0, 0.0) ); } void setView(Size size) { matProj = vec32.makePerspectiveMatrix( math.pi / 2.0, size.width / size.height, 0.01, 100.0); } void _setTransform() { for (int i = 0; i < _meshInstances.length; ++i) { final meshInstance = _meshInstances[i]; final matModel = vec32.Matrix4.compose(_positions[i], _rotations[i], _scales[i]); meshInstance.setTransform(matView * matModel, matProj); } notifyListeners(); } void _handleTick(Duration duration) { final double time = duration.inMicroseconds.toDouble() * 1e-6; if (_lastTime == null) { _lastTime = time; } final double dt = time - _lastTime; _lastTime = time; const kDrag = 0.2; for (int i = 0; i < _meshInstances.length; ++i) { // Apply drag (for a correct interaction we would // also multiply by the area of the object tangent to the velocity direction // but thats hard to calculate for arbitrary 3D shapes and we don't care that much here) final lvLength = _linearVelocities[i].length; if (lvLength.compareTo(0.0) != 0) { _linearVelocities[i] -= _linearVelocities[i].normalized() * 0.5 * kDrag * lvLength; } final avLength = _angularVelocities[i].length; if (avLength.compareTo(0.0) != 0) { _angularVelocities[i] -= _angularVelocities[i].normalized() * 0.5 * kDrag * avLength; } // Integrate velocity factors _positions[i].y += 1.0 * dt; _positions[i] += _linearVelocities[i] * dt; // Integrate the angular velocity using the quaternion integration equation _rotations[i] = quaternionExponent(vec32.Quaternion( (_angularVelocities[i].x + _constantAngularVelocities[i].x) * 0.5 * dt, (_angularVelocities[i].y + _constantAngularVelocities[i].y) * 0.5 * dt, (_angularVelocities[i].z + _constantAngularVelocities[i].z) * 0.5 * dt, 0.0, )) * _rotations[i]; if (_positions[i].y >= 16.0) { _positions[i].y = -16.0; } } // Update camera _cameraOffset += (_targetCameraOffset - _cameraOffset) * 4 * dt; _setCamera(_cameraOffset); _setTransform(); } } vec32.Quaternion quaternionExponent(vec32.Quaternion quaternion) { final ew = math.exp(quaternion.w); final v = vec32.Vector3(quaternion.x, quaternion.y, quaternion.z); final vlength = v.length; final cosv = math.cos(vlength); final sinv = math.sin(vlength); final w = ew * cosv; if (vlength.compareTo(0) == 0) { return vec32.Quaternion(0.0, 0.0, 0.0, w); } final x = ew * v.x / vlength * sinv; final y = ew * v.y / vlength * sinv; final z = ew * v.z / vlength * sinv; return vec32.Quaternion(x, y, z, w); }
0
mirrored_repositories/flutter_showcase/example/apps/indie_3d
mirrored_repositories/flutter_showcase/example/apps/indie_3d/lib/indie_app_bar.dart
import 'package:flutter/material.dart'; import 'main.dart'; class IndieAppBar extends StatelessWidget { const IndieAppBar({Key key}) : super(key: key); @override Widget build(context) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: EdgeInsets.symmetric(vertical: 10, horizontal: 20), child: Icon(Icons.menu, size: 32), ), Container( color: Color(0xFF010101), child: Text( 'FRESH BEATS BY', textAlign: TextAlign.right, style: TextStyle( package: App.pkg, letterSpacing: 2, fontFamily: 'Staatliches', fontWeight: FontWeight.bold, color: Colors.white, fontSize: 10.5, ), ), padding: EdgeInsets.only(top: 8, bottom: 8, left: 50, right: 16), ), ], ); } }
0
mirrored_repositories/flutter_showcase/example/apps/indie_3d
mirrored_repositories/flutter_showcase/example/apps/indie_3d/lib/indie_3d_model.dart
import 'package:flutter/material.dart'; import 'package:shared/ui/widget_model.dart'; import './indie_3d_model_controller.dart'; class Indie3dModel extends StatelessWidget { final Indie3dModelController controller; final int pageIndex; Indie3dModel({ @required this.controller, this.pageIndex = 0 }); @override Widget build(context) { return Stack( fit: StackFit.expand, children: controller.meshInstances != null ? <int>[0, 1, 2, 3, 4, 5].map( (int index) { return Container( child: CustomPaint( painter: MeshCustomPainter(controller.meshInstances[pageIndex * 6 + index]), ), ); } ).toList() : [], ); } }
0
mirrored_repositories/flutter_showcase/example/apps/indie_3d
mirrored_repositories/flutter_showcase/example/apps/indie_3d/lib/page.dart
import 'package:flutter/material.dart'; import 'package:shared/ui/blend_mask.dart'; import './indie_3d_model_controller.dart'; import './indie_3d_model.dart'; import 'main.dart'; class _Indie3dTextClipper extends CustomClipper<Rect> { final double y; final double height; _Indie3dTextClipper({this.y = 0, this.height = 0}); @override getClip(Size size) { return Rect.fromLTWH(0, height + y, size.width, size.height - height); } @override bool shouldReclip(_Indie3dTextClipper oldClipper) { return true; } } class Indie3dPage extends StatelessWidget { final String topTitle; final String bottomTitle; final Color backgroundColor; final ImageProvider image; final int pageIndex; final double bottomTitleScale; final Indie3dModelController controller; final double topTitleClipProgress; final double bottomTitleClipProgress; final double backgroundShapeOpacity; Indie3dPage({ this.topTitle = "", this.bottomTitle = "", this.backgroundColor, this.image, this.pageIndex = 0, this.controller, this.topTitleClipProgress = 0.0, this.bottomTitleClipProgress = 0.0, this.bottomTitleScale = 1.0, this.backgroundShapeOpacity = 0.85, }); @override Widget build(context) { final appSize = MediaQuery.of(context).size; final textScale = appSize.aspectRatio > 1? 1.15 : .8; return Container( color: backgroundColor, child: Stack( children: [ if (controller.initialized) ... { BlendMask( blendMode: BlendMode.hardLight, opacity: backgroundShapeOpacity, child: Indie3dModel(controller: controller, pageIndex: pageIndex * 2 + 0), ), Align( alignment: Alignment.bottomCenter, child: Container( height: appSize.height * (appSize.aspectRatio > 1? 1 : .80), child: Image(fit: BoxFit.fitHeight, image: image), ), ), BlendMask( blendMode: BlendMode.exclusion, child: Indie3dModel(controller: controller, pageIndex: pageIndex * 2 + 1), ), Align( alignment: Alignment.topRight, child: BlendMask( blendMode: BlendMode.difference, child: Padding( padding: EdgeInsets.fromLTRB(0, 60, 8, 4), child: Column( crossAxisAlignment: CrossAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.start, children: [ _buildClippedText(topTitle, topTitleClipProgress, 72 * textScale, 0, 6, 1), _buildClippedText(bottomTitle, bottomTitleClipProgress, 120 * textScale * bottomTitleScale, -10, 8, .9), ], ), ), ), ), BlendMask( opacity: 0.24, blendMode: BlendMode.colorDodge, child: Image( width: appSize.width, fit: BoxFit.none, image: AssetImage('images/noise.png', package: App.pkg), ), ), } else ... { Center( child: Text( 'Loading assets...', style: TextStyle( package: App.pkg, letterSpacing: 1.1, fontFamily: 'Roboto', fontWeight: FontWeight.bold, fontSize: 14, ), ), ), }, Align( alignment: Alignment.bottomCenter, child: Container( height: 200, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [const Color(0x00000000), const Color(0x99000000)], tileMode: TileMode.clamp, ), ), ), ), Align( alignment: Alignment.bottomCenter, child: Padding( padding: EdgeInsets.only(bottom: 60), child: Container( padding: EdgeInsets.symmetric(horizontal: 32, vertical: 12), color: Colors.white, child: Text( 'EXPLORE NOW', style: TextStyle( package: App.pkg, letterSpacing: 1.1, fontFamily: 'Roboto', fontWeight: FontWeight.bold, fontSize: 14, ), ), ), ), ), ], ), ); } ClipRect _buildClippedText(String text, double progress, double fontSize, double yOffset, double spacing, double height) { return ClipRect( clipper: _Indie3dTextClipper(height: progress * fontSize, y: yOffset), child: Text( text, textAlign: TextAlign.right, style: TextStyle( package: App.pkg, fontSize: fontSize, fontWeight: FontWeight.bold, fontFamily: 'Staatliches', letterSpacing: spacing, height: height, color: Colors.white, ), ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/indie_3d
mirrored_repositories/flutter_showcase/example/apps/indie_3d/lib/main.dart
import 'package:flutter/material.dart'; import 'package:shared/env.dart'; import './demo.dart'; void main() => runApp(App()); class App extends StatelessWidget { static String _pkg = 'indie_3d'; static String get pkg => Env.getPackage(_pkg); static String get bundle => Env.getBundle(_pkg); @override Widget build(context) { return MaterialApp( home: Indie3dHome(), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/indie_3d
mirrored_repositories/flutter_showcase/example/apps/indie_3d/lib/demo.dart
import 'package:flutter/material.dart'; import './indie_3d_model_controller.dart'; import './navigation.dart'; import './indie_app_bar.dart'; import './page.dart'; import 'main.dart'; class Indie3dHome extends StatefulWidget { @override State createState() => _Indie3dHomeState(); } class _Indie3dHomeState extends State<Indie3dHome> with TickerProviderStateMixin { AnimationController _page0TopTitleController; AnimationController _page0BottomTitleController; AnimationController _page1TopTitleController; AnimationController _page1BottomTitleController; AnimationController _page2TopTitleController; AnimationController _page2BottomTitleController; Indie3dModelController _controller; int _pageIndex = 0; @override void initState() { const duration = Duration(milliseconds: 400); _page0TopTitleController = AnimationController(vsync: this, duration: duration, value: 1.0); _page0BottomTitleController = AnimationController(vsync: this, duration: duration, value: 1.0); _page1TopTitleController = AnimationController(vsync: this, duration: duration, value: 0.0); _page1BottomTitleController = AnimationController(vsync: this, duration: duration, value: 0.0); _page2TopTitleController = AnimationController(vsync: this, duration: duration, value: 0.0); _page2BottomTitleController = AnimationController(vsync: this, duration: duration, value: 0.0); _controller = Indie3dModelController(); Listenable.merge([ _page0TopTitleController, _page0BottomTitleController, _page1TopTitleController, _page1BottomTitleController, _page2TopTitleController, _page2BottomTitleController, _controller, ]).addListener(() { setState(() { }); }); super.initState(); } @override void dispose() { _page0TopTitleController.dispose(); _page0BottomTitleController.dispose(); _page1TopTitleController.dispose(); _page1BottomTitleController.dispose(); _page2TopTitleController.dispose(); _page2BottomTitleController.dispose(); _controller.dispose(); super.dispose(); } @override Widget build(context) { if (!_controller.initialized) { precacheImage(AssetImage('images/artist_1.png', package: App.pkg), context); precacheImage(AssetImage('images/artist_2.png', package: App.pkg), context); precacheImage(AssetImage('images/artist_3.png', package: App.pkg), context); precacheImage(AssetImage('images/noise.png', package: App.pkg), context); _controller.init(context); } _controller.setView(MediaQuery.of(context).size); return SafeArea( child: Scaffold( body: Stack( children: [ GestureDetector( onTapUp: _handleTap, child: _buildPages(), ), IndieAppBar(), Align( alignment: Alignment.bottomCenter, child: Padding( padding: EdgeInsets.only(bottom: 32), child: Indie3dNavigationIndicator(pageIndex: _pageIndex,)), ) ], ), ), ); } Widget _buildPages() { final result = NotificationListener<ScrollUpdateNotification>( onNotification: _handleScroll, child: PageView( scrollDirection: Axis.horizontal, onPageChanged: _handlePageChange, children: [ _buildPageForIndex(0), _buildPageForIndex(1), _buildPageForIndex(2), ], ), ); return result; } Widget _buildPageForIndex(int index) { Widget result; switch (index) { case 0: result = Indie3dPage( topTitle: 'MILES', bottomTitle: 'MILLER', backgroundColor: Color(0xFF0DD479), image: AssetImage('images/artist_1.png', package: App.pkg), pageIndex: 0, controller: _controller, topTitleClipProgress: 1.0 - _page0TopTitleController.value, bottomTitleClipProgress: 1.0 - _page0BottomTitleController.value, bottomTitleScale: 1.0, ); break; case 1: result = Indie3dPage( topTitle: 'BRET', bottomTitle: 'HAMPTON', backgroundColor: Color(0xFFECA6C8), image: AssetImage('images/artist_2.png', package: App.pkg), pageIndex: 1, controller: _controller, topTitleClipProgress: 1.0 - _page1TopTitleController.value, bottomTitleClipProgress: 1.0 - _page1BottomTitleController.value, backgroundShapeOpacity: 1.0, bottomTitleScale: 0.9, ); break; case 2: result = Indie3dPage( topTitle: 'CINDY', bottomTitle: 'GREY', backgroundColor: Color(0xFFFFD500), image: AssetImage('images/artist_3.png', package: App.pkg), pageIndex: 2, controller: _controller, topTitleClipProgress: 1.0 - _page2TopTitleController.value, bottomTitleClipProgress: 1.0 - _page2BottomTitleController.value, ); break; } return result; } bool _handleScroll(ScrollUpdateNotification scrollUpdate) { setState(() { final appSize = MediaQuery.of(context).size; double pageProgress = (1.0 - ((scrollUpdate.metrics.pixels / appSize.width) - _pageIndex) .abs().clamp(0.0, 1.0)) * 2.0 - 1.0; _controller.cameraOffset = (1 - pageProgress) * 8.0 * scrollUpdate.scrollDelta.sign; double animValue = 0; switch (_pageIndex) { case 0: animValue = _page0TopTitleController.value; break; case 1: animValue = _page1TopTitleController.value; break; case 2: animValue = _page2TopTitleController.value; break; } if (animValue != 0) { switch (_pageIndex) { case 0: if (!_page0TopTitleController.isAnimating) { _page0TopTitleController.value = pageProgress; _page0BottomTitleController.value = pageProgress; } break; case 1: if (!_page1TopTitleController.isAnimating) { _page1TopTitleController.value = pageProgress; _page1BottomTitleController.value = pageProgress; } break; case 2: if (!_page2TopTitleController.isAnimating) { _page2TopTitleController.value = pageProgress; _page2BottomTitleController.value = pageProgress; } break; } } switch (_pageIndex) { case 0: if (pageProgress > 0.99) { _page0TopTitleController.animateTo(1.0); Future.delayed(Duration(milliseconds: 200), () => _page0BottomTitleController.animateTo(1.0) ); } _page1TopTitleController.reset(); _page1BottomTitleController.reset(); _page2TopTitleController.reset(); _page2BottomTitleController.reset(); break; case 1: _page0TopTitleController.reset(); _page0BottomTitleController.reset(); if (pageProgress > 0.99) { _page1TopTitleController.animateTo(1.0); Future.delayed(Duration(milliseconds: 200), () => _page1BottomTitleController.animateTo(1.0) ); } _page2TopTitleController.reset(); _page2BottomTitleController.reset(); break; case 2: _page0TopTitleController.reset(); _page0BottomTitleController.reset(); _page1TopTitleController.reset(); _page1BottomTitleController.reset(); if (pageProgress > 0.99) { _page2TopTitleController.animateTo(1.0); Future.delayed(Duration(milliseconds: 200), () => _page2BottomTitleController.animateTo(1.0) ); } break; } }); return false; } void _handleTap(TapUpDetails details) { _controller.triggerTap(context, details.localPosition, _pageIndex); } void _handlePageChange(int page) { setState(() { _pageIndex = page; }); } }
0
mirrored_repositories/flutter_showcase/example/apps/indie_3d
mirrored_repositories/flutter_showcase/example/apps/indie_3d/lib/navigation.dart
import 'package:flutter/material.dart'; class Indie3dNavigationIndicator extends StatelessWidget { final int pageIndex; Indie3dNavigationIndicator({ this.pageIndex = 0 }); @override Widget build(context) { final activeColor = Color(0xFFFFFFFF); final defaultColor = Color(0xFFAAAAAA); final double width = 20; final double height = 5; return Row( mainAxisSize: MainAxisSize.min, children: [ Container( width: width, height: height, margin: EdgeInsets.all(2), color: pageIndex == 0 ? activeColor : defaultColor, ), Container( width: width, height: height, margin: EdgeInsets.all(2), color: pageIndex == 1 ? activeColor : defaultColor, ), Container( width: width, height: height, margin: EdgeInsets.all(2), color: pageIndex == 2 ? activeColor : defaultColor, ), ], ); } }
0
mirrored_repositories/flutter_showcase/example/apps/_shared
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/env.dart
class Env { static bool isGalleryActive = false; //Utility functions to allow us to nest flutter projects within a parent application, without breaking fonts/image assets. //To facilitate this, the package value must be null when used in the primary project, but non-null when used from within the parent app. static String getPackage(String value) => isGalleryActive? value : null; static String getBundle(String value) => "packages/$value"; /** * USAGE //In main App() class static String _pkg = "constellations_list"; static String get pkg => Env.getPackage(_pkg); static String get bundle => Env.getBundle(_pkg); //Anywhere in app TextStyle(fontFamily: "Poppins", package: App.pkg); Image.asset("images/logo.png", package: App.pkg); rootBundle.load('${App.bundle}/assets/glow.png') IMPORTANT: If using rootBundle.load(), there's 2 additional steps: 1. Move your assets into /lib, for example /lib/images/img.png 2. Include the assets in pubspec.yaml, using the package syntax: /packages/mypackagename/images/img.png Note: You only have to do this for assets that are loaded with rootBundle(), the rest can stay in the root directory of your project */ }
0
mirrored_repositories/flutter_showcase/example/apps/_shared/lib
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/physics/constrained_scroll_physics.dart
import 'package:flutter/material.dart'; import 'dart:math' as math; import 'package:flutter/physics.dart'; class ConstrainedScrollPhysics extends BouncingScrollPhysics { final double maxOverscroll; final double maxOverscrollFactor; const ConstrainedScrollPhysics({ ScrollPhysics parent, this.maxOverscrollFactor, this.maxOverscroll }) : assert(maxOverscroll != null || maxOverscrollFactor != null), super(parent: parent); @override ConstrainedScrollPhysics applyTo(ScrollPhysics ancestor) { return ConstrainedScrollPhysics(parent: buildParent(ancestor), maxOverscroll:maxOverscroll, maxOverscrollFactor:maxOverscrollFactor); } @override double applyPhysicsToUserOffset(ScrollMetrics position, double offset) { if (!position.outOfRange) return offset; final double overscrollPastStart = math.max(position.minScrollExtent - position.pixels, 0.0); final double overscrollPastEnd = math.max(position.pixels - position.maxScrollExtent, 0.0); final double overscrollPast = math.max(overscrollPastStart, overscrollPastEnd); final double direction = offset.sign; final double cur = offset + overscrollPast; final double max = maxOverscroll ?? maxOverscrollFactor * position.viewportDimension; final double ratio = math.max(0, 1-cur/max); return direction * offset.abs() * ratio; } @override SpringDescription get spring => SpringDescription.withDampingRatio( mass: 0.15, // 0.5 stiffness: 250.0, // 100 ratio: 1.25, // 1.1 ); }
0
mirrored_repositories/flutter_showcase/example/apps/_shared/lib
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/math/transform.dart
/// Linearly maps values in the range (0, pIn) to (0, pOut) and values in the range (pIn, 1) to (pOut, 1) double piecewiseSinglePointLinearTransform(double pIn, double pOut, double x) { final lowerScale = pOut / pIn; final upperScale = (1.0 - pOut) / (1.0 - pIn); final upperOffset = 1.0 - upperScale; return x < pIn ? x * lowerScale : x * upperScale + upperOffset; }
0
mirrored_repositories/flutter_showcase/example/apps/_shared/lib
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui/sprite.dart
import 'dart:ui' as ui; import 'package:flutter/widgets.dart'; class Sprite extends StatefulWidget { final ImageProvider image; final int frameWidth; final int frameHeight; final num frame; Sprite({ Key key, @required this.image, @required this.frameWidth, this.frameHeight, this.frame=0 }): super(key: key); @override _SpriteState createState() => _SpriteState(); } class _SpriteState extends State<Sprite> { ImageStream _imageStream; ImageInfo _imageInfo; @override void initState() { super.initState(); } @override void didChangeDependencies() { super.didChangeDependencies(); _getImage(); } @override void didUpdateWidget(Sprite oldWidget) { super.didUpdateWidget(oldWidget); if (widget.image != oldWidget.image) { _getImage(); } } void _getImage() { final ImageStream oldImageStream = _imageStream; _imageStream = widget.image.resolve(createLocalImageConfiguration(context)); if (_imageStream.key == oldImageStream?.key) { return; } final ImageStreamListener listener = ImageStreamListener(_updateImage); oldImageStream?.removeListener(listener); _imageStream.addListener(listener); } void _updateImage(ImageInfo imageInfo, bool synchronousCall) { setState(() { _imageInfo = imageInfo; }); } @override void dispose() { _imageStream?.removeListener(ImageStreamListener(_updateImage)); super.dispose(); } @override Widget build(BuildContext context) { ui.Image img = _imageInfo?.image; if (img == null) { return SizedBox(); } int w = img.width, frame = widget.frame.round(); int frameW = widget.frameWidth, frameH = widget.frameHeight; int cols = (w / frameW).floor(); int col = frame % cols, row = (frame / cols).floor(); ui.Rect rect = ui.Rect.fromLTWH(col * frameW * 1.0, row * frameH * 1.0, frameW * 1.0, frameH * 1.0); return CustomPaint(painter: _SpritePainter(img, rect)); } } class _SpritePainter extends CustomPainter { ui.Image image; ui.Rect rect; _SpritePainter(this.image, this.rect); @override void paint(Canvas canvas, Size size) { canvas.drawImageRect(image, rect, ui.Rect.fromLTWH(0.0, 0.0, size.width, size.height), Paint()); } @override bool shouldRepaint(_SpritePainter oldPainter) { return oldPainter.image != image || oldPainter.rect != rect; } }
0
mirrored_repositories/flutter_showcase/example/apps/_shared/lib
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui/path_util.dart
import 'dart:ui' as ui; /// Returns the subset of the input path from start to end /// `start` and `end` are normalized in the range (0.0, 1.0) ui.Path extractPartialPath(ui.Path path, double start, double end) { assert(0.0 <= start && start <= 1.0); assert(0.0 <= end && end <= 1.0); assert(start < end); var result = ui.Path(); final metrics = path.computeMetrics().toList(); var totalLength = 0.0; for (var m in metrics) { totalLength += m.length; } final startPos = start * totalLength; final endPos = end * totalLength; var l = 0.0; for (var m in metrics) { final localStartPos = (startPos - l).clamp(0.0, m.length); final localEndPos = (endPos - l).clamp(0.0, m.length); if (localStartPos < localEndPos) result.addPath(m.extractPath(localStartPos, localEndPos), ui.Offset.zero); l += m.length; } return result; }
0
mirrored_repositories/flutter_showcase/example/apps/_shared/lib
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui/widget_model.dart
import 'dart:ui' as ui; import 'dart:async'; import 'dart:math' as math; import 'dart:typed_data'; import 'package:path/path.dart' as path; import 'package:vector_math/vector_math.dart' as vec32; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() => runApp(OBJApp()); class OBJApp extends StatelessWidget { @override Widget build(context) { return MaterialApp( home: OBJHome(), ); } } class OBJHome extends StatelessWidget { @override Widget build(context) { return Container( color: Color(0xFF223388), child: OBJViewer(), ); } } class OBJViewer extends StatefulWidget { @override State createState() { return OBJViewerState(); } } class OBJViewerState extends State<OBJViewer> { VertexMesh _mesh; VertexMeshInstance _meshInstance; vec32.Quaternion _rotation; OBJViewerState() : _rotation = vec32.Quaternion.identity(); @override void initState() { _loadMesh(); super.initState(); } @override Widget build(context) { return GestureDetector( onPanUpdate: _handleDragUpdate, child: CustomPaint( painter: MeshCustomPainter(_meshInstance), ), ); } Future<void> _loadMesh() async { _mesh = await loadVertexMeshFromOBJAsset(context, 'assets', 'thing.obj'); _updateTransform(); } void _handleDragUpdate(DragUpdateDetails dragUpdateDetails) { _rotation *= vec32.Quaternion.axisAngle(vec32.Vector3(0.0, 1.0, 0.0), dragUpdateDetails.delta.dx / 100); _rotation *= vec32.Quaternion.axisAngle(vec32.Vector3(1.0, 0.0, 0.0), dragUpdateDetails.delta.dy / 100); _rotation.normalize(); _updateTransform(); } void _updateTransform() { final modelMatrix = vec32.Matrix4.compose(vec32.Vector3.zero(), _rotation, vec32.Vector3.all(1.0)); final viewMatrix = vec32.makeViewMatrix( vec32.Vector3(0.0, 0.0, 4.0), vec32.Vector3(0.0, 0.0, 0.0), vec32.Vector3(0.0, 1.0, 0.0)); final projMatrix = vec32.makePerspectiveMatrix(math.pi / 2.0, 320.0 / 480.0, 0.01, 100.0); setState(() { _meshInstance = VertexMeshInstance(_mesh) ..setTransform(viewMatrix * modelMatrix, projMatrix); }); } } class OBJLoaderMaterial { String name; Color diffuseColor; String texturePath; ui.Image texture; } class OBJLoaderFace { List<vec32.Vector3> _positions; List<vec32.Vector3> _normals; List<vec32.Vector2> _uvs; String materialName; OBJLoaderFace() : _positions = List<vec32.Vector3>(3), _normals = List<vec32.Vector3>(3), _uvs = List<vec32.Vector2>(3); List<vec32.Vector3> get positions => _positions; List<vec32.Vector3> get normals => _normals; List<vec32.Vector2> get uvs => _uvs; } class OBJLoader { AssetBundle _bundle; String _basePath; String _objPath; String _mtlPath; String _objSource; String _mtlSource; List<OBJLoaderFace> _faces; Map<String, OBJLoaderMaterial> _materials; OBJLoader(this._bundle, this._basePath, this._objPath) : _faces = <OBJLoaderFace>[], _materials = Map<String, OBJLoaderMaterial>(); Future<VertexMesh> parse() async { String p = path.join(_basePath, _objPath); _objSource = await _bundle.loadString(p); _parseOBJFile(); p = path.join(_basePath, _mtlPath); _mtlSource = await _bundle.loadString(p); _parseMTLFile(); await _loadMTLTextures(); return _buildVertexMesh(); } void _parseOBJFile() { List<vec32.Vector3> positions = <vec32.Vector3>[]; List<vec32.Vector3> normals = <vec32.Vector3>[]; List<vec32.Vector2> uvs = <vec32.Vector2>[]; String currentMaterialName; final objLines = _objSource.split('\n'); for (var line in objLines) { line = line.replaceAll("\r", ""); if (line.startsWith('v ')) { final args = line.split(' '); // args[0] = 'v' args[1..3] = position coords positions.add(vec32.Vector3(double.parse(args[1]), double.parse(args[2]), double.parse(args[3]))); } else if (line.startsWith('vn ')) { final args = line.split(' '); // args[0] = 'vn' args[1..3] = normal coords normals.add(vec32.Vector3(double.parse(args[1]), double.parse(args[2]), double.parse(args[3]))); } else if (line.startsWith('vt ')) { final args = line.split(' '); // args[0] = 'vt' args[1..2] = texture coords uvs.add(vec32.Vector2(double.parse(args[1]), double.parse(args[2]))); } else if (line.startsWith('f ')) { final args = line.split(' '); // We only support loading meshs with triangulated faces assert(args.length == 4); final v0 = args[1].split('/'); final v1 = args[2].split('/'); final v2 = args[3].split('/'); final face = OBJLoaderFace(); face.positions[0] = positions[int.parse(v0[0]) - 1]; face.positions[1] = positions[int.parse(v1[0]) - 1]; face.positions[2] = positions[int.parse(v2[0]) - 1]; if (normals.isNotEmpty) { face.normals[0] = normals[int.parse(v0[2]) - 1]; face.normals[1] = normals[int.parse(v1[2]) - 1]; face.normals[2] = normals[int.parse(v2[2]) - 1]; } else { face.normals[0] = face.normals[1] = face.normals[2] = vec32.Vector3.zero(); } if (uvs.isNotEmpty) { face.uvs[0] = uvs[int.parse(v0[1]) - 1]; face.uvs[1] = uvs[int.parse(v1[1]) - 1]; face.uvs[2] = uvs[int.parse(v2[1]) - 1]; } else { face.uvs[0] = face.uvs[1] = face.uvs[2] = vec32.Vector2.zero(); } face.materialName = currentMaterialName; _faces.add(face); } else if (line.startsWith('o ')) { // TODO: Load multiple objects } else if (line.startsWith('mtllib ')) { _mtlPath = line.split(' ')[1]; } else if (line.startsWith('usemtl ')) { currentMaterialName = line.split(' ')[1]; } else if (line.startsWith('s ')) { // TODO: Set scale value } } } void _parseMTLFile() { final mtlLines = _mtlSource.split('\n'); OBJLoaderMaterial currentMaterial; for (var line in mtlLines) { line = line.replaceAll("\r", ""); if (line.startsWith('newmtl ')) { if (currentMaterial != null) _materials[currentMaterial.name] = currentMaterial; currentMaterial = OBJLoaderMaterial(); currentMaterial.name = line.split(' ')[1]; } else if (line.startsWith('Kd ')) { if (currentMaterial != null) { final args = line.split(' '); currentMaterial.diffuseColor = Color.fromARGB( 255, (double.parse(args[1]) * 255).round(), (double.parse(args[2]) * 255).round(), (double.parse(args[3]) * 255).round()); } } else if (line.startsWith('map_Kd ')) { if (currentMaterial != null) { final args = line.split(' '); currentMaterial.texturePath = args[1]; } } } if (currentMaterial != null) _materials[currentMaterial.name] = currentMaterial; } Future<void> _loadMTLTextures() async { List<Future<void>> _imageFutures = <Future<void>>[]; for (var mtl in _materials.values) { if (mtl.texturePath != null) { print('loading texture: ${mtl.texturePath}'); final c = Completer<void>(); _imageFutures.add(c.future); AssetImage(path.join(_basePath, mtl.texturePath), bundle: _bundle).resolve(ImageConfiguration()).addListener( ImageStreamListener((ImageInfo info, bool _) { print('loaded texture: ${mtl.texturePath}'); mtl.texture = info.image; c.complete(); }), ); } } await Future.wait(_imageFutures); } VertexMesh _buildVertexMesh() { // TODO: Improve mesh building algorithm by deduplicating vertices Float32List positions = Float32List(_faces.length * 3 * 3); Float32List normals = Float32List(_faces.length * 3 * 3); Float32List uvs = Float32List(_faces.length * 3 * 2); Int32List colors = Int32List(_faces.length * 3); Uint16List indices = Uint16List(_faces.length * 3); // TODO: Combine multiple material textures into one and offset uv's accordingly ui.Image texture = _materials.values.first.texture; for (int i = 0; i < _faces.length; ++i) { positions[i * 9 + 0] = _faces[i].positions[0].x; positions[i * 9 + 1] = _faces[i].positions[0].y; positions[i * 9 + 2] = _faces[i].positions[0].z; positions[i * 9 + 3] = _faces[i].positions[1].x; positions[i * 9 + 4] = _faces[i].positions[1].y; positions[i * 9 + 5] = _faces[i].positions[1].z; positions[i * 9 + 6] = _faces[i].positions[2].x; positions[i * 9 + 7] = _faces[i].positions[2].y; positions[i * 9 + 8] = _faces[i].positions[2].z; normals[i * 9 + 0] = _faces[i].normals[0].x; normals[i * 9 + 1] = _faces[i].normals[0].y; normals[i * 9 + 2] = _faces[i].normals[0].z; normals[i * 9 + 3] = _faces[i].normals[1].x; normals[i * 9 + 4] = _faces[i].normals[1].y; normals[i * 9 + 5] = _faces[i].normals[1].z; normals[i * 9 + 6] = _faces[i].normals[2].x; normals[i * 9 + 7] = _faces[i].normals[2].y; normals[i * 9 + 8] = _faces[i].normals[2].z; uvs[i * 6 + 0] = _faces[i].uvs[0].x; uvs[i * 6 + 1] = _faces[i].uvs[0].y; uvs[i * 6 + 2] = _faces[i].uvs[1].x; uvs[i * 6 + 3] = _faces[i].uvs[1].y; uvs[i * 6 + 4] = _faces[i].uvs[2].x; uvs[i * 6 + 5] = _faces[i].uvs[2].y; colors[i * 3 + 0] = _materials[_faces[i].materialName].diffuseColor.value; colors[i * 3 + 1] = _materials[_faces[i].materialName].diffuseColor.value; colors[i * 3 + 2] = _materials[_faces[i].materialName].diffuseColor.value; indices[i * 3 + 0] = i * 3 + 0; indices[i * 3 + 1] = i * 3 + 1; indices[i * 3 + 2] = i * 3 + 2; } return VertexMesh() ..positions = positions ..normals = normals ..uvs = uvs ..colors = colors ..indices = indices ..texture = texture; } } Future<VertexMesh> loadVertexMeshFromOBJAsset( BuildContext context, String basePath, String path) async { final bundle = DefaultAssetBundle.of(context); final loader = OBJLoader(bundle, basePath, path); return loader.parse(); } class VertexMesh { /// 3D local space position vertex data Float32List positions; /// 3D local space normal vertex data Float32List normals; /// 2D texture space uv vertex data Float32List uvs; /// Material vertex color's Int32List colors; /// Triangle indices Uint16List indices; /// Material texture ui.Image texture; VertexMesh(); int get vertexCount => positions.length ~/ 3; void log() { for (int i = 0; i < indices.length; i += 3) { var x0 = positions[indices[i + 0] * 3 + 0]; var y0 = positions[indices[i + 0] * 3 + 1]; var z0 = positions[indices[i + 0] * 3 + 2]; var x1 = positions[indices[i + 1] * 3 + 0]; var y1 = positions[indices[i + 1] * 3 + 1]; var z1 = positions[indices[i + 1] * 3 + 2]; var x2 = positions[indices[i + 2] * 3 + 0]; var y2 = positions[indices[i + 2] * 3 + 1]; var z2 = positions[indices[i + 2] * 3 + 2]; print('f: {' + x0.toStringAsFixed(3) + ', ' + y0.toStringAsFixed(3) + ', ' + z0.toStringAsFixed(3) + '}, {' + x1.toStringAsFixed(3) + ', ' + y1.toStringAsFixed(3) + ', ' + z1.toStringAsFixed(3) + '}, {' + x2.toStringAsFixed(3) + ', ' + y2.toStringAsFixed(3) + ', ' + z2.toStringAsFixed(3) + '}'); } } } class VertexMeshInstance { VertexMesh _mesh; /// Post transform draw ready vertices ui.Vertices _vertices; vec32.Matrix4 _modelView; vec32.Matrix4 _projection; bool _vertexCacheInvalid; VertexMeshInstance(this._mesh) : _vertexCacheInvalid = true; void setTransform(vec32.Matrix4 modelView, vec32.Matrix4 projection) { _modelView = modelView; _projection = projection; _vertexCacheInvalid = true; } ui.Vertices get vertices { if (_vertexCacheInvalid) _cacheVertices(); return _vertices; } ui.Image get texture { return _mesh.texture; } void _cacheVertices() { // Create vertices from mesh data List<vec32.Vector4> transformedPositions = List<vec32.Vector4>(_mesh.vertexCount); List<int> culledIndices = <int>[]; final transform = _projection * _modelView; // Transform vertices for (int i = 0; i < _mesh.vertexCount; ++i) { vec32.Vector4 position = vec32.Vector4( _mesh.positions[i * 3 + 0], _mesh.positions[i * 3 + 1], _mesh.positions[i * 3 + 2], 1.0); position = transform.transform(position); position.xyz /= position.w; transformedPositions[i] = position; } // Cull back faces for (int i = 0; i < _mesh.indices.length; i += 3) { final a = transformedPositions[_mesh.indices[i + 0]].xyz; final b = transformedPositions[_mesh.indices[i + 1]].xyz; final c = transformedPositions[_mesh.indices[i + 2]].xyz; final ab = b - a; final ac = c - a; if (ab.cross(ac).z > 0.0) { // Insert the faces that are visible (vertices with ccw winding with a normal pointed towards the camera) culledIndices.add(_mesh.indices[i + 0]); culledIndices.add(_mesh.indices[i + 1]); culledIndices.add(_mesh.indices[i + 2]); } } // Depth sort { final tmpCulledIndices = List<int>.from(culledIndices); assert(tmpCulledIndices.length == culledIndices.length); _triangleMergeSortSplit(transformedPositions, culledIndices, tmpCulledIndices, 0, culledIndices.length ~/ 3); } // Build 2d positions array Float32List positions2D = Float32List(_mesh.vertexCount * 2); for (int i = 0; i < _mesh.vertexCount; ++i) { // Transformed positions are in ndc space, transform that into view coords positions2D[i * 2 + 0] = transformedPositions[i].x; positions2D[i * 2 + 1] = transformedPositions[i].y; } // Basic light Int32List colors = Int32List(_mesh.vertexCount); final normalTransform = _modelView.getNormalMatrix(); for (int i = 0; i < colors.length; ++i) { final xn = normalTransform.transform(vec32.Vector3( _mesh.normals[i * 3 + 0], _mesh.normals[i * 3 + 1], _mesh.normals[i * 3 + 2], ).normalized()); final b = 1.0;//xn.dot(vec32.Vector3(0.5, 0.5, 1.0).normalized()).clamp(0.1, 1.0); colors[i] = 0xFF000000 | ((b * ((_mesh.colors[i] >> 16) & 0xFF)).floor() << 16) | ((b * ((_mesh.colors[i] >> 8) & 0xFF)).floor() << 8) | ((b * ((_mesh.colors[i] >> 0) & 0xFF)).floor() << 0); } _vertices = ui.Vertices.raw(VertexMode.triangles, positions2D, indices: Uint16List.fromList(culledIndices), textureCoordinates: _mesh.uvs, colors: colors); _vertexCacheInvalid = false; } } class MeshCustomPainter extends CustomPainter { VertexMeshInstance _meshInstance; MeshCustomPainter(this._meshInstance); @override void paint(canvas, size) { canvas.scale(size.width * 0.5, size.height * 0.5); canvas.translate(1.0, 1.0); // Flip y canvas.scale(1, -1); if (_meshInstance != null) { final paint = Paint(); if (_meshInstance.texture != null) { paint.shader = ImageShader( _meshInstance.texture, TileMode.clamp, TileMode.clamp, Matrix4.identity().scaled( 1 / _meshInstance.texture.width, 1 / _meshInstance.texture.height, 1.0 ).storage); } canvas.drawVertices(_meshInstance.vertices, BlendMode.multiply, paint); } } @override bool shouldRepaint(MeshCustomPainter oldPainter) { // TODO: Do an actual state diff to check for repaint return true; } } bool _compareDepth(List<vec32.Vector4> positions, List<int> src, int indexA, int indexB) { double depthA, depthB; { final a = positions[src[indexA * 3 + 0]]; final b = positions[src[indexA * 3 + 1]]; final c = positions[src[indexA * 3 + 2]]; depthA = (a.z + b.z + c.z) / 3.0; } { final a = positions[src[indexB * 3 + 0]]; final b = positions[src[indexB * 3 + 1]]; final c = positions[src[indexB * 3 + 2]]; depthB = (a.z + b.z + c.z) / 3.0; } return depthA > depthB; } void _triangleMergeSortMerge(List<vec32.Vector4> positions, List<int> dst, List<int> src, int begin, int middle, int end) { assert(begin < middle && middle < end); int j = begin, k = middle; for (int i = begin; i < end; ++i) { if (j < middle && (k >= end || _compareDepth(positions, src, j, k))) { dst[i * 3 + 0] = src[j * 3 + 0]; dst[i * 3 + 1] = src[j * 3 + 1]; dst[i * 3 + 2] = src[j * 3 + 2]; ++j; } else { dst[i * 3 + 0] = src[k * 3 + 0]; dst[i * 3 + 1] = src[k * 3 + 1]; dst[i * 3 + 2] = src[k * 3 + 2]; ++k; } } } void _triangleMergeSortSplit(List<vec32.Vector4> positions, List<int> dst, List<int> src, int begin, int end) { final count = end - begin; final middle = begin + count ~/ 2; if (count > 2) { _triangleMergeSortSplit(positions, src, dst, begin, middle); _triangleMergeSortSplit(positions, src, dst, middle, end); _triangleMergeSortMerge(positions, dst, src, begin, middle, end); } }
0
mirrored_repositories/flutter_showcase/example/apps/_shared/lib
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui/widget_mask.dart
import 'package:flutter/material.dart'; import 'package:flutter/painting.dart'; import 'package:flutter/rendering.dart'; import 'dart:ui'; /// Acts exactly like a `Stack` however the first child acts like an alpha mask when rendering the rest of the children class RenderWidgetMask extends RenderStack { RenderWidgetMask( {List<RenderBox> children, AlignmentGeometry alignment, TextDirection textDirection, StackFit fit, Overflow overflow}) : super( children: children, alignment: alignment, textDirection: textDirection, fit: fit, overflow: overflow); @override void paintStack(context, offset) { // Early exit on no children if (firstChild == null) return; final paintContent = (PaintingContext context, Offset offset) { // Paint all but the first child RenderBox child = (firstChild.parentData as StackParentData).nextSibling; while (child != null) { final childParentData = child.parentData as StackParentData; context.paintChild(lastChild, offset + childParentData.offset); child = childParentData.nextSibling; } }; final paintMask = (PaintingContext context, Offset offset) { context.paintChild(firstChild, offset + (firstChild.parentData as StackParentData).offset); }; final paintEverything = (PaintingContext context, Offset offset) { paintContent(context, offset); context.canvas.saveLayer(offset & size, Paint()..blendMode=BlendMode.dstIn); paintMask(context, offset); context.canvas.restore(); }; // Force the foreground content to be composited onto this layer context.pushOpacity(offset, 255, paintEverything); } } /// Is a simple wrapper around the `Stack` widget that creates a custom stack based render object class WidgetMask extends Stack { WidgetMask( {Key key, AlignmentGeometry alignment = AlignmentDirectional.topStart, TextDirection textDirection, StackFit fit = StackFit.loose, Overflow overflow = Overflow.clip, @required Widget maskChild, @required Widget child}) : super( key: key, alignment: alignment, textDirection: textDirection, fit: fit, overflow: overflow, children: [maskChild, child], ); @override RenderStack createRenderObject(context) { return RenderWidgetMask( alignment: alignment, textDirection: textDirection ?? Directionality.of(context), fit: fit, overflow: overflow, ); } @override void updateRenderObject(BuildContext context, RenderWidgetMask renderObject) { renderObject ..alignment = alignment ..textDirection = textDirection ?? Directionality.of(context) ..fit = fit ..overflow = overflow; } }
0
mirrored_repositories/flutter_showcase/example/apps/_shared/lib
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui/custom_paint_mask.dart
import 'package:flutter/material.dart'; import 'package:flutter/painting.dart'; import 'package:flutter/rendering.dart'; class RenderCustomPaintMask extends RenderProxyBox { CustomPainter _painter; RenderCustomPaintMask({ @required CustomPainter painter }) : _painter = painter; @override void paint(context, offset) { final paintContent = (PaintingContext context, Offset offset) { // Paint foreground super.paint(context, offset); }; final paintMask = (PaintingContext context, Offset offset) { if (offset != Offset.zero) context.canvas.translate(offset.dx, offset.dy); _painter.paint(context.canvas, size); }; final paintEverything = (PaintingContext context, Offset offset) { paintContent(context, offset); context.canvas.saveLayer(offset & size, Paint()..blendMode=BlendMode.dstIn); paintMask(context, offset); context.canvas.restore(); }; context.pushOpacity(offset, 255, paintEverything); } } /// This widget is used to mask `child` using `painter` /// Anything rendered with `painter` acts as an alpha mask for child (child is transparent by default), the color of anything rendered with `painter` is ignored /// /// See also: /// - [CustomPainter](in the rendering library), for information on how to implement `painter` class CustomPaintMask extends SingleChildRenderObjectWidget { final CustomPainter _painter; CustomPaintMask({@required CustomPainter painter, Key key, Widget child }) : _painter = painter, super(key: key, child: child); @override RenderObject createRenderObject(context) { return RenderCustomPaintMask(painter: _painter); } @override void updateRenderObject(BuildContext context, RenderCustomPaintMask renderObject) { renderObject._painter = _painter; } }
0
mirrored_repositories/flutter_showcase/example/apps/_shared/lib
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui/animated_sprite.dart
import 'package:flutter/widgets.dart'; import 'package:shared/ui/sprite.dart'; class AnimatedSprite extends AnimatedWidget { final ImageProvider image; final int frameWidth; final int frameHeight; AnimatedSprite({ Key key, @required this.image, @required this.frameWidth, this.frameHeight, @required Animation<double> animation, }): super(key: key, listenable: animation); @override Widget build(BuildContext context) { final animation = listenable as Animation<double>; return Sprite( image: image, frameWidth: frameWidth, frameHeight: frameHeight, frame: animation.value, ); } }
0
mirrored_repositories/flutter_showcase/example/apps/_shared/lib
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui/blend_mask.dart
import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; // Applies a BlendMode to its child. class BlendMask extends SingleChildRenderObjectWidget { final BlendMode _blendMode; final double _opacity; BlendMask({@required BlendMode blendMode, double opacity = 1.0, Key key, Widget child }) : _blendMode = blendMode, _opacity = opacity, super(key: key, child: child); @override RenderObject createRenderObject(context) { return RenderBlendMask(_blendMode, _opacity); } @override void updateRenderObject(BuildContext context, RenderBlendMask renderObject) { renderObject._blendMode = _blendMode; renderObject._opacity = _opacity; } } class RenderBlendMask extends RenderProxyBox { BlendMode _blendMode; double _opacity; RenderBlendMask(BlendMode blendMode, double opacity) : _blendMode = blendMode, _opacity = opacity; @override void paint(context, offset) { // Create a new layer and specify the blend mode and opacity to composite it with: context.canvas.saveLayer(offset & size, Paint()..blendMode=_blendMode..color=Color.fromARGB((_opacity * 255).round(), 255, 255, 255)); super.paint(context, offset); // Composite the layer back into the canvas using the blendmode: context.canvas.restore(); } }
0
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui/placeholder/placeholder_image.dart
import 'package:flutter/material.dart'; class PlaceholderImage extends StatelessWidget { final double width; final double height; final double cornerRadius; final Color color; final Color backgroundColor; const PlaceholderImage({Key key, this.cornerRadius = 4, this.color, this.backgroundColor, this.width = 100, this.height = 100}) : super(key: key); @override Widget build(BuildContext context) { var fgColor = color ?? Color(0xfff2f2f2); var bgColor = backgroundColor ?? Colors.white; return Container( width: width, height: height, decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), color: bgColor, ), margin: EdgeInsets.all(12), child: CustomPaint( painter: _ImagePainter(fgColor, bgColor), ), ); } } class _ImagePainter extends CustomPainter { final Color color; final Color backgroundColor; _ImagePainter(this.color, this.backgroundColor); @override void paint(Canvas canvas, Size size) { final paintForeground = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 4 ..strokeCap = StrokeCap.round ..strokeJoin = StrokeJoin.round ..color = color; //Draw mountains, size to width var width = size.width * .6; canvas.translate(size.width / 2 - width/2, size.height / 2 + (width * .7)/2); var path = Path() ..lineTo(width * .4, -width * .66) ..lineTo(width * .63, -width * .29) ..lineTo(width * .74, -width * .44) ..lineTo(width, 0) ..lineTo(0, 0); //Paint twice, for both stroke and fill canvas.drawPath(path, paintForeground); paintForeground.style = PaintingStyle.fill; canvas.drawPath(path, paintForeground); //Draw sun canvas.drawCircle(Offset(width * .9, -width * .7), width * .1, paintForeground); } @override bool shouldRepaint(CustomPainter oldDelegate) { return false; } }
0
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui/placeholder/placeholder_card_tall.dart
import 'dart:math'; import 'package:flutter/material.dart'; class PlaceholderCardTall extends StatelessWidget { final double width; final double height; final double cornerRadius; final Color color; final Color backgroundColor; const PlaceholderCardTall({Key key, this.cornerRadius = 4, this.color, this.backgroundColor, this.width = 400, this.height}) : super(key: key); @override Widget build(BuildContext context) { var r = Random(); var fgColor = color ?? Color(0xfff2f2f2); double lineHeight = 14; return Container( width: width ?? double.infinity, height: height ?? double.infinity, decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), color: backgroundColor ?? Colors.white, ), padding: EdgeInsets.all(20), child: Stack( children: <Widget>[ //Circle image Container( decoration: BoxDecoration(borderRadius: BorderRadius.circular(999), color: fgColor), height: 45, width: 45, ), //Title Container(margin: EdgeInsets.only(left: 65, top: 10), color: fgColor, height: lineHeight * 1.2, width: 100.0 + r.nextInt(100)), //Content Line Container(margin: EdgeInsets.only(top: 60, right: 10.0 + r.nextInt(60)), color: fgColor, height: lineHeight), //Content Line Container(margin: EdgeInsets.only(top: 85, right: 10.0 + r.nextInt(60)), color: fgColor, height: lineHeight), //Content Line Container(margin: EdgeInsets.only(top: 110, right: 10.0 + r.nextInt(60)), color: fgColor, height: lineHeight), //Content Line Container(margin: EdgeInsets.only(top: 135, right: 60.0 + r.nextInt(60)), color: fgColor, height: lineHeight), ], ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui/placeholder/placeholder_image_with_text.dart
import 'package:flutter/material.dart'; class PlaceholderImageWithText extends StatelessWidget { final double width; final double height; final double cornerRadius; final Color color; final Color backgroundColor; const PlaceholderImageWithText({Key key, this.cornerRadius = 0, this.color, this.backgroundColor, this.width = 100, this.height = 100}) : super(key: key); @override Widget build(BuildContext context) { var fgColor = color ?? Color(0xfff2f2f2); return Container( width: width, height: height, decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), color: backgroundColor ?? Colors.white, ), margin: EdgeInsets.all(10), child: Column( children: <Widget>[ Expanded(child: Container(color: fgColor)), Stack( children: <Widget>[ Container(color: fgColor, height: 16, margin: EdgeInsets.only(top: 12, left: 10, right: 70)), Container(color: fgColor, height: 10, margin: EdgeInsets.only(top: 40, left: 10, right: 30)), Container(color: fgColor, height: 10, margin: EdgeInsets.only(top: 56, left: 10, right: 10)), Container(color: fgColor, height: 10, margin: EdgeInsets.only(top: 72, left: 10, right: 60, bottom: 12)), ], ), ], ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui
mirrored_repositories/flutter_showcase/example/apps/_shared/lib/ui/placeholder/placeholder_card_short.dart
import 'dart:math'; import 'package:flutter/material.dart'; class PlaceholderCardShort extends StatelessWidget { final double width; final double height; final double cornerRadius; final Color color; final Color backgroundColor; const PlaceholderCardShort({Key key, this.cornerRadius = 4, this.color, this.backgroundColor, this.width = 400, this.height = 90 }) : super(key: key); @override Widget build(BuildContext context) { var r = Random(); var fgColor = color ?? Color(0xfff2f2f2); double lineHeight = 16; return Container( height: height, decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), color: backgroundColor ?? Colors.white, ), padding: EdgeInsets.all(26), child: Stack( children: <Widget>[ //Circle image Align( alignment: Alignment.centerRight, child: Container( margin: EdgeInsets.only(right: 8), decoration: BoxDecoration(borderRadius: BorderRadius.circular(4), color: fgColor), height: 32, width: 32, ), ), //Content Line Container(margin: EdgeInsets.only(right: 60.0 + r.nextInt(60)), color: fgColor, height: lineHeight ), //Content Line Container(margin: EdgeInsets.only(right: 80.0 + r.nextInt(120), top: lineHeight + 6), color: fgColor, height: lineHeight ), ], ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/form_mixin.dart
mixin FormMixin { Map<String, bool> validInputsMap = {}; double formCompletion = 0; bool isFormErrorVisible = false; void onItemValidate(String name, bool isValid, {String value}); void onItemChange(String name, String value); int countValidItems() { int count = 0; validInputsMap.forEach((name, isValid) { if (isValid) count++; }); return count; } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/styles.dart
import 'package:flutter/material.dart'; import 'main.dart'; class Styles { static double formRadius = 20; static double hzPadding = 37; static double vtFormPadding = 18; static Color primaryColor = Color(0xff00b27f); static Color secondaryColor = Color(0xff007b80); static Color baseColor = Color(0xff4a4a4a); static Color lightGrayColor = Color(0xffe6e6e6); static Color grayColor = Color(0xff505050); static Color darkGrayColor = Color(0xff2d2d2d); static Color helperColor = Color(0xff787878); static Color optionalColor = Color(0xffA7A7A7); static Color errorColor = Color(0xffea6060); static final BoxDecoration formContainerDecoration = BoxDecoration( color: Colors.white, boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 8)], border: Border.all(color: Color(0xffd4d4d4)), borderRadius: BorderRadius.vertical( top: Radius.circular(Styles.formRadius), ), ); static TextStyle barlow = TextStyle(fontFamily: "Barlow", package: App.pkg); static TextStyle baloo = TextStyle(fontFamily: "Baloo", package: App.pkg); static TextStyle appTitle1 = barlow.copyWith( color: Styles.primaryColor, fontWeight: FontWeight.w800, fontSize: 8, letterSpacing: 1.95, ); static TextStyle appTitle2 = baloo.copyWith( color: Styles.primaryColor, fontSize: 32, letterSpacing: -1.08, height: 1.1, decoration: TextDecoration.underline, decorationThickness: 1.2); static TextStyle formTitle = baloo.copyWith(color: Styles.primaryColor, height: 1, fontSize: 30, letterSpacing: 0.22); static TextStyle formSection = barlow.copyWith(fontSize: 16, fontWeight: FontWeight.w600, letterSpacing: 0.5, color: secondaryColor); static TextStyle imageBatch = barlow.copyWith(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16, letterSpacing: 0.5); static TextStyle productName = barlow.copyWith(fontWeight: FontWeight.w600, color: Styles.secondaryColor, letterSpacing: 0.63, fontSize: 20); static TextStyle productPrice = barlow.copyWith(fontWeight: FontWeight.w500, fontSize: 20, height: 1.8, letterSpacing: 0.63); static TextStyle orderLabel = barlow.copyWith(fontSize: 14, color: Styles.baseColor, letterSpacing: 0.44, fontWeight: FontWeight.w500); static TextStyle orderPrice = barlow.copyWith(fontSize: 14, color: Styles.baseColor, letterSpacing: 0.44, fontWeight: FontWeight.w600); static TextStyle orderTotalLabel = barlow.copyWith(fontSize: 16, color: Styles.baseColor, letterSpacing: 0.5, fontWeight: FontWeight.w500); static TextStyle orderTotal = barlow.copyWith(fontSize: 20, color: Styles.baseColor, letterSpacing: 0.63, fontWeight: FontWeight.bold); static TextStyle helperStyle = barlow.copyWith(fontSize: 16, color: helperColor, letterSpacing: 0.5, fontWeight: FontWeight.w500); static TextStyle inputStyle = barlow.copyWith(fontSize: 16, color: Styles.baseColor, letterSpacing: 0.5, fontWeight: FontWeight.w500); static TextStyle submitButtonText = barlow.copyWith(fontSize: 16, color: Colors.white, letterSpacing: 0.44, fontWeight: FontWeight.bold); static TextStyle labelOptional = barlow.copyWith(fontSize: 8, color: optionalColor, fontWeight: FontWeight.bold, letterSpacing: 1); static TextStyle labelNotValid = barlow.copyWith(fontSize: 8, color: errorColor, fontWeight: FontWeight.bold, letterSpacing: 1); static TextStyle labelRequired = barlow.copyWith(fontSize: 6, color: grayColor, fontWeight: FontWeight.bold, letterSpacing: .5); static TextStyle textButton = barlow.copyWith(fontSize: 16, color: Styles.secondaryColor, letterSpacing: 0.5, fontWeight: FontWeight.bold); static TextStyle optionsTitle = barlow.copyWith(fontSize: 20, color: Styles.darkGrayColor, letterSpacing: 0.63, fontWeight: FontWeight.w600); static TextStyle iconDropdown = baloo.copyWith( color: Styles.secondaryColor, fontSize: 27, ); static TextStyle formError = barlow.copyWith(fontSize: 12, color: errorColor, fontStyle: FontStyle.italic, letterSpacing: 0.38, fontWeight: FontWeight.w500); static TextStyle inputLabel = barlow.copyWith(fontSize: 16, color: Styles.baseColor, letterSpacing: 0.5, fontWeight: FontWeight.w600); static InputDecoration getInputDecoration({String helper}) { return InputDecoration( helperStyle: Styles.helperStyle, focusedBorder: OutlineInputBorder(borderSide: BorderSide(color: Styles.secondaryColor)), errorBorder: OutlineInputBorder(borderSide: BorderSide(color: Styles.errorColor)), enabledBorder: OutlineInputBorder(borderSide: BorderSide(color: Styles.lightGrayColor)), border: OutlineInputBorder(), errorStyle: TextStyle(color: Colors.transparent), helperText: '', hintText: helper, hintStyle: Styles.helperStyle, ); } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/plant_form_summary.dart
import 'package:flutter/material.dart'; import 'package:plant_forms/demo_data.dart'; import 'package:provider/provider.dart'; import 'components/section_separator.dart'; import 'components/stack_pages_route.dart'; import 'components/submit_button.dart'; import 'demo.dart'; import 'form_page.dart'; import 'plant_form_information.dart'; import 'main.dart'; import 'styles.dart'; class PlantFormSummary extends StatelessWidget { final double pageSize; final bool isHidden; const PlantFormSummary({Key key, this.pageSize, this.isHidden = false}) : super(key: key); @override Widget build(BuildContext context) { print("Rebuilding Summary @ ${DateTime.now().millisecondsSinceEpoch}"); return FormPage( pageSizeProportion: pageSize ?? 0.85, isHidden: isHidden, title: 'Order Summary', children: <Widget>[ _buildOrderSummary(), Separator(), _buildOrderInfo(), Separator(), _buildOrderTotal(), _buildOrderSpecialInstructions(context), SubmitButton( padding: EdgeInsets.symmetric(horizontal: Styles.hzPadding), child: Text('Next', style: Styles.submitButtonText), onPressed: () => _handleSubmit(context), ), ], ); } void _handleSubmit(BuildContext context) { Navigator.push( context, StackPagesRoute( previousPages: [PlantFormSummary(pageSize: .85, isHidden: true)], enterPage: PlantFormInformation(), ), ); } Widget _buildOrderSummary() { return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Stack( overflow: Overflow.visible, children: <Widget>[ Container( width: 135, height: 135, decoration: BoxDecoration( border: Border.all(color: Styles.grayColor), borderRadius: BorderRadius.circular(4), image: DecorationImage(image: AssetImage('images/plant_header_background.png', package: App.pkg))), ), Positioned( top: -10, right: -10, child: Container( width: 24, height: 24, decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), color: Styles.grayColor, ), child: Center(child: Text('1', style: Styles.imageBatch)), )), ], ), SizedBox(width: 36), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('Red Potted \nPlant w/ \nWhite Bowl', style: Styles.productName), Text('\$34.00', style: Styles.productPrice) ], ) ], ); } Widget _buildOrderInfo() { return Column( children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text('Subtotal', style: Styles.orderLabel), Text('\$34.00', style: Styles.orderPrice), ], ), SizedBox(height: 12), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text('Shipping', style: Styles.orderLabel), Text('FREE', style: Styles.orderPrice), ], ), ], ); } Widget _buildOrderTotal() { return Padding( padding: const EdgeInsets.only(bottom: 30.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text('Total', style: Styles.orderTotalLabel), Text('\$34.00', style: Styles.orderTotal), ], ), ); } Widget _buildOrderSpecialInstructions(BuildContext context) { String name = 'Special Instructions'; SharedFormState sharedState = Provider.of<SharedFormState>(context, listen: false); var values = sharedState.valuesByName; return TextFormField( onChanged: (value)=>values[FormKeys.instructions] = value, initialValue: values.containsKey(FormKeys.instructions)? values[FormKeys.instructions] : "", style: Styles.inputLabel, decoration: Styles.getInputDecoration(helper: name), minLines: 4, maxLines: 6, ); } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/demo_data.dart
class FormKeys { static String instructions = "instructions"; static String firstName = "first_name"; static String lastName = "last_name"; static String country = "country"; static String address = "address"; static String apt = "apt"; static String city = "city"; static String postal = "postal"; static String company = "company"; static String email = "email"; static String phone = "phone"; static String ccNumber = "ccNumber"; static String ccName = "ccName"; static String ccCode = "ccCode"; static String ccExpDate = "ccExpDate"; } class CountryData { static List<String> _countries = ['Canada', 'France', 'United States', 'Japan']; static List<String> _canadaProvinces = [ 'Alberta', 'British Columbia', 'Manitoba', 'New Brunswick', 'Newfoundland and Labrador', 'Northwest Territories', 'Nova Scotia', 'Nunavut', 'Ontario', 'Prince Edward Island', 'Quebec', 'Saskatchewan', 'Yukon', ]; static List<String> _japanPrefectures = [ 'Hokkaido', 'Aomori', 'Iwate', 'Miyagi', 'Akita', 'Yamagata', 'Fukushima', 'Ibaraki', 'Tochigi', 'Gunma', 'Saitama', 'Chiba', 'Tokyo', 'Kanagawa', 'Niigata', 'Toyama', 'Ishikawa', 'Fukui', 'Yamanashi', 'Nagano', 'Gifu', 'Shizuoka', 'Aichi', 'Mie', 'Shiga', 'Kyoto', 'Osaka', 'Hyogo', 'Nara', 'Wakayama', 'Tottori', 'Shimane', 'Okayama', 'Hiroshima', 'Yamaguchi', 'Tokushima', 'Kagawa', 'Ehime', 'Kochi', 'Fukuoka', 'Miyazaki', 'Nagasaki', 'Kumamoto', 'Kagoshima', 'Saga', 'Oita', 'Okinawa', ]; static List<String> _usaStates = [ 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'IllinoisIndiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'MontanaNebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' ]; static String getSubdivisionTitle(String country) { String subdivision = ''; switch (country) { case 'Canada': subdivision = 'Province'; break; case 'Japan': subdivision = 'Prefecture'; break; case 'United States': subdivision = 'State'; break; case 'France': break; } return subdivision; } static List<String> getCountries() => _countries; static List<String> getSubdivisionList(String subdivision) { switch (subdivision) { case 'Province': return _canadaProvinces; case 'Prefecture': return _japanPrefectures; case 'State': return _usaStates; default: return []; } } } enum InputType { text, email, number, telephone } enum CreditCardInputType { number, expirationDate, securityCode } enum CreditCardNetwork { visa, mastercard, amex }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/form_page.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'styles.dart'; class FormPage extends StatelessWidget { static Map<String, String> formState = {}; final List<Widget> children; final double pageSizeProportion; final GlobalKey<FormState> formKey; final String title; final bool isHidden; const FormPage({ Key key, this.title = '', this.formKey, this.isHidden = false, @required this.pageSizeProportion, @required this.children, }) : super(key: key); // Size screenSize; // double bottomPosition; // double startPosition; // double topListPadding = 0; @override Widget build(BuildContext context) { Size screenSize = MediaQuery.of(context).size; return Stack( children: <Widget>[ if (!isHidden) Align( alignment: Alignment.topCenter, child: GestureDetector( onTap: () => _handleBackGesture(context), child: Container( width: double.infinity, height: screenSize.height * (1 - pageSizeProportion), color: Colors.transparent, ), ), ), Align( alignment: Alignment.bottomCenter, child: GestureDetector( onTap: () => _handleTap(context), child: Container( padding: EdgeInsets.symmetric(horizontal: Styles.hzPadding) .add(EdgeInsets.only(top: Styles.vtFormPadding)), width: screenSize.width, height: screenSize.height * pageSizeProportion, decoration: Styles.formContainerDecoration, child: Scaffold( backgroundColor: Colors.white, body: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Text(title, style: Styles.formTitle), Expanded( child: Form( key: formKey, child: SingleChildScrollView( padding: EdgeInsets.symmetric(vertical: 20.0), physics: BouncingScrollPhysics(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: children, ), ), ), ), ]), ), ), ), ), ], ); } _handleTap(BuildContext context) { //To improve user experience, we'll unfocus any textfields when the users taps oon the background of the form if (MediaQuery.of(context).viewInsets.bottom > 0) SystemChannels.textInput.invokeMethod('TextInput.hide'); WidgetsBinding.instance.focusManager.primaryFocus?.unfocus(); } _handleBackGesture(BuildContext context) { if (Navigator.of(context).canPop()) Navigator.of(context).pop(); } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/plant_form_information.dart
import 'package:flutter/material.dart'; import 'package:plant_forms/demo.dart'; import 'package:provider/provider.dart'; import 'components/section_title.dart'; import 'components/stack_pages_route.dart'; import 'components/submit_button.dart'; import 'demo_data.dart'; import 'form_inputs/dropdown_menu.dart'; import 'form_inputs/text_input.dart'; import 'form_mixin.dart'; import 'form_page.dart'; import 'plant_form_payment.dart'; import 'plant_form_summary.dart'; import 'styles.dart'; class PlantFormInformation extends StatefulWidget { final double pageSize; final bool isHidden; const PlantFormInformation({Key key, this.pageSize, this.isHidden = false}) : super(key: key); @override _PlantFormInformationState createState() => _PlantFormInformationState(); } class _PlantFormInformationState extends State<PlantFormInformation> with FormMixin { final _formKey = GlobalKey<FormState>(); SharedFormState formState; Map<String, String> get values => formState.valuesByName; String get _selectedCountry => _getFormValue(FormKeys.country); //String _country; ValueNotifier<String> _country; String _countrySubdivisionKey; List<String> _countries; @override void initState() { super.initState(); _countries = CountryData.getCountries(); formState = Provider.of<SharedFormState>(context, listen: false); if (!values.containsKey(FormKeys.country)) { // if not value, set default country _country = ValueNotifier(_countries[2]); values[FormKeys.country] = _country.value; } _updateCountrySubdivision(_selectedCountry); } @override Widget build(BuildContext context) { print("Rebuilding information @ ${DateTime.now().millisecondsSinceEpoch}"); return FormPage( formKey: _formKey, isHidden: widget.isHidden, pageSizeProportion: widget.pageSize ?? 0.85, title: 'Information', children: <Widget>[ //All countries share the a title and country selector at the top of the form FormSectionTitle('Contact Information'), //Email Input _buildText(FormKeys.email, type: InputType.email, required: true), FormSectionTitle('Shipping Address'), //Country selector DropdownMenu( key: ValueKey(FormKeys.country), label: 'Country / Region', options: _countries, defaultOption: _selectedCountry, onValidate: onItemValidate, ), //Inject the country-specific fields into the list, ..._buildCountrySpecificFormElements(), //Phone number is always last _buildText(FormKeys.phone, title: "Phone Number", type: InputType.telephone), SubmitButton( isErrorVisible: isFormErrorVisible, child: Text('Continue to payment', style: Styles.submitButtonText), percentage: formCompletion, onPressed: () => _handleSubmit(context)), ], ); } DropdownMenu _buildSubdivisionDropdown() { return DropdownMenu( key: ValueKey(_countrySubdivisionKey), label: _countrySubdivisionKey, defaultOption: _getFormValue(_countrySubdivisionKey), options: CountryData.getSubdivisionList(_countrySubdivisionKey), onValidate: onItemValidate); } List<Widget> _buildCountrySpecificFormElements() { var postalTitle = _selectedCountry == "United States" ? "Zip Code" : "Postal Code"; List<Widget> elements = []; switch (_selectedCountry) { case 'United States': case 'Canada': elements = [ _buildText(FormKeys.firstName), _buildText(FormKeys.lastName, required: true), _buildText(FormKeys.address, required: true), _buildText(FormKeys.apt, title: "Apartment, suite, etc."), _buildText(FormKeys.city, required: true), _buildSubdivisionDropdown(), _buildText(FormKeys.postal, title: postalTitle, required: true), ]; break; case 'Japan': elements = [ _buildText(FormKeys.company), _buildText(FormKeys.lastName, required: true), _buildText(FormKeys.firstName), _buildText(FormKeys.postal, title: postalTitle, required: true), _buildSubdivisionDropdown(), _buildText(FormKeys.city, required: true), _buildText(FormKeys.address, required: true), _buildText(FormKeys.apt, title: "Apartment, suite, etc."), ]; break; case 'France': elements = [ _buildText(FormKeys.firstName), _buildText(FormKeys.lastName, required: true), _buildText(FormKeys.company), _buildText(FormKeys.address, required: true), _buildText(FormKeys.apt, title: "Apartment, suite, etc."), _buildText(FormKeys.postal, title: postalTitle, required: true), _buildText(FormKeys.city, required: true), ]; break; } return elements; } TextInput _buildText(String key, {String title, bool required = false, InputType type = InputType.text}) { title = title ?? _snakeToTitleCase(key); // Register the input validity if (!validInputsMap.containsKey(key)) validInputsMap[key] = !required; return TextInput( key: ValueKey(key), helper: title, type: type, initialValue: _getFormValue(key), onValidate: onItemValidate, onChange: onItemChange, isRequired: required, valueNotifier: _country, ); } @override void onItemValidate(String key, bool isValid, {String value}) { // update the input validity validInputsMap[key] = isValid; bool hasChanged = values[key] != value; values[key] = value; // on country updated if (key == FormKeys.country && hasChanged) { _country.value = value; validInputsMap.clear(); _updateCountrySubdivision(value); onItemChange(key, value); } WidgetsBinding.instance.addPostFrameCallback((_) { setState(() { formCompletion = countValidItems() / validInputsMap.length; if (formCompletion == 1) isFormErrorVisible = false; }); }); } @override //Update cached values each time the form changes void onItemChange(String key, String value) { values[key] = value; } String _snakeToTitleCase(String value) { String capitalize(String s) => s[0].toUpperCase() + s.substring(1); List<String> words = value.split("_"); words = words.map((w) => capitalize(w)).toList(); return words.join(" "); } String _getFormValue(String name) { return values.containsKey(name) ? values[name] : ""; } void _updateCountrySubdivision(String country) { //Invalidate input maps validInputsMap.clear(); //Get the key for this country _countrySubdivisionKey = CountryData.getSubdivisionTitle(country); //Select default is nothing is currently set if (!values.containsKey(_countrySubdivisionKey) && _countrySubdivisionKey.isNotEmpty) { values[_countrySubdivisionKey] = CountryData.getSubdivisionList(_countrySubdivisionKey)[0]; } } void _handleSubmit(BuildContext context) { if (_formKey.currentState.validate() && formCompletion == 1) { Navigator.push( context, StackPagesRoute(previousPages: [ PlantFormSummary(isHidden: true, pageSize: .85), PlantFormInformation(isHidden: true, pageSize: .85), ], enterPage: PlantFormPayment())); } else setState(() { isFormErrorVisible = true; }); } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:shared/env.dart'; import 'demo.dart'; void main() => runApp(App()); class App extends StatelessWidget { static String _pkg = "plant_forms"; static String get pkg => Env.getPackage(_pkg); @override Widget build(BuildContext context) { SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle( statusBarBrightness: Brightness.light, )); return MaterialApp( debugShowCheckedModeBanner: false, title: 'Plant Forms', home: PlantFormsDemo(), ); } }
0