在Flutter中一次显示来自API的问题

时间:2019-10-17 20:46:11

标签: android-studio flutter dart

我想逐一显示我从API中获得的问题。我调用API,解析并存储数据,但是我不知道如何分别显示每个问题。我可以将它们放在列表视图中,仅此而已。我有一个带有FutureBuilder的小部件,该小部件可以调用API,而我目前正尝试将数据发送到另一个小部件,并使用另一个FutureBuilder在此处进行操作(这样,当我遍历问题列表时,我就不会继续调用该API。显示它们)。我有一个整数来跟踪当前位置。我应该怎么做?

部分代码: 在这里,我正在尝试将数据发送到另一个小部件。

FutureBuilder<Reply>(
              future: questions(token, id),
              builder: (context, snapshot) {
                if (snapshot.hasError) {
                  print('Error : ${snapshot.error}'); //show error on the terminal
                  return Text('Error : ${snapshot.error}'); //show error on the app
                } else if (snapshot.hasData) {
                  reply = snapshot.data;
                  return Show_Questions(reply: reply,);
                } else {
                  return Center(child: CircularProgressIndicator()); //else display a loading indicator
                } //loading indicator
              }
          ),

感谢您的帮助。如果需要,我可以发布更多代码。

1 个答案:

答案 0 :(得分:0)

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: new FutureBuilder(
          future: questions(token, id),
          initialData: [],
          builder: (context, snapshot) {
            return createListView(context, snapshot);
          }),
    );

  }

  Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
    var values = snapshot.data;

    return ListView.builder(
      itemCount: values == null ? 0 : values.length,
      itemBuilder: (BuildContext context, int index) {
        return GestureDetector(
          onTap: () {
            setState(() {

            });
          },
          child: Column(
            children: <Widget>[
              new ListTile(
                title: Text(values[index]),
              ),
              Divider(
                height: 2.0,
              ),
            ],
          ),
        );
      },
    );
  }
}

希望能为您提供帮助:)