繁体   English   中英

Flutter:从 DataTableSource 中的方法更新 PaginatedDataTable?

[英]Flutter: update PaginatedDataTable from method in DataTableSource?

我想我已经接近解决这个问题了,但不知道该怎么做,也许还有更好的方法。

我有这个WeightDataSourceWeightDialog将简单地返回用户输入的数字。 这些值正确地存储在内存中,但当然屏幕没有更新,因为另一个类中的状态没有改变(如果我重新加载应用程序,我可以看到更改)。

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);
    }
  }

您是否尝试在数据源上调用 notifyListeners() ? 这就是对我有用的东西。

我认为在您的情况下,它必须在 _editCell() 方法中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM