簡體   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