这个函数的返回类型是“Widget”,但没有以返回语句结束。

4
@override
Widget build(BuildContext context) {
  return StreamBuilder(
    stream: slides,
    initialData: [],
    builder: (context, AsyncSnapshot snap) {
      List slideList = snap.data.toList();
      return PageView.builder(
          controller: ctrl,
          itemCount: slideList.length + 1,
          itemBuilder: (context, int currentIdx){
            if (currentIdx == 0) {
              return _buildTagPage();
            }
            else if (slideList.length >= currentIdx){
              bool active = currentIdx == currentPage;
              return _buildStoryPage(slideList[currentIdx - 1], active);
            }
          }
      );
    },
  );
}

这是Reflectly应用的克隆版本的摘录,我在 (context, int currentIdx) { 遇到了错误。

我猜想我需要在某处添加一个返回语句,但不知道应该在哪里添加。

2个回答

0

你需要在两个if语句后添加return语句,以防它们都为false:

            itemBuilder: (context, int currentIdx){
              if (currentIdx == 0) {
                return _buildTagPage();
              } 
              else if (slideList.length >= currentIdx){
                bool active = currentIdx == currentPage;
                return _buildStoryPage(slideList[currentIdx - 1], active);
              }

              return [some_widget]; // <---- here
            }

好的。根据您的使用情况,您可能只需返回Container即可。 - Derek Fredrickson

0

这里的问题在于 if-else if 的组合不是穷尽的,这意味着可能存在情况,既不满足任何条件,因此也不执行任何代码块。

然而,itemBuilder 指定了回调函数需要返回一个 Widget。因此,您会看到错误。

要解决这个问题,您可以添加一个 else 语句,使 if-else 组合变得穷尽,并从两个代码块中返回;或者您可以只在最后添加一个 return,如果之前没有返回任何内容,则始终会到达该语句;

    controller: ctrl,
    itemCount: slideList.length + 1,
    itemBuilder: (context, int currentIdx){
      if (currentIdx == 0) {
        return _buildTagPage();
      } else if (slideList.length >= currentIdx) {
        bool active = currentIdx == currentPage;
        return _buildStoryPage(slideList[currentIdx - 1], active);
      }

      return Text('No slide availabe.');
    }
);

正如您所看到的,我在结尾处添加了一个返回语句,它将向用户显示一条消息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接