【问题标题】:In Flutter: Is it possible to use a Future<bool> be used as a property in another widget?在 Flutter 中:是否可以将 Future<bool> 用作另一个小部件中的属性?
【发布时间】:2020-09-08 13:04:51
【问题描述】:

我有一个 Card() 小部件,其中包含一个 ListTile() 小部件。

ListTile() 小部件的属性之一是enabled。我想通过使用使用异步和等待的Future&lt;bool&gt; 的结果来动态设置此enabled 属性的值。这可能吗?

这是 Card() 小部件,其中包含 ListTile()

  Card myCard = Card(
    child: ListTile(
      title: Text('This is my list tile in a card'),
      enabled: needsToBeEnabled(1),
    ),
  );

这是我的未来

  Future<bool> cardNeedsToBeEnabled(int index) async {
    bool thisWidgetIsRequired = await getAsynchronousData(index);
    if (thisWidgetIsRequired == true) {
      return true;
    } else {
      return false;
    }
  }

其他尝试 我曾尝试使用 Future Builder。这在我构建 widget 时效果很好,但在这种情况下,我试图设置小部件的 property;不要自己构建小部件。

【问题讨论】:

    标签: flutter


    【解决方案1】:

    你不能这样做有两个原因:

    1. enable 不接受Future&lt;bool&gt;bool
    2. 收到结果后需要更新状态(需要StatefullWidget

    有 100 万种方法可以做您想做的事情,其中​​之一是 FutureBuilder,但如果您不想重建所有小部件,您可以使用此流程(您的主要小部件需要有状态):

    1. 创建一个包含布尔值的局部变量,例如bool _enabled
    2. initState() 方法覆盖上,您可以启动获取异步数据的调用,并使用then() 扩展方法,您可以在调用完成时为您的小部件提供新状态。 比如:
    @override
      void initState() {
        super.initState();
        getAsynchronousData(index).then((result) {
          if (result == true) {
            _enabled = true;
          } else {
            _enabled = false;
          }
          setState(() {});
        });
      }
    
    1. 将布尔变量分配给ListTile 小部件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 2023-01-03
      • 2019-01-30
      • 2020-08-22
      • 2022-08-03
      • 2021-09-10
      相关资源
      最近更新 更多