Flutter animation - animation

How can I fade out 1st widget, and animate 2nd widget to come from bottom, and replace the 1st widget, once user click the button?
And on click on second button, to make 2nd widget go down and 1st widget fade in?

You can do that with an AnimatedOpacity for the first widget and an AnimatedPositioned for the second one. Here you have an example:
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
double _firstWidgetOpacity = 1.0;
double _secondWidgetBottomPosition = -200.0;
animate() {
setState(() {
if (_firstWidgetOpacity == 1.0) {
_firstWidgetOpacity = 0.0;
_secondWidgetBottomPosition = MediaQuery.of(context).size.height / 2 - 140.0;
} else {
_firstWidgetOpacity = 1.0;
_secondWidgetBottomPosition = -200.0;
}
});
}
#override
void initState() {
super.initState();
print((560 / 60).floor());
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: animate,
label: Text('Animate'),
),
body: Stack(
children: <Widget>[
Align(
alignment: Alignment.center,
child: AnimatedOpacity(
duration: Duration(milliseconds: 350),
opacity: _firstWidgetOpacity,
curve: Curves.easeIn,
child: Container(
width: 200.0,
height: 200.0,
color: Colors.blue,
child: Center(
child: Text('First widget'),
),
),
),
),
AnimatedPositioned(
duration: Duration(milliseconds: 350),
curve: Curves.elasticIn,
bottom: _secondWidgetBottomPosition,
left: 0.0,
right: 0.0,
child: Center(
child: Container(
width: 200.0,
height: 200.0,
color: Colors.orange,
child: Center(
child: Text('Second widget'),
),
),
),
),
],
),
);
}
}
You can play with the durations and curves to get the result that you need.

Related

Flutter Zoom out effect on Stack of cards by swipe down

I am trying to implement swipe down on stack of cards and making them zoom out.
I have tried many basic animations together but nothing worked.
Here is one of my code that i have tried:
class _HomePageState extends State<HomePage> {
final HomeController _controller;
double _scaley = 1;
double skewY = 0;
double rotateZ = 0;
double radius = 15.0;
_HomePageState(this._controller);
#override
void initState() {
super.initState();
refreshView();
}
refreshView() {
_controller.init((result) {
setState(() {});
});
}
#override
Widget build(BuildContext context) {
return _controller.isLoading
? Center(
child: CircularProgressIndicator(),
)
: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_controller.data.defaultCard == null
? Container()
: Container(
height: MediaQuery.of(context).size.height / 2.4,
child: new GestureDetector(
onVerticalDragDown: (DragDownDetails details) {
skewY = 0.3;
rotateZ = -3.14 / 18.0;
_scaley = 1.1;
radius = 20.0;
setState(() {});
},
child: Stack(
alignment: FractionalOffset.topRight,
children: <Widget>[
Positioned(
top: 20,
child: Transform(
transform: Matrix4.skewX(skewY)..rotateZ(rotateZ)..scale(_scaley),
child: OtherCard(
radius: radius,
card: _controller.data.defaultCard,
defaultCard: true,
callback: refreshView,
),
),
),
Positioned(
top: 70,
child: Transform(
transform: Matrix4.skewX(skewY)..rotateZ(rotateZ)..scale(_scaley),
child: OtherCard(
radius: radius,
card: _controller.data.defaultCard,
defaultCard: true,
callback: refreshView,
),
),
),
Positioned(
top: 120,
child: Transform(
transform: Matrix4.skewX(skewY)..rotateZ(rotateZ)..scale(_scaley),
child: OtherCard(
radius: radius,
card: _controller.data.defaultCard,
defaultCard: true,
callback: refreshView,
),
),
),
],
),
),
),
],
),
);
}
}
I need animation like Apple pay:
Its showing single card and I need to show 3 cards as stack:
and by dragging them down will zoom them out(like gif)

Animate multiple widgets on same screen flutter

