当我在文本字段上输入新项目时,Consumer Widget 没有重建,我该如何解决这个问题?(我只有在热重启时才能看到新项目)
这是我使用消费者小部件的地方:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpodtx/providers/txprovider.dart';
final transactionProvider = StateNotifierProvider((ref) => TxState());
class CurrTx extends ConsumerWidget {
//Current transaction List
@override
Widget build(BuildContext context, ScopedReader watch) {
final txList = watch(transactionProvider.state);
return Container(
height: 240,
margin: EdgeInsets.only(top: 15),
child: ListView(
children: txList.map((e) {
return ListTile(
tileColor: Colors.pink,
title: Text(e.title),
leading: Text(e.price),
);
}).toList(),
));
}
}
这是我使用提交按钮添加新项目的地方:
class NewTx extends StatelessWidget {
final TextEditingController titleController = TextEditingController(text: '');
final TextEditingController priceController = TextEditingController(text: '');
@override
Widget build(BuildContext context) {
return Container(
child:
Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
TextField(
controller: titleController,
decoration: InputDecoration(labelText: 'Title'),
),
TextField(
decoration: InputDecoration(labelText: 'Price'),
controller: priceController,
keyboardType: TextInputType.number,
),
Container(
alignment: AlignmentDirectional.bottomEnd,
child: IconButton(
icon: Icon(Icons.add),
onPressed: () => context.read(transactionProvider).addTx(
Transaction(titleController.text, priceController.text))))
]));
}
}
这是状态通知程序:
import 'package:riverpodtx/models/transaction.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class TxState extends StateNotifier<List<Transaction>> {
TxState([List<Transaction>? _transaction]) : super(_transaction ?? []);
void addTx(Transaction tx) {
state.add(tx);
}
}
答案 0 :(得分:4)
要让 StateNotifier 触发状态更新,您必须实际更新状态对象。
也就是说,状态必须替换为不等于由相等运算符 ==
评估的旧值的内容,以触发对其侦听器的通知。
不要使用 List.add
,而是尝试使用扩展运算符 ...
创建一个新列表:
class TxState extends StateNotifier<List<Transaction>> {
TxState([List<Transaction>? _transaction]) : super(_transaction ?? []);
void addTx(Transaction tx) {
state = [...state, tx];
}
}