【问题标题】:Change state in FutureBuilder when the data is loaded加载数据时更改 FutureBuilder 中的状态
【发布时间】:2020-12-20 12:00:20
【问题描述】:

如果我需要等待FutureBuilder,如何更新 UI?我是否需要调用我的未来函数两次,一次用于构建器,一次用于更改 UI?

FutureBuilder<String>(
        future: getUserOrder(4045),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Text(snapshot.data,style: Theme.of(context).textTheme.headline);
          } else if (snapshot.hasError) {
            // I need to change the state at this point
            return Text("${snapshot.error}",style: Theme.of(context).textTheme.headline);
          } else {
            return CircularProgressIndicator();
          }
        }),

FutureBuilder 内调用setState 会引发此错误:

在构建期间调用 setState() 或 markNeedsBuild()。

我不需要显示要单击的按钮或任何其他按钮。我想在futureBuilder中加载日期时自动执行操作

【问题讨论】:

  • 你的意思是如果出现错误如何使用状态来重试未来?
  • 这能回答你的问题吗? Reload data when using FutureBuilder
  • 您可以致电setState()。但目标是什么?
  • 你不能在futureBuilder中调用setState(我稍后会添加错误)
  • 更新有错误的问题

标签: flutter flutter-layout


【解决方案1】:

由于我无法在 FutureBuilder 中调用 setState,因此解决方案是删除它并执行以下操作:

getBillingInfo() {
    Provider.of<MyRents>(context, listen: false)
        .getBillingInfo(context)
        .then((billingInfo) {
      setState(() {
        if (billingInfo["companyInfo"] != null &&
            billingInfo["taxes"].isNotEmpty) {
          _canGenerateInvoices = true;
        } else {
          _canGenerateInvoices = false;
        }
      });
    });
  }

...

void initState() {
    super.initState();
    getBillingInfo();
  }

...

Visibility(
 visible: _canGenerateInvoices,
 child: MyWidget()
)

有了这个,当我执行其他操作时,我总是可以更改_canGenerateInvoices的值

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 2019-10-07
    • 1970-01-01
    • 2023-04-04
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    相关资源
    最近更新 更多