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

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

我想一一展示我从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
              }
          ),

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

android-studio flutter dart
1个回答
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,
              ),
            ],
          ),
        );
      },
    );
  }
}

希望对您有所帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.