How to show increment of counter in my ui in flutter? [duplicate] - user-interface

This question already has an answer here:
variable won't change Text dynamically in flutter
(1 answer)
Closed 3 years ago.
I have declared a variable called ticketCounter that is getting stored in SharedPrefs. This variable is getting incremented and decremented as needed. However I wanted to display this counter on my appBar and want its value to update. Although the value is getting stored in the variable it isn't showing up.
int tickets;
void fetchTickets() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
tickets = prefs.getInt('ticketRW') ?? 0;
}
void initState() {
portraitModeOnly();
fetchTickets();
super.initState();
}
Widget build(BuildContext context) {
return Material(
child: Scaffold(
appBar: AppBar(
actions: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 14, right: 14),
child: Text(
tickets.toString(),//isn't getting updated
style: TextStyle(
fontSize: 22,
fontFamily: "Netflix",
color: Colors.white,
fontWeight: FontWeight.w500,
),
),
),
),
),
}

You should use setState() to update your state.
Change this method:
void fetchTickets() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
tickets = prefs.getInt('ticketRW') ?? 0;
}
with this:
void fetchTickets() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
tickets = prefs.getInt('ticketRW') ?? 0;
});
}
In Flutter, there are StatefulWidget and StatelessWidget.
Stateless widgets have an initial state and it never changes.
Stateful widgets have state objects paired with them. Widgets are UI representations of those state objects. If you have a counter variable in a state object, stateful widget will draw the value of counter. However, chaning the counter variable will not update the UI. You should tell the widget "Hey, I changed your state object, you better check it and update yourself." with setState().
This is an introduction to the state management in Flutter. I suggest you to read further here.

Related

How to move select image button forward when selecting one in flutter