I need slide animation from left to right and vice versa.
Can anyone give me any guidance which widget i should use in it?
I have tried a few thing like :- carousel_slider, transformer_pageview, page_transformer
I used SlideTransition class, but it is not giving me expected result, I have also tried different range/values of OffSet but no luck.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';
class HomePage extends StatefulWidget {
const HomePage({Key key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
AnimationController _controller;
Animation<Offset> _offsetAnimation;
AnimationController _controllerTwo;
Animation<Offset> _offsetAnimationTwo;
#override
void initState() {
_controller = AnimationController(
duration: const Duration(seconds: 1),
vsync: this,
);
_offsetAnimation = Tween<Offset>(
begin: const Offset(-0.00001, 0.0),
end: const Offset(0.09, 0.0),
).animate(CurvedAnimation(
parent: _controller,
curve: Curves.easeInOut,
));
_controllerTwo = AnimationController(
duration: const Duration(seconds: 1),
vsync: this,
);
_offsetAnimationTwo = Tween<Offset>(
begin: const Offset(-0.85, 0.0),
end: const Offset(-0.00001, 0.0),
).animate(CurvedAnimation(
parent: _controllerTwo,
curve: Curves.easeInOut,
));
super.initState();
}
#override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Expanded(
child: new GestureDetector(
onHorizontalDragUpdate: (details) {
if (details.primaryDelta > 0) {
_controller..reverse();
_controllerTwo..reverse();
}
if (details.primaryDelta < 0) {
_controller..forward();
_controllerTwo..forward();
}
print(details.primaryDelta);
},
child: Row(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
SlideTransition(
position: _offsetAnimationTwo,
child: Card(
color: Colors.black54,
child: Container(),
),
),
Flexible(
child: SlideTransition(
position: _offsetAnimation,
child: Container(
child: SlidingUpPanel(
renderPanelSheet: false,
panel: _floatingStatement(),
body: CardsStack(context),
),
),
),
),
],
),
),
)
],
);
}
Widget _floatingStatement() {
return Container(
margin: const EdgeInsets.all(24.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(24.0)),
boxShadow: [
BoxShadow(
blurRadius: 20.0,
color: Colors.grey,
),
],
),
);
}
}
class CardsStack extends StatelessWidget {
const CardsStack(BuildContext context, {Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return new Stack(
alignment: Alignment.center,
children: <Widget>[
Positioned(
top: 20,
left: 10,
right: 10,
child: Card(
color: Colors.black54,
child: Container(),
),
),
Positioned(
top: 70,
left: 10,
right: 10,
child: Card(
color: Colors.black54,
child: Container(),
),
),
Positioned(
top: 120,
left: 10,
right: 10,
child: Card(
color: Colors.black54,
child: Container(),
),
),
],
);
}
}
You can use PageView to horizontally (even vertically) swipe between pages.
Or you can use TabBarView to implement it with bottom navigation.
Example code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false,
);
}
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
body: TabBarView(
children: <Widget>[
Center(child: Text("Page1")),
Center(child: Text("Page2")),
Center(child: Text("Page3")),
],
),
bottomNavigationBar: Container(
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10.0),
topRight: Radius.circular(10.0),
),
boxShadow: [
BoxShadow(
color: Colors.black,
offset: Offset(0, 0),
blurRadius: 10.0,
),
],
),
child: TabBar(
indicatorColor: Colors.red,
indicatorWeight: 5.0,
indicatorSize: TabBarIndicatorSize.label,
labelColor: Colors.black,
tabs: <Widget>[
Tab(icon: Icon(Icons.home)),
Tab(icon: Icon(Icons.category)),
Tab(icon: Icon(Icons.account_circle)),
],
),
),
),
);
}
}

Flutter: hide and display app bar in scrolling detected

