【问题标题】:How can I rebuild a widget (with a list) I can't access?如何重建我无法访问的小部件(带有列表)?
【发布时间】:2019-01-20 02:27:59
【问题描述】:

删除其中一项后,我无法更新我的债务清单。

我有一个带有底部导航栏的主屏幕,有两个选项。检查所有项目的列表或一般信息。索引零是列表,因此默认绘制。

https://i.imgur.com/6qOVPPE.png

在我的 main_screen.dart 中,我有一个从 SQLite 数据库获得的 List debtList 女巫。我将此列表传递给每个构造函数。

    Widget _getTab(int currentIndex) {
    switch (currentIndex) {
      case 0:
        return DebtList(debtList);
      case 1:
        return GeneralInfo(debtList);
        break;
      default:
        return DebtList(debtList);
    }
  }

现在我点击一个项目可以访问该项目的信息。

https://i.imgur.com/ikl4cEI.png

当我单击删除时,它可以工作。该项目不再在数据库中,但列表未更新。

dbHelper.deleteDebt(widget.debt.id);
Navigator.pop(context, **true**);

我已经尝试返回 true,所以我可以像这样检查它:

 bool result = await Navigator.push(context, MaterialPageRoute(builder: (context) => DebtDetail(debt)));
    if (result != null && result == true) {
      ...

但是方法 updateList() 在我的 main_screen.dart 类中,而不是在我的 debt_list.dart 类中。

我做错了什么?我无法更新 debt_list 类中的列表,因为它是最终的。

 widget.debtList = debtList; //cant do this

我应该改变什么?

感谢您的宝贵时间!

【问题讨论】:

标签: dart flutter


【解决方案1】:

您需要通知DebtList 知道要删除哪个列表项Debt。由于您在DebtDetail 屏幕上有许多操作来更新列表,例如updatedelete...所以最好定义一个DTO(数据传输对象)类从DebtDetail 传递到DebtList

class DebtActionResult {
    int action; // 0: nothing, 1: update, 2: delete

    int debtId;

    Debt updateDebt;

    DebtActionResult({this.action, this.debtId, this.updateDebt});
}

现在,在DebtDetail 屏幕上,我们必须将结果传递给DebtList

void _delete() {
  DebtActionResult result = DebtActionResult(action: 2, debtId: widget.debt.id, null);
  Navigator.pop(context, result);
}

void _update() {
  DebtActionResult result = DebtActionResult(action: 1, debtId: widget.debt.id, newDebt); // handle this yourself, because you are adding `final` to the state. Remove the final or create a new `newDebt` state variable.
  Navigator.pop(context, result);
}

到目前为止一切顺利,是时候在DebtList 屏幕上处理结果了。

Future<void> _navigateToDetail(Debt debt) async {
  DebtActionResult result = await Navigator.push(context, MaterialPageRoute(builder: (context) => DebtDetail(debt)));

  if (result == null) { 
    // Do nothing, no change
  } else {
    if (result.action == 2) { 
      // oh, it's a delete request
      setState( () {
        widget.debtList.removeWhere( (d) => d.id == result.debtId );
      });

    } else if (result.action == 1) {
      // modify the debtList here .. write your code similar to delete above.
    }
  }
}

【讨论】:

  • 感谢您的回答,我现在无法尝试,但我明天会尝试。希望它有效!。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-04
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 1970-01-01
  • 2015-02-19
相关资源
最近更新 更多