Flutter构建多张卡片

问题描述 投票:0回答:1

我有一个函数postList,它从Wordpress生成的json中检索帖子列表。 id变量是页码,因此每次到达底部时,它都会添加一个循环进度条并加载更多值作为卡(customCard函数)。

_getJsonData(url, page) async {
  final response = await http.get("$url?page=$page");
  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return json.decode(response.body);
  } else {
    // If that call was not successful, throw an
     error. throw Exception('Failed to load post');
  }
}

customCard(value) {
  return  new Card(
    child: new Text ("Post ID: $value"),
  );
}

postsList(url, int id) {
  //List cards;
  _getJsonData(url, id).then((val) {
    for (var singlePost in val) {
      String myID = singlePost["id"].toString();
      print ("Post ID: $myID");

      customCard(myID);
    }
  });
}

@override
Widget build(BuildContext context) {
  return new Scaffold(
    appBar: AppBar(
      title: Text("Infinite Posts List"),
    ),
    body: ListView.builder(
      itemCount: items.length + 1,
      itemBuilder: (context, index) {
        if (index == items.length) {
          return _buildProgressIndicator();
        } else {
          return Container(
            child: postsList(postsUrl, index+1),
          );
        }
      },
      controller: _scrollController,
    ),
  );
}

控制台结果如下:

Initializing hot reload...
Syncing files to device Android SDK built for x86...
Reloaded 1 of 507 libraries in 990ms.
I/flutter (13984): Post ID: 169266
I/flutter (13984): Post ID: 169169
I/flutter (13984): Post ID: 169065
I/flutter (13984): Post ID: 169136
I/flutter (13984): Post ID: 169093
I/flutter (13984): Post ID: 150806
I/flutter (13984): Post ID: 168330
I/flutter (13984): Post ID: 169125
I/flutter (13984): Post ID: 168756
I/flutter (13984): Post ID: 169028

它工作并在控制台上打印我每页10个帖子,但问题是输出是一个空的容器。就像从来没有生产customCard。

不知道我是否清楚。

json wordpress flutter
1个回答
0
投票

您没有在postsList函数中返回任何内容。修改你的功能:

Widget customCard(value) {
  return  new Card(
    child: new Text ("Post ID: $value"),
  );
}

Widget postsList(url, int id) {
  //List cards;
  List<Widget> list = [];
  _getJsonData(url, id).then((val) {
    for (var singlePost in val) {
      String myID = singlePost["id"].toString();
      print ("Post ID: $myID");

      list.add(customCard(myID));
    }
    return Column(
      children: list,
      mainAxisSize: MainAxisSize.min,
    );
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.