I have added a rive ❤️ heart animation to a iconButton in flutter. when I tap on it, it animates from Unlike > Like and when I tapped again it animates backwards. Which is perfectly working. But the thing is, when I close the page and reopen the same page, Rive animation animates again from the very beginning (the default state of the animation is outline bordered heart icon, which I have to tap on it to make ❤️ filled heart icon). So the problem is if I like an item, close the page and then reopened the page I have to tap on it again, in order to make the item favorite or not. I also created a isFavorite bool to tack the icon button state, the thing is I don't know how to sync the bool with rive animation.
So this is what I want: I need the riveAnimation to stay liked or unliked according to the state of isFavourite bool + Unlike, Dislike transition animation. This may be hard to understand. Please leave a comment what part is that you do not understand.
Rive Animation I Used (go to rive)
class Place with ChangeNotifier {
bool isFavourite;
Place(
{this.isFavourite = false});
void toggleFavouriteStatus() {
isFavourite = !isFavourite;
notifyListeners();
}
}
.
.
.
.
.
.
.
SMIInput<bool>? _heartButtonInput;
Artboard? _heartButtonArtboard;
#override
void initState() {
super.initState();
rootBundle.load('assets/rive/heart.riv').then(
(data) {
final file = RiveFile.import(data);
final artboard = file.mainArtboard;
var controller = StateMachineController.fromArtboard(
artboard,
'state',
);
if (controller != null) {
artboard.addController(controller);
_heartButtonInput = controller.findInput('Like');
}
setState(() => _heartButtonArtboard = artboard);
},
);
}
#override
Widget build(BuildContext context) {
final Fav = Provider.of<Place>(context); // I used provider package to retrieve bool data
void _heartButtonAnimation() {
if (_heartButtonInput?.value == false &&
_heartButtonInput?.controller.isActive == false) {
_heartButtonInput?.value = true;
} else if (_heartButtonInput?.value == true &&
_heartButtonInput?.controller.isActive == false) {
_heartButtonInput?.value = false;
}
}
return Stack(
alignment: Alignment.bottomCenter,
children: [
Positioned(
right: 8,
top: 8,
child: Container(
child: Center(
child: Material(
color: Colors.transparent,
child: _heartButtonArtboard == null
? const SizedBox()
: IconButton(
onPressed: () {
Fav.toggleFavouriteStatus();
_heartButtonAnimation();
},
icon: Rive(
artboard: _heartButtonArtboard!,
fit: BoxFit.cover,
),
),
),
),
),
)
],
);
}
}
I'm not sure if I understood correctly. When your record is already given a heart, then after revisiting it, you want the heart to be displayed in "liked" state without running animating it. Is that it?
If so, IMO the problem is within your state machine not allowing the animation to be started in the desired state of "liked". For the heart to get to the liked state, it needs to pass through the liking animation. This is how your state machine looks now:
You should define two paths from Entry state depending on the value of your Like input. Take a look at a state machine from a checkbox I've imported to Flutter lately. Each of the "idle" timelines have only one keyframe for being checked or unchecked. On entry, there's an intersection where a decision is made based on the initial value of checked input.
This way you can display your heart in the desired state without any animation happening when the widget is built.
Related
I want to create a list of widgets depending on the content of two or three dynamically generated lists.
List<String> Sound = ['A','B','C'];
List<String> Number = ['1','2','3'];
List<int> vertical = [10,20,30];
List<int> horizontal = [20,30,40];
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Row(
children: Sounds.map((sound) {
return FloatingActionButton(
onPressed: () => _audioCache.play(Sound),
child: Text(Number),
);
}).toList(),
),
),
);
}
}
Using the map function it seems like I can only build a list of Floating action buttons with one property. I want to give each button created by the map function properties from multiple different lists. How can I achieve that? This build function is in the state class of a stateful widget.
To expand on Uni's comment, here is a simple Dart program that shows the use of List.generate to create a list of Maps from two lists - your code would create your widgets:
void main() {
List<String> Sound = ['A', 'B', 'C'];
List<String> Number = ['1', '2', '3'];
var list = List.generate(
Sound.length,
(i) => {'Sound': Sound[i], 'Number': Number[i]},
);
print(list);
}
BTW it is recommended to name non-constant identifiers using lowerCamelCase, so Sound should be sound.
I would personally remodel the data.
If you are always using the same index of each list to build the widget why not make the a class with a sound and a number as properties then have one list of those objects.
Then the map you have would just be over those objects
enter image description here
Change the form field by selecting different fieldsqVS3e.gif
Try to use some kind of switch case or any form of iterator, when selecting the item from the drop down menu, you pass the value to another switch case again (or if statements, what ever you prefer) that renders the input fields depending on the selected value from the dropdown menu.
enum Menu { one, two, three }
PopupMenuButton<Menu>(
onSelected: (methods) {
switch (methods) {
case Menu.one:
/// method that passed the data and tells some sort of builder like an `ListView` Builder, hey build a list with these form fields
break;
case Menu.two:
// another method with different form fields
break;
case Menu.three:
// and again, a different method
break;
}
},
itemBuilder: (BuildContext context) =>
<PopupMenuEntry<Menu>>[
const PopupMenuItem<Menu>(
value: Menu.one,
child: Text('One'),
),
const PopupMenuItem<Menu>(
value: Menu.two,
child: Text('Two'),
),
const PopupMenuItem<Menu>(
value: Menu.three,
child: Text('Three'),
),
],
),
then the passed value from the PopUpMenu is put in a, like I said, switch case like above or an if statement:
if(value from dropdown one){
// build a `Form` with specific `TextFormField`s
} else if (value from the dropdown two) {
// build this `Form` with specific `TextFormField`s
} else (value from dropdown three){
// then build this `Form` with specific `TextFormField`s
}
I'm receiving a list of images that I want to display dynamically in rows of 4 items each row. If there are 5 itens the row should wrap. The thing is, I need the images to allow for a longpress click that opens edit buttons in the appBar. Besides the edit button when longing pressing, it should allow for multiple selecting the other images.
Could this code be adapted for that:
class cardy extends StatefulWidget {
#override
_cardyState createState() => new _cardyState();
}
class _cardyState extends State<cardy> {
var isSelected = false;
var mycolor=Colors.white;
#override
Widget build(BuildContext context) {
return new Card(
color: mycolor,
child: new Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
new ListTile(
selected: isSelected,
leading: const Icon(Icons.info),
title: new Text("Test"),
subtitle: new Text("Test Desc"),
trailing: new Text("3"),
onLongPress: toggleSelection // what should I put here,
)
]),
);
}
void toggleSelection() {
setState(() {
if (isSelected) {
mycolor=Colors.white;
isSelected = false;
} else {
mycolor=Colors.grey[300];
isSelected = true;
}
});
}
}
Yes, this code can be adapted for that ;)
To start, check out SliverGrid class.
https://api.flutter.dev/flutter/widgets/SliverGrid-class.html
Here is a (not complete) snippet to get you started, but you'll have to specify what options you want to use because this will not copy and paste solve your problem:
SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200.0,
mainAxisSpacing: 5,
crossAxisSpacing: 3,
crossAxisCount,
),
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Container()})),
I'll note that if you want to use the information you're gathering, namely which images you're selecting, do take care to store that information somewhere. That is, your example toggles selection for a single item, but how will you get that information later? That is, if you click 3 items then hit edit, you need a way to record which 3 items have been selected. One option is maintaining a list and .removing / .adding it as part of your toggle.
I'm building a Workout Tracker app using Flutter and Dart. On the tracking page are lists of exercises and a done Icon, when clicked, changes its color(To show that you're done with the set). Icon state changes locally in the file.
So the problem is when I scroll down, the upper items revert back to their original state. Long story short, I don't want the icons to Rerender on demand and save their state until I want to.
Tried AutomaticKeepAliveStateMixin but it doesn't seem to be working. I'm a newbie in coding so maybe I am implementing it wrong.
class _ExerciseInputState extends State<ExerciseInput>
with AutomaticKeepAliveClientMixin {
#override
bool get wantKeepAlive => true;
#override
Widget build(BuildContext context) {
super.build(context);
var deviceSize = MediaQuery.of(context).size;
return ListView.builder(
itemCount: widget.loadedRoutine.exercises.length,
itemBuilder: (BuildContext context, int i) {
return buildExerciseContainer(
widget.loadedRoutine.exercises[i].title,
widget.loadedRoutine.exercises[i].sets,
widget.loadedRoutine.exercises[i].reps,
deviceSize,
context);
},
);
}
}
No error messages.
I am trying to build an Flutter App with a GriView of cards and I want to add a new Card every time I hit the floatingActionButton. But how to update my view? I know the items are added to my list, but the GridView doesn't show the change.
List<Widget> cardsList = [];
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('Team Kitty'),
),
body: GridView.builder(
itemCount: cardsList.length,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemBuilder: (BuildContext context, int index) {
return Container(child: cardsList[index]);
}),
floatingActionButton: new FloatingActionButton(
onPressed: addCard(),
tooltip: 'Add Card',
child: new Icon(Icons.add),
),
);
}
addCard() {
setState(() {
cardsList.add(_RobotCard());
});
}
}
I find it hard to find good Grid documentation, maybe someone has a hint?
Thx Guys
You invoke addCard method while your widget is built instead of passing method's reference as onPressed parameter:
floatingActionButton: new FloatingActionButton(
onPressed: addCard, // pass method reference here
tooltip: 'Add Card',
child: new Icon(Icons.add),
)
Its too late to answer, but this might help someone who came here finding solution to similar problem .
The problem with this is , list will be updated with values , but builder doesn't rebuild the list immediately which is in visible region of the screen. If suppose you have a long list of cards , and if you add a new item to this list, then it wont be rebuild immediately . To see the change ,keep scrolling down the list and then come back up , then you can see that the builder has rebuild the list.
Hence to solve this issue after not finding any relevant answers, I tried this ,May be it might not be the best solution but it works .
The approach is, if you have a list
List CardList =List();
and it initially has 5 items. So builder would have build 5 cards on the screen.
Then , if a new 6th item is added , then even if you do
setState((){
CardList.add(newItem);
})
Builder won't rebuild immediately .
To solve this, use a variable of type Widget, and initialize with empty Text .
Widget WidgetToBeShownInBody = Text("");
Use this under scaffold , as shown :
#override Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('Team Kitty'),
),
body: WidgetToBeShownInBody,
floatingActionButton: new FloatingActionButton(
onPressed: addCard(),
tooltip: 'Add Card',
child: new Icon(Icons.add),
),
);}
And Modify the onPressed function as this,
So, on every press of the button, empty text is shown in the scaffold for few milliseconds(which is negligible and goes unnoticed) and then the updated list of cards is shown on the screen.
addCard() {
//Show Empty Widget for few milliseconds
setState(() {
WidgetToBeShownInBody=Text("");
});
//update the list with new Item.
cardList.add(SomeNewItem);
//after some milliseconds ,
//use setState to update the variable to list of cards returned by GridViewBuilder
Timer(Duration(milliseconds: 50), () {
setState(() {
WidgetToBeShownInBody=GridView.builder(
itemCount: cardsList.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemBuilder: (BuildContext context, int index) {
return Container(child: cardsList[index]);
});
});
});
}
The above code is kind of fooling the build function , that now UI only has a simple empty text.
But after few milliseconds , UI is rebuild-ed, as the setState updates the new value of variable "WidgetToBeShownInBody" with list of cards.
When a new item is added, show a empty widget instead of the builder for few milliseconds , and then after some millisecond delay , send the builder list with 6 items.
Hence builder rebuilds the UI with 6 items and "WidgetToBeShownInBody" is updated with new list of cards.
Hope this is clear and useful!!
If someone finds a proper solution for this , please do update .
Thanks!