【问题标题】:Is there a FutureBuilder alternative that would NOT require a Widget as the output?是否有不需要 Widget 作为输出的 FutureBuilder 替代方案?
【发布时间】:2021-10-11 18:52:52
【问题描述】:

这是我的背景图片:

 Container(
           decoration: BoxDecoration(image: DecorationImage(fit: BoxFit.cover, image: FileImage(widget.lightAnimation.imageFile))),
widget.lightAnimation.imageFile: FutureBuilder(
             future: getImageFile(),
             builder: (context, snapshot) => snapshot.data,
           )

Future<File> getImageFile() 返回一个File

问题是输出必须是一个小部件,FileBoxDecoration 都不被认为是 Widget 下一个最接近的将是 Container,但是这在我的情况下不起作用因为 Container 的子节点非常健壮,包含许多变量、函数等。

换句话说,我可以做的是:

FutureBuilder(
             future: getImageFile(),
             builder: (context, snapshot) => Container(
          decoration: BoxDecoration(image: DecorationImage(fit: BoxFit.cover, image: FileImage(snapshot.data))),
          ),
           )

但是,在这种情况下,我必须将我所有的大孩子都搬到 FutureBuilder 中,因为 Container 会随身携带,我不想这样做。

我可以使用任何替代方法来代替不需要 Widget 作为输出的 FutureBuilder 吗?或者也许有其他可能的方法来让我的背景图像具有未来的“建造者/制造者/功能”?

【问题讨论】:

  • 你试过 getImageFile().whenComplete(() => ...) 还是 .then()
  • 我不确定你会在哪里添加它。能具体说明一下吗?
  • 我不明白为什么FutureBuilder 如果你有一些Future 没有用:你有一些Container 那你为什么不想从builder: .... 代码返回它?
  • 因为让 FutureBuilder 返回一个 FileFileImageDecoratingImage 给我一个错误,即 FutureBuilder 构建器必须构建/返回一个小部件,例如Container。因此,与其在 FutureBuilder 中返回/构建它:builder: (context, snapshot) => snapshot.data, 我将不得不返回/构建:builder: (context, snapshot) => Container(decoration: BoxDecoration(image: DecorationImage(fit: BoxFit.cover, image: FileImage(snapshot.data))),,我不想这样做。
  • 如果你不想 FutureBuilder 使用 getImageFile().then((file) => setState(() => _file = file)); 并将其添加到 initState() 方法中 - 但老实说这是 FutureBuilder 完全构建你的小部件的工作,上面的代码你正在复制FutureBu8ilder的代码

标签: flutter dart asynchronous future


【解决方案1】:

这就是 ValueListenableBuilder 的用途。

 ValueListenableBuilder<File>(
                valueListenable: imageFile,
                builder: (_, _imageFile, __) {
                  return  Container(
           decoration: BoxDecoration(image: DecorationImage(fit: BoxFit.cover, image: _imageFile ));
                })

imageFile 必须是ValueNotifier&lt;File&gt;。有两种方式:

  • 像这样声明 imageFile:
final imageFile = ValueNotifier<File>("initial_File");
  • 或者像这样在一个单独的类中:
class ImageFile extends ValueNotifier<File> {
updateFile() => value='newFile';
}

不过,最好将 FilePath 实现为可听变量而不是 File。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2014-01-29
    相关资源
    最近更新 更多