I'm trying to upload multiple image not once, but like this, when user select one image then upload image image will move forward, here is the snap what i'm trying to say
on click on add button an image picker will display
then after selecting the image this should be like this
here i'm selecting one image.
final ImagePicker picker = ImagePicker();
File? _image;
Future pickImagefromGallery() async{
try{
final image=await ImagePicker().pickImage(source: ImageSource.gallery);
if(image==null) return;
// final imageTemp=File(image.path);
final imagePermanent=await saveImagePermantly(image.path);
setState(() {
this._image=imagePermanent;
});
} on PlatformException catch(e){
print("Failed to pick an image" + e.toString());
}
}
#override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.topLeft,
child: _image!=null?Image.file(_image!,
width: MediaQuery.of(context).size.width * 0.3,
height: MediaQuery.of(context).size.height * 0.13,
fit: BoxFit.cover,
):
Align(
alignment: Alignment.topLeft,
child: customImageButton(
context,
"+",
(){pickImagefromGallery()})
):}}
output:
You can put all widgets into a List with a Wrap as parent.
https://api.flutter.dev/flutter/widgets/Wrap-class.html
List<Widgets> listWidgets = [];
...
//then you can add any widget to list
//first you need to add your button to list
listWidgets.add(Align(
alignment: Alignment.topLeft,
child: customImageButton(
context,
"+",
(){pickImagefromGallery()}));
listWidgets.add(Image.file(...)); // this add widget to last position
listWidgets.insert(0, Image.file(...)); // this add to first position like you want
// when you add a widget into list need to do a setState()
// and use Wrap with a list
Wrap(
children: listWidgets,
)

Call state class from widget in flutter

I think I have a flawed architecture but I'm struggling to see how/why. I'm very new to flutter, so bear with me please.
I have a map, and a drawer. I'm loading a list of coordinates in the drawer, and I'd like to do stuff on the map once I press one of those coordinates.
So my problem is that I don't know what to call where to be clean code AND working. Of course I could just expose everything to everyone but that wouldn't solve the main issue : me understanding
My map is drawn in the same place as my drawer, so there I already think I'm cheating but I think that's okay. To be honest I'm not even sure that part is really correct.
Drawing the map :
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
var _map = MapView();
var _stationService = StationService();
....
#override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.map)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike))
],
),
title: Text('Floctta Plus'),
),
drawer: _drawer(),
body: TabBarView(
physics: NeverScrollableScrollPhysics(),
children: [
IncrementView(),
_map,
Icon(Icons.directions_transit),
Icon(Icons.directions_bike)
],
),
),
),
);
}
In my drawer code :
ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, position) {
return ListTile(
title: new Text(snapshot.data[position].titleFR),
leading: new Icon(Icons.pin_drop),
onTap: () {
_map.GoToStation(); <<= Here, calling the MapView class
},
);
},
),
All the MapView.dart code
class MapView extends StatefulWidget {
MapView({Key key}) : super(key: key);
void GoToStation() {
print("I'm reaching this point with success!");
}
#override
_MapViewState createState() => _MapViewState();
}
class _MapViewState extends State<MapView> {
CameraPosition _initialPosition =
CameraPosition(target: LatLng(50.8267018, 4.3532732), zoom: 10.0);
Completer<GoogleMapController> _controller = Completer();
var _markers;
void AddMarkers(List<Station> stations) {
setState(() {
_markers = new List.generate(
stations.length,
(index) => Marker(
markerId: MarkerId(index.toString()),
position: new LatLng(double.parse(stations[index].latitude),
double.parse(stations[index].longitude)),
infoWindow: InfoWindow(
title: stations[index].titleFR,
snippet: stations[index].city,
),
icon: BitmapDescriptor.defaultMarker,
));
});
}
void _onMapCreated(GoogleMapController controller) {
_controller.complete(controller);
}
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: _initialPosition,
markers: _markers,
myLocationEnabled: true,
),
],
);
// );
}
}
I think there is enough code.
My question is :
Im in my Mapview class now, and I'd like to call AddMarkers that is in my State class. But I can't. I'm not really sure how I'm supposed to proceed.
Should I call the state class directly from the drawer? If so, how?
Should I call the state from the view class ? If so, how?
Should I be doing something else entirely? If so, what ?
Right!
I will assume that MapView and Drawer are in different widget subtrees under Scaffold. One is the drawer, the other appears somewhere under body.
My understanding is that when someone clicks on a ListTile in the Drawer, the MapView should update.
In general, the principle you want to employ in that case is introducing a 3rd party object to mediate between the 2 components.
AWidget <--> SState <--> MapView
The most ill-advised approach of it would be to introduce a global variable (please, don't ever do, just mentioning it so that you get the idea). So chit-chat between the ListTiles and your MapView should happen through this mediator object.
Let's call this object SState. (Double SS is on purpose to differentiate from Flutter's State class). This SState will be responsible for keeping track of the params of the map building. (I'm not actually familiar with the insights of your app, so that is completely made up)
So, this indirection of action handling will mean:
tap on ListTile in drawer -> update SState object -> let Flutter know stuff happened and should update those widgets that are sensitive to that change (MapView)
Updating SState object is easy, it is just a function call/setter call to it. But how do you let Flutter know that it should update MapView? And where should you place that SState object instance so that both can reach it without a global var?
To answer that, there are a number of solutions: scoped_model, InheritedWidget, Provider, BLoC pattern. What is common in all of this is that they employ a principle called lifting state up. Basically means, that the SState object should be created in the tree above both of them.
Provider example:
class SState with ChangeNotifier {
String _someMapParam;
String get someMapParam => _someMapParam;
set someMapParam(String val) {
_someMapParam = val;
if(hasListeners) notifyListeners();
}
}
// [...] somewhere in your app
Widget build(BuildContext context) {
return ChangeNotifierProvider<SState>(
builder: (ctx) => new SState(),
child: Scaffold(
drawer: _drawer(),
body: Consumer<SState>(
builder: (_, sStateInstance, __) => Text(sStateInstance.someMapParam),
),
),
);
}
More details on provider: https://pub.dev/packages/provider

How can I use animation/animation not running during a Hero transition in Flutter?

I have a grid of cards depicting products. When a card is tapped, I want it to flip over (around the Y axis) to reveal the "other side" that shows the details, while simultaneously growing to fill the screen.
Duration 0.0 - Card shows front side and is in grid view
Duration 0.5 - Card is 50% of the way to full-screen and perpendicular to the screen (front side facing to the right, "back" side facing to the left)
Duration 1.0 - Card is fully expanded and the "back" card is showing.
I have managed to get a flip animation working, but am having trouble figuring out how to also get it to run during the Hero transition. From this article it seems like I may need to make use of flightShuttleBuilder to be able to animate the overlay but my animation does not run during the transition:
return Hero(
tag: 'test',
flightShuttleBuilder: (
BuildContext flightContext,
Animation<double> animation,
HeroFlightDirection flightDirection,
BuildContext fromHeroContext,
BuildContext toHeroContext,
) {
final Hero toHero = toHeroContext.widget;
return Transform(
transform: Matrix4.identity()..rotateY(-pi * animation.value),
alignment: FractionalOffset.center,
child: toHero,
);
},
child: Card(...),
);
As it turns out, flightShuttleBuilder only emits values at the start and end of the transition instead of throughout the animation. Capturing from this issue on GitHub, it is apparently expected behavior.
The workaround is to create your own transition which extends from AnimatedWidget; that will emit values normally and can be used in the flightShuttleBuilder:
class FlipcardTransition extends AnimatedWidget {
final Animation<double> flipAnim;
final Widget child;
FlipcardTransition({#required this.flipAnim, #required this.child})
: assert(flipAnim != null),
assert(child != null),
super(listenable: flipAnim);
#override
Widget build(BuildContext context) {
return Transform(
transform: Matrix4.identity()
..rotateY(-pi * flipAnim.value),
alignment: FractionalOffset.center,
child: child,
);
}
}
...
flightShuttleBuilder: (BuildContext flightContext,
Animation<double> animation,
HeroFlightDirection flightDirection,
BuildContext fromHeroContext,
BuildContext toHeroContext,) {
final Hero toHero = toHeroContext.widget;
return FlipcardTransition(
flipAnim: animation,
child: toHero,
);
},
As Matt said, the default behavior is only emitting start and end value, so we should listen the animation to get the full animatable widget. Here is an example:
Hero(
tag: "YourHeroTag",
flightShuttleBuilder: (BuildContext flightContext,
Animation<double> animation,
HeroFlightDirection flightDirection,
BuildContext fromHeroContext,
BuildContext toHeroContext,) {
return AnimatedBuilder(
animation: animation,
builder: (context, value) {
return Container(
color: Color.lerp(Colors.white, Colors.black87, animation.value),
);
},
);
},
child: Material( // Wrap in Material to prevent missing theme, mediaquery, ... features....
// ...
)
)
It's recommended to wrap in Material widget to prevent unexpected missing style.

What would be the proper way to update animation values in a Flutter animation?

So I'm trying to create an animation in Flutter that requires a different outcome every time the user presses a button.
I've implemented the following code according to the Flutter Animations tutorial and created a function to update it.
class _RoulettePageWidgetState extends State<RoulettePageWidget>
with SingleTickerProviderStateMixin {
Animation<double> _animation;
Tween<double> _tween;
AnimationController _animationController;
int position = 0;
#override
void initState() {
super.initState();
_animationController =
AnimationController(duration: Duration(seconds: 2), vsync: this);
_tween = Tween(begin: 0.0, end: 100.0);
_animation = _tween.animate(_animationController)
..addListener(() {
setState(() {});
});
}
void setNewPosition(int newPosition) {
_tween = Tween(
begin: 0.0,
end: math.pi*2/25*newPosition);
_animationController.reset();
_tween.animate(_animationController);
_animationController.forward();
}
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
Center(
child: Transform.rotate(
angle: _animationController.value,
child: Icon(
Icons.arrow_upward,
size: 250.0,
),
)),
Expanded(
child: Container(),
),
RaisedButton(
child: Text('SPIN'),
onPressed: () {
setState(() {
setNewPosition(math.Random().nextInt(25));
});
},
)
],
)
);
}
}
As you can see I'm updating the _tween's begin: and end: but this doesn't seem to change the animation.
So what should I be doing to create a 'different' animation every time the users presses the button?
The general idea is to make the animations build upon each other with a random new value so for example:
first spin: 0 -> 10
second spin: 10 -> 13
third spin: 13 -> 18
... etc
So I wondered if I could update the animation, or should I create a new animation every time?
Another thing I could think of was tracking the positions and use the same animation every time (0.0 -> 100.0) to act as a percentage of the transfer.
So instead of creating a new animation from 10 -> 15 I would be doing something like:
currentValue = 10 + (15-10)/100*_animationController.value
I'm going to skip your code a bit, and focus on what you're really asking:
The general idea is to make the animations build upon each other with a random new value so for example:
first spin: 0 -> 10
second spin: 10 -> 13
third spin: 13 -> 18
... etc
With an explicit animation like this, there are three objects you are interested in:
a controller, which is a special kind of Animation that simply generates values linearly from its lower to its upper bound (both doubles, typically 0.0 and 1.0). You can control the flow of the animation - send it running forward, reverse it, stop it, or reset it.
a tween, which isn't an Animation but rather an Animatable. A tween defines the interpolation between two values, which don't even have to be numbers. It implements a transform method under the hood that takes in the current value of an animation and spits out the actual value you want to work with: another number, a color, a linear gradient, even a whole widget. This is what you should use to generate your angles of rotation.
an animation, which is the animation whose value you're actually going to work with (so this is where you'd grab values to build with). You get this by giving your tween a parent Animation to transform - this might be your controller directly but can also be some other sort of animation you've built on it (like a CurvedAnimation, which would give you easing or bouncy/elastic curves and so on). Flutter's animations are highly composable that way.
Your code is failing largely because you're not actually using the top-level animation you created in your build method and you're creating a new tween and animation every time you call setNewPosition. You can use the same tween and animation for multiple animation "cycles" - simply change the begin and end properties of the existing tween and it bubbles up to the animation. That ends up something like this:
class _RoulettePageWidgetState extends State<RoulettePageWidget>
with SingleTickerProviderStateMixin {
Animation<double> _animation;
Tween<double> _tween;
AnimationController _animationController;
math.Random _random = math.Random();
int position = 0;
double getRandomAngle() {
return math.pi * 2 / 25 * _random.nextInt(25);
}
#override
void initState() {
super.initState();
_animationController =
AnimationController(duration: Duration(seconds: 2), vsync: this);
_tween = Tween(begin: 0.0, end: getRandomAngle());
_animation = _tween.animate(_animationController)
..addListener(() {
setState(() {});
});
}
void setNewPosition() {
_tween.begin = _tween.end;
_animationController.reset();
_tween.end = getRandomAngle();
_animationController.forward();
}
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
Center(
child: Transform.rotate(
angle: _animation.value,
child: Icon(
Icons.arrow_upward,
size: 250.0,
),
)),
Expanded(
child: Container(),
),
RaisedButton(
child: Text('SPIN'),
onPressed: setNewPosition,
)
],
)
);
}
}
Hope that helps!
While working, in no situation will you actually want to make these animations within your layout as explained by #filleduchaos.
This is under optimized, as you're rebuilding far more than you should for the animation. And it's a pain to write yourself.
You'll want to use the AnimatedWidget family for this. They are divided into two
kinds:
XXTransition
AnimatedXX
The first is a low layer that consumes an Animation and listens to it so that you don't need to do that ugly :
..addListener(() {
setState(() {});
});
The second handles the remaining pieces: AnimationController, TickerProvider and Tween.
This makes using animations much easier as it's almost entirely automatical.
In your case a rotation example would be as followed:
class RotationExample extends StatefulWidget {
final Widget child;
const RotationExample({
Key key,
this.child,
}) : super(key: key);
#override
RotationExampleState createState() {
return new RotationExampleState();
}
}
class RotationExampleState extends State<RotationExample> {
final _random = math.Random();
double rad = 0.0;
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _rotate,
child: AnimatedTransform(
duration: const Duration(seconds: 1),
alignment: Alignment.center,
transform: Matrix4.rotationZ(rad),
child: Container(
color: Colors.red,
height: 42.0,
width: 42.0,
),
),
);
}
void _rotate() {
setState(() {
rad = math.pi * 2 / 25 * _random.nextInt(25);
});
}
}
Easier right?
The irony is that Flutter forgot to provide an AnimatedTransform (even although we have many others !). But no worries, I made it for you!
The AnimatedTransform implementation is as followed :
class AnimatedTransform extends ImplicitlyAnimatedWidget {
final Matrix4 transform;
final AlignmentGeometry alignment;
final bool transformHitTests;
final Offset origin;
final Widget child;
const AnimatedTransform({
Key key,
#required this.transform,
#required Duration duration,
this.alignment,
this.transformHitTests = true,
this.origin,
this.child,
Curve curve = Curves.linear,
}) : assert(transform != null),
assert(duration != null),
super(
key: key,
duration: duration,
curve: curve,
);
#override
_AnimatedTransformState createState() => _AnimatedTransformState();
}
class _AnimatedTransformState
extends AnimatedWidgetBaseState<AnimatedTransform> {
Matrix4Tween _transform;
#override
void forEachTween(TweenVisitor<dynamic> visitor) {
_transform = visitor(_transform, widget.transform,
(dynamic value) => Matrix4Tween(begin: value));
}
#override
Widget build(BuildContext context) {
return Transform(
alignment: widget.alignment,
transform: _transform.evaluate(animation),
transformHitTests: widget.transformHitTests,
origin: widget.origin,
child: widget.child,
);
}
}
I will submit a pull request so that in the future you won't need this bit of code.
If you want to reverse your animation with a different path (go/back way). Try this.
In your setNewPosition function, just define new begin/end value for _tween.
void setNewPosition() {
_tween.begin = 0; //new begin int value
_tween.end = 1; //new end int value
_animationController.reverse();
}