I'm having trouble with app bar animation, I'm using SilverAppBar, in my app. So, the problem is when I'm in the middle of my list and I scroll up, the app bar does not appear, but it appears just when scrolling reaches the top of the items list. I already tested the snap parameter and give it true, but not the result I expect. I have ideas about creating a custom animation for this, but I'm not too experienced in Flutter, and also if there is a way to add parameters, or another widget that will work for my situation, it would be great.
The actual code of the demo I'm using:
Widget _search() => Container(
color: Colors.grey[400],
child: SafeArea(
child: Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
enabled: false,
style: TextStyle(fontSize: 16, color: Colors.white),
decoration: InputDecoration(
prefix: SizedBox(width: 12),
hintText: "Search",
contentPadding:
EdgeInsets.symmetric(horizontal: 32.0, vertical: 14.0),
border: InputBorder.none,
),
),
),
)),
);
Container _buildBody() {
return Container(
child: new GridView.count(
crossAxisCount: 2,
children: List.generate(100, (index) {
return Center(
child: Text(
'Item $index',
style: Theme.of(context).textTheme.headline,
),
);
}),
));
}
#override
Widget build(BuildContext context) {
return new Scaffold(
resizeToAvoidBottomPadding: false,
body: new NestedScrollView(
headerSliverBuilder:
(BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
new SliverAppBar(
title: Text("Demo",
style: TextStyle(
color: Colors.white,
)),
pinned: false,
floating: true,
forceElevated: innerBoxIsScrolled,
),
];
},
body: new Column(children: <Widget>[
_search(),
new Expanded(child: _buildBody())
])));
}
The result I have now:
Image 1
The result I got after giving true to the snap parameter:
Image 2
Plenty of applications like WhatsApp, Facebook, LinkedIn ... have this animating app bar. To explain more what exactly I expect with this animating app bar, I added an example of Google Play Store, showing the wanted animation: Play Store example
I had a similar issue with CustomScrollView and SliverAppbar using refresh indicator i ended up creating my own custom appbar.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class HomeView extends StatefulWidget {
#override
HomeState createState() => HomeState();
}
class HomeState extends State<HomeView> with SingleTickerProviderStateMixin {
bool _isAppbar = true;
ScrollController _scrollController = new ScrollController();
#override
void initState() {
super.initState();
_scrollController.addListener(() {
if (_scrollController.position.userScrollDirection ==
ScrollDirection.reverse) {
appBarStatus(false);
}
if (_scrollController.position.userScrollDirection ==
ScrollDirection.forward) {
appBarStatus(true);
}
});
}
void appBarStatus(bool status) {
setState(() {
_isAppbar = status;
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(kToolbarHeight),
child: AnimatedContainer(
height: _isAppbar ? 55.0 : 0.0,
duration: Duration(milliseconds: 200),
child: CustomAppBar(),
),
),
body: ListView.builder(
controller: _scrollController,
itemCount: 20,
itemBuilder: (BuildContext context, int index) {
return container();
},
),
),
);
}
}
Widget container() {
return Container(
height: 80.0,
color: Colors.pink,
margin: EdgeInsets.all(8.0),
width: 100,
child: Center(
child: Text(
'Container',
style: TextStyle(
fontSize: 18.0,
),
)),
);
}
class CustomAppBar extends StatefulWidget {
#override
AppBarView createState() => new AppBarView();
}
class AppBarView extends State<CustomAppBar> {
#override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: Colors.white,
leading: InkWell(
onTap: () => {},
child: new Padding(
padding: const EdgeInsets.all(8.0),
child: CircleAvatar(
backgroundColor: Colors.white,
child: ClipOval(
child: Image.network(
'https://images.squarespace-cdn.com/content/5aee389b3c3a531e6245ae76/1530965251082-9L40PL9QH6PATNQ93LUK/linkedinPortraits_DwayneBrown08.jpg?format=1000w&content-type=image%2Fjpeg'),
),
),
),
),
actions: <Widget>[
IconButton(
alignment: Alignment.centerLeft,
icon: Icon(
Icons.search,
color: Colors.black,
),
onPressed: () {},
),
],
title: Container(
alignment: Alignment.centerLeft,
child: Text("Custom Appbar", style: TextStyle(color: Colors.black),)
),
);
}
}
To get this functionality to work, you will need to use the CustomScrollView widget instead of NestedScrollView. Google Documentation
Here is a working example:
class MyHomeState extends State<MyHome> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
const SliverAppBar(
pinned: false,
snap: false,
floating: true,
flexibleSpace: FlexibleSpaceBar(
title: Text('Demo'),
),
),
SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200.0,
mainAxisSpacing: 10.0,
crossAxisSpacing: 10.0,
childAspectRatio: 4.0,
),
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Container(
alignment: Alignment.center,
color: Colors.teal[100 * (index % 9)],
child: Text('grid item $index'),
);
},
childCount: 50,
),
),
],
)
);
}
}
Example of this running here
I was able to make the floating Appbar with Tabbar similar to that of WhatsApp by using SliverAppbar with NestedScrollView. Do remember to add floatHeaderSlivers: true, in NestedScrollView. Link to sample code
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: CustomSliverAppbar(),
);
}
}
class CustomSliverAppbar extends StatefulWidget {
#override
_CustomSliverAppbarState createState() => _CustomSliverAppbarState();
}
class _CustomSliverAppbarState extends State<CustomSliverAppbar>
with SingleTickerProviderStateMixin {
TabController _tabController;
#override
void initState() {
_tabController = TabController(
initialIndex: 0,
length: 2,
vsync: this,
);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: NestedScrollView(
floatHeaderSlivers: true,
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
SliverAppBar(
title: Text(
"WhatsApp type sliver appbar",
),
centerTitle: true,
pinned: true,
floating: true,
bottom: TabBar(
indicatorColor: Colors.black,
labelPadding: const EdgeInsets.only(
bottom: 16,
),
controller: _tabController,
tabs: [
Text("TAB A"),
Text("TAB B"),
]),
),
];
},
body: TabBarView(
controller: _tabController,
children: [
TabA(),
const Center(
child: Text('Display Tab 2',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
),
],
),
),
);
}
#override
void dispose() {
_tabController.dispose();
super.dispose();
}
}
class TabA extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scrollbar(
child: ListView.separated(
separatorBuilder: (context, child) => Divider(
height: 1,
),
padding: EdgeInsets.all(0.0),
itemCount: 30,
itemBuilder: (context, i) {
return Container(
height: 100,
width: double.infinity,
color: Colors.primaries[Random().nextInt(Colors.primaries.length)],
);
},
),
);
}
}

