Hello I am having issue to understand how to manage properties of a class when it is part of a list of classes
Here are my classes
class BasketItem {
final String itemDescription;
final String itemNote;
BasketItem(
{this.itemDescription,
this.itemNote});
}
class AppData {
static final AppData _appData = new AppData._internal();
List<BasketItem> basketList = [];
factory AppData() {
return _appData;
}
AppData._internal();
}
final appData = AppData();
And here is my List
List<Container> _buildBasketList() {
return appData.basketList.map((bList) {
var container = Container(
child: Builder(
builder: (context) => Dismissible(
key: Key(UniqueKey().toString()),
background: Container(
margin: EdgeInsets.all(8.0),
color: kColorAccent,
child: Align(
alignment: Alignment(-0.90, 0.00),
child: Icon(Icons.add_comment)),
),
onDismissed: (direction) {
final newItemToAdd = BasketItem(
itemDescription: bList.itemDescription,
itemNote: 'xxxxx',);
appData.basketList.add(newItemToAdd);
setState(() {});
appData.basketList.remove(bList);
},
child: Stack(...)
),
),
);
return container;
}).toList();
}
I would like to do the following: when onDismissed
get executed I would like to amend the property itemNote
to 'xxxxx'. How can I do it? At the moment I remove the BasketItem I have swiped and I create a new BasketItem and I add it to the list. The problem is that this does not seem efficient and it also add the item at the end of the list while I would like to keep it at the same position/index where it was.
Thanks
Make fields in BasketItem
non final. So you can amend them.
class BasketItem {
final String itemDescription;
/*final*/ String itemNote;
BasketItem(
{this.itemDescription,
this.itemNote});
}
// onDismissed will change itemNote.
....
onDismissed: (direction) {
setState(() {
bList.itemNote = 'xxxxx';
});
},
...
Replace list contents inline. Don't remove and add
List<Container> _buildBasketList() {
return appData.basketList.asMap().map((index, bList) {
var container = Container(
child: Builder(
builder: (context) => Dismissible(
key: Key(UniqueKey().toString()),
background: Container(
margin: EdgeInsets.all(8.0),
color: kColorAccent,
child: Align(
alignment: Alignment(-0.90, 0.00),
child: Icon(Icons.add_comment)),
),
onDismissed: (direction) {
setState(() {
appData.basketList[index] = BasketItem(
itemDescription: bList.itemDescription,
itemNote: 'xxxxx',);
});
},
child: Stack(...)
),
),
);
return container;
}).toList();
}
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.