【问题标题】:The return type 'Widget?' isn't a 'Widget', as required by the closure's context返回类型“小部件?”不是闭包上下文所要求的“小部件”
【发布时间】:2021-09-27 21:43:37
【问题描述】:

我正在使用消费者小部件来避免在 null 安全之前重新渲染它工作正常......但是当我将提供程序包升级到它时给我一个错误,我上面提到它不接受 ListView.builder() 并说返回根据闭包上下文的要求,类型 Widget? 不是 Widget


Consumer<GreatPlaces>(
        child: Center(
          child: const Text(
            'Got no places yet, start adding some',
          ),
        ),
        builder: (ctx, greatPlaces, ch) => greatPlaces.items.length <= 0
            ? ch
            : ListView.builder(          ***//Here I got error***
                itemBuilder: (ctx, index) => Center(),
                itemCount: 5,
              ),
      ),

【问题讨论】:

  • 请添加更多关于你想要做什么的信息
  • 我正在使用消费者小部件来避免在空安全之前重新渲染它工作正常......但是当我将提供程序包升级到它时给我一个错误,我上面提到它不接受 ListView.builder () 并说 返回类型 'Widget?'不是闭包上下文所要求的“小部件”
  • 在 Flutter 的 null-safety 更新中,Widget? 是可空的,Widget 是不可空的。我猜ListView.builder 有时可能为空,这就是导致您的问题的原因。尝试用 Container() 替换 ListView.builder... 并重新运行您的代码。如果错误消失,那么您就知道问题所在了,您需要在没有 .builder 构造函数的情况下定义小部件
  • 我在没有构建器的情况下定义 ListView,它给了我同样的错误

标签: flutter flutter-layout


【解决方案1】:

ch!使用bang!操作

 data.state.length <= 0
          ? child!
          : ListView.builder(
              itemBuilder: (context, index) => Container(),
              itemCount: 4,
            );

【讨论】:

  • 您的解决方案解决了我在此代码上的问题: body: Consumer( builder: (ctx, greatPlaces, ch) => greatPlaces.items.length
  • 对我来说太解决了
猜你喜欢
  • 1970-01-01
  • 2021-11-17
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 2023-02-13
  • 2021-09-11
  • 2019-10-28
  • 2021-08-07
相关资源
最近更新 更多