Flutter: Best way to change a widget opacity and color on scroll

My goal is to change the color and the opacity of the appbar when user scrolls down.
My logic is:
scroll offset = 0 : appbar is red with opacity = 1
0 < scroll offset < 40 : appbar is blue with opacity = 0.4
40 <= scroll offset : appbar is blue with opacity proportional to scroll offset
I came up with the following code:
import 'package:flutter/material.dart';
import 'package:gradient_app_bar/gradient_app_bar.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _gradientColor1 = Colors.red[400];
var _gradientColor2 = Colors.red[800];
ScrollController _scrollViewController;
void changeColor(){
if((_scrollViewController.offset == 0) && (_gradientColor1 != Colors.red[400])){
setState(() {
_gradientColor1 = Colors.red[400];
_gradientColor2 = Colors.red[800];
});
}else if((_scrollViewController.offset <= 40) && (_gradientColor1 != Color.fromRGBO(66,165,245 ,0.4))){
setState(() {
_gradientColor1 = Color.fromRGBO(66,165,245 ,0.4);
_gradientColor2 = Color.fromRGBO(21,101,192 ,0.4);
});
}else if((_scrollViewController.offset <= 100) && (_scrollViewController.offset > 40)){
var opacity = _scrollViewController.offset/100;
setState(() {
_gradientColor1 = Color.fromRGBO(66,165,245 ,opacity);
_gradientColor2 = Color.fromRGBO(21,101,192 ,opacity);
});
}
}
#override
void initState() {
_scrollViewController = ScrollController(initialScrollOffset: 0.0);
_scrollViewController.addListener(changeColor);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: GradientAppBar(
backgroundColorStart: _gradientColor1,
backgroundColorEnd: _gradientColor2,
elevation: 0,
),
body: SingleChildScrollView(
controller: _scrollViewController,
child: Column(
children: <Widget>[
Container(color: Colors.red, height: 400,),
Container(color: Colors.purple, height: 400,),
],
),
),
);
}
}
It works as expected but it becomes laggy with a more complicated UI.
In my example I'm using GradientAppbar: https://github.com/joostlek/GradientAppBar
i think the best approach Will be using AnimatedBuilder and you will see that first container in body will not changed its color because widget state have not changed
and the result :
code:
import 'dart:math';
import 'package:flutter/material.dart';
class ProductDetails extends StatefulWidget {
#override
_ProductDetailsState createState() => _ProductDetailsState();
}
class _ProductDetailsState extends State<ProductDetails>
with TickerProviderStateMixin {
AnimationController _ColorAnimationController;
AnimationController _TextAnimationController;
Animation _colorTween, _iconColorTween;
Animation<Offset> _transTween;
#override
void initState() {
_ColorAnimationController =
AnimationController(vsync: this, duration: Duration(seconds: 0));
_colorTween = ColorTween(begin: Colors.transparent, end: Color(0xFFee4c4f))
.animate(_ColorAnimationController);
_iconColorTween = ColorTween(begin: Colors.grey, end: Colors.white)
.animate(_ColorAnimationController);
_TextAnimationController =
AnimationController(vsync: this, duration: Duration(seconds: 0));
_transTween = Tween(begin: Offset(-10, 40), end: Offset(-10, 0))
.animate(_TextAnimationController);
super.initState();
}
bool _scrollListener(ScrollNotification scrollInfo) {
if (scrollInfo.metrics.axis == Axis.vertical) {
_ColorAnimationController.animateTo(scrollInfo.metrics.pixels / 350);
_TextAnimationController.animateTo(
(scrollInfo.metrics.pixels - 350) / 50);
return true;
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFFEEEEEE),
body: NotificationListener<ScrollNotification>(
onNotification: _scrollListener,
child: Container(
height: double.infinity,
child: Stack(
children: <Widget>[
SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
height: 150,
color:
Color((Random().nextDouble() * 0xFFFFFF).toInt() << 0)
.withOpacity(1),
width: 250,
),
Container(
height: 150,
color: Colors.pink,
width: 250,
),
Container(
height: 150,
color: Colors.deepOrange,
width: 250,
),
Container(
height: 150,
color: Colors.red,
width: 250,
),
Container(
height: 150,
color: Colors.white70,
width: 250,
),
],
),
),
Container(
height: 80,
child: AnimatedBuilder(
animation: _ColorAnimationController,
builder: (context, child) => AppBar(
backgroundColor: _colorTween.value,
elevation: 0,
titleSpacing: 0.0,
title: Transform.translate(
offset: _transTween.value,
child: Text(
"اسم کالا اینجا",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 16),
),
),
iconTheme: IconThemeData(
color: _iconColorTween.value,
),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.local_grocery_store,
),
onPressed: () {
// Navigator.of(context).push(TutorialOverlay());
},
),
IconButton(
icon: Icon(
Icons.more_vert,
),
onPressed: () {},
),
],
),
),
),
],
),
),
),
);
}
}
In this little example I do the following: I change the opacity of my AnimatedOpacity depending on some conditions, namely if its offset is either greater or less than 100 pixels from the top to the bottom of the screen. I obtain the mentioned offset with the help of RenderBox and GlobalKey. This validations and events happen within the function passed to my scrollListener. That means that they get triggered every time I scroll. Here is the full code.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
ScrollController _scrollController;
GlobalKey widgetKey = GlobalKey();
Offset widgetOffset;
double _currentPosition;
double opacity = 1;
#override
void initState() {
_scrollController = ScrollController();
_scrollController.addListener(_scrollListener);
super.initState();
}
_scrollListener() {
print('scrolling');
RenderBox textFieldRenderBox = widgetKey.currentContext.findRenderObject();
widgetOffset = textFieldRenderBox.localToGlobal(Offset.zero);
_currentPosition = widgetOffset.dy;
print(
"widget position: $_currentPosition against: 100");
if (100 > _currentPosition && _currentPosition > 1) {
setState(() {
opacity = _currentPosition / 100;
});
} else if (_currentPosition > 100 && opacity != 1) {
opacity = 1;
}
else if (_currentPosition < 0 && opacity != 0) {
opacity = 0;
}
print("opacity is: $opacity");
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
controller: _scrollController,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
margin: EdgeInsets.only(bottom: 50),
height: 100,
width: 100,
color: Colors.red,
),
Container(
margin: EdgeInsets.only(bottom: 50),
height: 100,
width: 100,
color: Colors.red,
),
AnimatedOpacity(
key: widgetKey,
duration: Duration(milliseconds: 1),
opacity: opacity,
child: Center(
child: Container(
margin: EdgeInsets.only(bottom: 50),
height: 100,
width: 100,
color: Colors.purpleAccent,
),
),
),
Container(
margin: EdgeInsets.only(bottom: 50),
height: 100,
width: 100,
color: Colors.red,
),
Container(
margin: EdgeInsets.only(bottom: 50),
height: 100,
width: 100,
color: Colors.red,
),
Container(
margin: EdgeInsets.only(bottom: 50),
height: 100,
width: 100,
color: Colors.red,
),
Container(
margin: EdgeInsets.only(bottom: 50),
height: 100,
width: 100,
color: Colors.teal,
),
Container(
margin: EdgeInsets.only(bottom: 50),
height: 100,
width: 100,
color: Colors.teal,
),
Container(
margin: EdgeInsets.only(bottom: 50),
height: 100,
width: 100,
color: Colors.teal,
),
],
)),
);
}
}

