Edit: Fixed it.. Look down
Old problem:
I am experimenting with the Dismissible widget. I can successfully monitor the state of the direction, which is stored in directionVar. It outputs something like DismissDirection.endToStart
I want to use this information, to change the placement of the icon that I show. When removing an item, the background is red, with an icon on the right to it. Something in the style like Gmail.
Widget build(BuildContext context) {
DismissDirection directionVar;
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Dismissible(
key: Key(products[index]['title']), //Should be unique.
onDismissed: (DismissDirection direction) {
directionVar = direction;
},
My issue is this part:
background: Container(
color: Colors.red,
padding: EdgeInsets.only(left: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Icon(
Icons.delete,
)
],
),
),);});}
I want this part to change dependent on the directionVar
value. The padding
should change dependent on the value of directionVar
, together with the mainAxisAlignment
.
Something along these lines:
if(directionVar == DismissDirection.endToStart){
} else if (directionVar == DismissDirection.startToEnd){
}
But I can't access the background
: and padding
property in these statements, since they are a property of the Dismissible
widget and can't be changed inside onDismissed(){}
This seems like simple problem but can't seem to solve it.
Edit: Fixed it.. Very easy.. Just added this:
secondaryBackground: Container(
color: Colors.red,
padding: EdgeInsets.only(right: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Icon(
Icons.delete,
)
],
),
),
There are a few ways that you can achieve this. For example, you can create a method that handles the direction dynamically and then update it accordingly in your widget tree. Something like
List<dynamic> _resolveDirection(DismissDirection direction) {
switch (direction) {
case DismissDirection.endToStart:
return [MainAxisAlignment.center, 20.0];
break;
case DismissDirection.startToEnd:
return [MainAxisAlignment.start, 10.0];
break;
case DismissDirection.vertical:
return [MainAxisAlignment.end, 5.0];
break;
// And so on...
default:
return [];
}
}
and then replace your tree with
background: Container(
color: Colors.red,
padding: _resolveDirection(directionVar)[1],
child: Row(
mainAxisAlignment: _resolveDirection(directionVar)[0],
children: <Widget>[
Icon(
Icons.delete,
)
],
),
),);});}
In the end, all you have to do everytime a swipe occurs, is just rebuild your tree with the direction updated
setState(() => directionVar = direction);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.