当我追加新元素到现有列表中并在屏幕上显示列表后,有时新元素显示在列表顶部,有时显示在最后。
为什么List会这样?
在下面的代码中,我想在列表顶部显示这个新添加的元素。有没有办法做到这一点?
class _TransactionListState extends State<TransactionList> {
// Existing List with two transactions
final List<Transaction> transactions = [
Transaction(
title: 'New Books',
id: 't1',
amount: 44.55,
date: DateTime.now(),
),
Transaction(
title: 'Weekly Items',
id: 't2',
amount: 22.44,
date: DateTime.now(),
),
];
final titleController = TextEditingController();
final amountController = TextEditingController();
void addTransactions() {
// Add new transaction
Transaction tx = Transaction(
title: titleController.text,
amount: double.parse(amountController.text),
date: DateTime.now(),
id: DateTime.now().toString());
setState(() {
// Add new transaction to existing List. I want this new element on top of screen
transactions.add(tx);
});
}
最佳答案
使用List的insert()方法添加项目,此处的索引将为0,以将其开头添加。示例:
List<String> transactions = ["Items1", "Items2", "Items3"];
transactions.insert(0, "New Value");
关于flutter - 为什么列表在添加新元素时表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63504177/