【问题标题】:How can I print the response data in a List?如何在列表中打印响应数据?
【发布时间】:2021-04-28 06:59:06
【问题描述】:

我正在尝试在列表构建器中列出来自 response.data 的数据,但我无法解析从响应中获取的数据。 这是我要使用的代码:

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

Future getIds() async {
  var response = await Dio().get(
      'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty');
   return response.data;
}



void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
List ids = getIds();
  @override
  Widget build(BuildContext context) {
    getIds();
    return ListView.builder(
      itemCount: ids.length,
        itemBuilder: null);
  }
}

我如何使用 dio 做到这一点?

【问题讨论】:

    标签: list flutter http dio


    【解决方案1】:

    您不能使用无状态小部件来显示来自 API 的数据。您必须使用 statefull 小部件,并在项目构建器中返回一个小部件

    itemBuilder:(BuildContext context, int index) {
      return Text("${ids[index]["yourKey"]}")
     }
    

    并在初始化状态中添加函数

    List ids;
    @override
    void initState() {
      TODO: implement initState
     super.initState();
     ids = getIds();
    

    }

    【讨论】:

    • 但是我如何使用我得到的响应数据?
    【解决方案2】:

    有一些解决方案。

    • FutureBuilder

      FutureBuilder(
      future: getIds(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          List<Map<String, dynamic>> ids =
            snapshot.data;
          return ListView.builder(
        itemCount: ids.length,
          itemBuilder:(BuildContext context, int index) {
            return Text("${ids[index]["yourKey"]}")
         });
        } else if (snapshot.hasError) {
          return snapshot.error;
        } else {
          return Center(
          child: CircularProgressIndicator(),
        );
        }
      })
      
    • 有状态的小部件

      setState(() {
        ids = dataList;
      });
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      相关资源
      最近更新 更多