我想我已经接近解决这个问题了,但是我不确定该怎么做,也许还有更好的方法。
我有这个WeightDataSource,WeightDialog将简单地返回一个用户输入的数字。值被正确地存储在内存中,但当然屏幕没有更新,因为另一个类中的状态没有更改(如果我重新加载应用程序,我可以看到更改)。
class WeightDataSource extends DataTableSource {
final List<Weight> _weights;
final BuildContext context;
WeightDataSource(this.context, this._weights);
int _selectedCount = 0;
_editCell(index, Weight _weight) async {
print('$index $_weight');
var updatedWeight = await Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
WeightDialog(
color: Colors.greenAccent,
saveUpdate: 'update',
),
fullscreenDialog: true,
));
if (updatedWeight != null) {
print('received weight: $updatedWeight');
final prefs = await SharedPreferences.getInstance();
var tempWeights = json.decode(prefs.getString('weights')) ?? {};
tempWeights[_weight.date.toString()] = updatedWeight;
prefs.setString('weights', json.encode(tempWeights));
tempWeights = json.decode(prefs.getString('weights')) ?? {};
print('updated weights $tempWeights');
}
}
// ...我的想法是,如果我能以某种方式调用我的_loadAsyncData函数,屏幕就会更新,但我不确定如何从不同的类中做到这一点:
class HistoryPageState extends State<HistoryPage> {
var calories = {};
var weights = {};
@override
void initState() {
super.initState();
_loadAsyncData();
}
_loadAsyncData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
calories = json.decode(prefs.getString('calories')) ?? {};
weights = json.decode(prefs.getString('weights')) ?? {};
});
}
// ...
_updateWeights(BuildContext context, _weightsDataSource) async {
var inputCalories = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Scaffold(
appBar: AppBar(title: Text('Update weights')),
body: PaginatedDataTable(
header: Text('Weight Log'),
dataRowHeight: 30,
headingRowHeight: 30,
rowsPerPage: 3,
columns: <DataColumn>[
DataColumn(
label: Text('Date'),
),
DataColumn(label: Text('Weight'))
],
source: _weightsDataSource,
),
),
fullscreenDialog: true,
));
if (inputCalories != null) {
print(inputCalories);
}
}发布于 2019-11-15 10:40:20
您是否尝试在数据源上调用notifyListeners()?这对我来说很管用。
我认为在您的例子中,它必须在_editCell()方法中。
https://stackoverflow.com/questions/57280777
复制相似问题