Flutter: Notifications UI

I can't distinguish new Firebase Cloud Messaging notifications from older ones in my Flutter UI. How can I fix this? Thanks.
EXAMPLE: 3 users comment on an author's post that already has 2 "seen" comments. The author's post gets a +3 red marble on it. When the author clicks on this post in the Notifications tab, the user is routed to its comments, that +3 reduces to 0, and the bottom tab marble reduces to 3 (6-3=3) as well.
Dummy UI Code and Pics below.
1. A blank "home page;"
2. a dummy notifications page with posts that have been replied to
3. On clicking a post, a comments page.
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
routes: <String, WidgetBuilder>{
"/comment": (BuildContext context) => new commentFoundation(),
},
home: MainScreen());
}
}
//The content of the notification tab.
class Notification extends StatefulWidget {
#override
_NotificationState createState() => new _NotificationState();
}
class _NotificationState extends State<Notification> {
#override
Widget build(BuildContext context) {
return _buildPostList();
}
Widget _buildPostList() {
return new Scaffold(
backgroundColor: Colors.blue,
body: new Scrollbar(
child: new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return new Container(
child: new Stack(children: <Widget>[
new Column(
children: <Widget>[
Container(
margin: EdgeInsets.only(top: 0.0, left: 12.0),
child: DummyPost()),
],
),
replyNotification(),
]));
},
itemCount: 2,
)));
}
Widget replyNotification() {
return new Positioned(
left: 175,
top: 205.5,
child: new Container(
padding: EdgeInsets.only(left: 3.0, right: 3.0),
decoration: new BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(30),
),
constraints: BoxConstraints(
minWidth: 30,
minHeight: 30,
),
child: Row(
children: <Widget>[
Container(
padding: EdgeInsets.only(top: 0.0),
child: new Text(
'+',
style: new TextStyle(
color: Colors.white,
fontSize: 26,
),
textAlign: TextAlign.center,
)),
Container(
padding: EdgeInsets.only(right: 0.0),
child: new Text(
'3',
style: new TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
)),
],
)),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Center(
child: new Container(
child: Text("HomePageStuff"),
));
}
}
//A dummy post in notififications tab
class DummyPost extends StatefulWidget {
#override
_DummyPostState createState() => new _DummyPostState();
}
class _DummyPostState extends State<DummyPost> {
bool monVal = false;
bool reportPressed = false;
Widget commentButton() {
return RaisedButton(
child: Text("ReplyButton"),
onPressed: () => Navigator.push(context,
MaterialPageRoute(builder: (context) => commentFoundation())),
);
}
#override
Widget build(BuildContext context) {
return postList();
}
Widget postList() {
return Column(children: <Widget>[
new GestureDetector(
//this type works
onTap: () => Navigator.pushNamed(context, '/comment'),
child: new Stack(children: <Widget>[
Column(children: <Widget>[
SizedBox(
height: 10.0,
),
Container(
margin: EdgeInsets.only(top: 35.0),
width: 390.0,
child: Card(
shape: RoundedRectangleBorder(
//15?
borderRadius: BorderRadius.circular(5.0),
),
color: Colors.white,
elevation: 2.0,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Flexible(
child: ListTile(
// The main post content
subtitle: Container(
height: 130.0,
margin: EdgeInsets.only(
top: 15.0, left: 15.0, right: 15.0),
child: Container(
child: Center(
child: Text(
"This is a dummy post",
textAlign: TextAlign.center,
style: TextStyle(
wordSpacing: 3.0,
color: Colors.black,
fontSize: 18.0),
))),
),
)),
//button row
new Container(
width: 400.0,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
margin: EdgeInsets.only(right: 0.0),
width: 190.0,
height: 40.0,
child: commentButton(),
),
// Text to indicate comment numbers
],
)),
],
))),
]),
]))
]);
}
}
//the entire comment page.
class commentFoundation extends StatefulWidget {
#override
_commentFoundationState createState() => new _commentFoundationState();
}
class _commentFoundationState extends State<commentFoundation> {
ScrollController _scrollController = new ScrollController();
#override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.green,
appBar: _buildAppBar(),
body: new Stack(children: <Widget>[
ListView.builder(
shrinkWrap: true,
controller: _scrollController,
itemCount: 5,
itemBuilder: (BuildContext context, int index) {
return new individualComment();
}),
]));
}
Widget _buildAppBar() {
return AppBar(
title: Text("REPLIES"),
automaticallyImplyLeading: true,
backgroundColor: Colors.white,
elevation: 0.0,
);
}
}
//Each individual comment you see when you click on a post
class individualComment extends StatefulWidget {
final String title;
const individualComment({Key key, this.title}) : super(key: key);
#override
_individualCommentState createState() => new _individualCommentState();
}
class _individualCommentState extends State<individualComment> {
#override
Widget build(BuildContext context) {
return new Stack(
children: <Widget>[
Column(children: <Widget>[
//this used to be an expanded
new Container(
child: Card(
elevation: 0.0,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new ListTile(
// The avatar
leading: Container(
child: Icon(
Icons.accessibility_new,
)),
// Title, location, and time
// The main post content
subtitle: Container(
margin: EdgeInsets.only(top: 10.0, bottom: 0.0),
child: Text(
"This is a reply",
style: TextStyle(
color: Colors.black,
fontSize: .0364609 *
MediaQuery.of(context).size.width),
),
),
),
],
))),
])
],
);
}
}
//*****This is just the tabbar.
class MainScreen extends StatefulWidget {
#override
_MainScreenstate createState() => new _MainScreenstate();
}
class _MainScreenstate extends State<MainScreen> with TickerProviderStateMixin {
String _lastSelected = '0';
final List<Widget> _bodyOptions = [
HomePage(),
Notification(),
];
int _selectedIndex = 0;
bool tab = true;
_selectedTab(int index) {
setState(() {
_lastSelected = '$index';
});
}
Widget __buildTabs() {
return Scaffold(
body: _bodyOptions.elementAt(int.parse(_lastSelected)),
//around the FAB
backgroundColor: const Color(0xFFF4F4F4),
bottomNavigationBar: new Stack(
children: <Widget>[
FABBottomAppBar(
height: 45.0,
centerItemText: '',
color: Colors.black,
selectedColor: Colors.blue,
notchedShape: CircularNotchedRectangle(),
onTabSelected: _selectedTab,
items: [
FABBottomAppBarItem(iconData: Icons.search, text: 'Home'),
FABBottomAppBarItem(
iconData: Icons.notifications, text: 'Notifications'),
],
),
//the red "notification" marble
new Positioned(
right: 20,
top: 0.5,
child: new Container(
padding: EdgeInsets.all(1),
decoration: new BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(12),
),
constraints: BoxConstraints(
minWidth: 20,
minHeight: 20,
),
child: new Text(
'6',
style: new TextStyle(
color: Colors.white,
fontSize: 14,
),
textAlign: TextAlign.center,
),
),
)
],
));
}
#override
Widget build(BuildContext context) {
return __buildTabs();
}
}
//Everything below is boiler plate tabbar code.
class FABBottomAppBarItem {
FABBottomAppBarItem({this.iconData, this.text});
IconData iconData;
String text;
}
class FABBottomAppBar extends StatefulWidget {
FABBottomAppBar({
this.items,
this.centerItemText,
this.height: 60.0,
this.iconSize: 24.0,
this.backgroundColor,
this.color,
this.selectedColor,
this.notchedShape,
this.onTabSelected,
}) {
assert(this.items.length == 2 || this.items.length == 4);
}
final List<FABBottomAppBarItem> items;
final String centerItemText;
final double height;
final double iconSize;
final Color backgroundColor;
final Color color;
final Color selectedColor;
final NotchedShape notchedShape;
final ValueChanged<int> onTabSelected;
#override
State<StatefulWidget> createState() => FABBottomAppBarState();
}
class FABBottomAppBarState extends State<FABBottomAppBar> {
int _selectedIndex = 0;
_updateIndex(int index) {
widget.onTabSelected(index);
setState(() {
_selectedIndex = index;
});
return _selectedIndex;
}
#override
Widget build(BuildContext context) {
List<Widget> items = List.generate(widget.items.length, (int index) {
return _buildTabItem(
item: widget.items[index],
index: index,
onPressed: _updateIndex,
);
});
items.insert(items.length >> 1, _buildMiddleTabItem());
return BottomAppBar(
elevation: 0.0,
notchMargin: 2.0,
shape: CircularNotchedRectangle(),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: items,
),
//color of bottom
color: Colors.white,
);
}
Widget _buildMiddleTabItem() {
return Expanded(
child: SizedBox(
height: widget.height,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(height: widget.iconSize),
Text(
widget.centerItemText ?? '',
style: TextStyle(color: widget.color),
),
],
),
),
);
}
Widget _buildTabItem({
FABBottomAppBarItem item,
int index,
ValueChanged<int> onPressed,
}) {
Color color = _selectedIndex == index ? widget.selectedColor : widget.color;
return Expanded(
child: SizedBox(
height: widget.height,
child: Material(
type: MaterialType.transparency,
child: InkWell(
onTap: () => onPressed(index),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(item.iconData, color: color, size: widget.iconSize),
Text(
item.text,
style: TextStyle(color: color),
)
],
),
),
),
),
);
}
}
This seems to be a broad question and I'm unsure if you're asking for suggestions on how you can implement tracking read and unread notifications, or troubleshooting help on your existing code. I suggest checking tips posted on this thread on how you can manage notification counters.

Resources