How to create a hero style animation on the same screen route with Flutter?

I'm trying to create a dynamic animation described in the mockup above. What I need is:
A round shape that will represent an avatar (user pic, for example);
A text centered below it.
Below those (that use half of the screen) is a scrollable PageView.
The animation should be as the following:
Begin: In a Stack both centered at the begin.
Animation: Scaling down and sliding the text (with variable lenght) that must be to the right of the avatar.
End: As the second image in the mockup. Side-to-side while the content below keeps scrolling.
Thought in SliverPersistentHeader combined with CustomMultiChildLayout but the problem is that the text starts centered and ends align to the left and I can animate this dynamically. I was trying to remove the offset of the centered text in the end but it doesn't feel right.
Any help or a sample only with this animation would be appreciate. Thank you.
You will need a Sliver to animate your layout based on the scroll offset. More specifically, SliverPersistentHeader in your situation.
CustomMultiChildLayout is not necessary though, you can achieve the same result using tweens and align/padding/stuff. But you can give it a go if your layout starts to become too complex.
The trick is to use the scroll offset given by SliverPersistentHeader to compute the current progression. Then use that progression to position element between their original and final position.
Here's a raw example:
class TransitionAppBar extends StatelessWidget {
final Widget avatar;
final Widget title;
const TransitionAppBar({this.avatar, this.title, Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return SliverPersistentHeader(
pinned: true,
delegate: _TransitionAppBarDelegate(
avatar: avatar,
title: title,
),
);
}
}
class _TransitionAppBarDelegate extends SliverPersistentHeaderDelegate {
final _avatarTween =
SizeTween(begin: Size(150.0, 150.0), end: Size(50.0, 50.0));
final _avatarMarginTween =
EdgeInsetsTween(begin: EdgeInsets.zero, end: EdgeInsets.only(left: 10.0));
final _avatarAlignTween =
AlignmentTween(begin: Alignment.topCenter, end: Alignment.centerLeft);
final _titleMarginTween = EdgeInsetsTween(
begin: EdgeInsets.only(top: 150.0 + 5.0),
end: EdgeInsets.only(left: 10.0 + 50.0 + 5.0));
final _titleAlignTween =
AlignmentTween(begin: Alignment.center, end: Alignment.centerLeft);
final Widget avatar;
final Widget title;
_TransitionAppBarDelegate({this.avatar, this.title})
: assert(avatar != null),
assert(title != null);
#override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent) {
final progress = shrinkOffset / 200.0;
final avatarSize = _avatarTween.lerp(progress);
final avatarMargin = _avatarMarginTween.lerp(progress);
final avatarAlign = _avatarAlignTween.lerp(progress);
final titleMargin = _titleMarginTween.lerp(progress);
final titleAlign = _titleAlignTween.lerp(progress);
return Stack(
fit: StackFit.expand,
children: <Widget>[
Padding(
padding: avatarMargin,
child: Align(
alignment: avatarAlign,
child: SizedBox.fromSize(size: avatarSize, child: avatar),
),
),
Padding(
padding: titleMargin,
child: Align(
alignment: titleAlign,
child: DefaultTextStyle(
style: Theme.of(context).textTheme.title, child: title),
),
)
],
);
}
#override
double get maxExtent => 200.0;
#override
double get minExtent => 100.0;
#override
bool shouldRebuild(_TransitionAppBarDelegate oldDelegate) {
return avatar != oldDelegate.avatar || title != oldDelegate.title;
}
}
which you can use with a CustomScrollView:
Scaffold(
body: CustomScrollView(
slivers: <Widget>[
TransitionAppBar(
avatar: Material(
color: Colors.blue,
elevation: 3.0,
),
title: Text("Hello World"),
),
SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
return ListTile(
title: Text('$index'),
);
}),
)
],
),
);

Resources