简体   繁体   English

ListView.builder 不显示 JSON 响应数据

[英]ListView.builder not showing JSON response data

["

I am trying to get data from an API<\/i>我正在尝试从 API 获取数据<\/b><\/p>

Here you have the API Call:<\/i>这里有 API 调用:<\/b><\/p>

Future<List<Clinica>> fetchClinicas(String idUsuario) async {

  print("USUARIO ID EN FETCHCLINICAS " + idUsuario);
  String url = Constantes().URLProyecto+Constantes().APICarpeta+"get_clinicas.php?usuario="+idUsuario;
  final response = await http.get(Uri.parse(url));
  print("RESPONSE BODY CLINICAS " +response.body.toString());

  return clinicaFromJson(response.body);

}

Data doesn't have "email_clinica" while the model expects that.模型期望数据没有“email_clinica”。 Mark it as optional.将其标记为可选。

...
  String telClinica;
  String? emailClinica;
  String codClinica;
...

Here I'm displaying a simple fetch of a list of posts and converting them to a list and displaying it in a ListView.builder在这里,我显示了对帖子列表的简单获取并将它们转换为列表并在ListView.builder中显示

Api Service: API服务:

static Future<List<PostModel>> fetchPosts({
    required int pageNum,
  }) async {
    var url = Config.apiUrl + Config.postsUrl + pageNum.toString();
// here we're fetching the data from the api
    var response = await http.get(
      Uri.parse(url),
    );

// checking if the call is a success or not
    if (response.statusCode == 200) {
// if yes then get the body from the response and fill the method 
// where we convert the data to an actual list of a model in the 
// PostsModel class
      var jsonString = response.body;

      return postsFromJson(jsonString);
    } else {
      List<PostModel> emptyList = [];
      return emptyList;
    }
  }

PostsModel:帖子型号:

// here we are decoding the body of the response and converting
// to a list of that Model
List<PostModel> postsFromJson(String str) => List<PostModel>.from(
      json.decode(str).map(
            (x) => PostModel.fromJson(x),
          ),
    );

class PostModel {
  int? id;
  String? title;
  dynamic imageUrl;
  String? postedDate;
  String? author;
  String? postContent;

  PostModel({
    required this.id,
    required this.title,
    required this.imageUrl,
    required this.postedDate,
    required this.author,
    required this.postContent,
  });
// here we can find the fromJson method which converts the json into
 // a dart objcet which in my case here is a PostModel
  PostModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    title = json['title']['rendered'];
    imageUrl = json["_embedded"]["wp:featuredmedia"] == null
        ? 'https://pergjigje.net/wp-content/uploads/2021/09/Logo-e-544.png'
        : json["_embedded"]["wp:featuredmedia"][0]["source_url"];
    postedDate = DateFormat('MMMM d, yyyy').format(
      DateTime.parse(
        json['date'],
      ),
    );
    author = json["_embedded"]["author"][0]["name"];
    if (json['content']['rendered'] != null) {
      postContent = json['content']['rendered'];
    }
  }

  PostModel.searchFromJson(
      Map<String, dynamic> json, Map<String, dynamic> searchMediaJson) {
    id = json['id'];
    title = json['title']['rendered'];
    imageUrl = searchMediaJson['source_url'] == null
        ? 'https://via.placeholder.com/300x150.png'
        : json['source_url'];
    postedDate = DateFormat('MMMM d, yyyy').format(
      DateTime.parse(
        json['date'],
      ),
    );
    author = json["_embedded"]["author"][0]["name"];
    if (json['content']['rendered'] != null) {
      postContent = json['content']['rendered'];
    }
  }
}

My postsController(Because I use GetX as a state manager):我的帖子控制器(因为我使用 GetX 作为状态管理器):


// In the controller we call the method which we created in the
 //services and fill a local list with its result
// you can call this in the **initState()** btw or put it in a 
//**FutureBuilder()**
  Future<void> fetchPosts({
    int? pageNum = 0,
  }) async {
    try {
      if (postsList.isEmpty || pageNum == 0) {
        isLoading(true);
        postsList.clear();
      }

      var posts = await ApiServices.fetchPosts(
        pageNum: pageNum!.toInt(),
      );

      if (posts.isNotEmpty) {
        _page += 5;
// Here we are filling the local postsList with the list from the 
//apiService 
        postsList.assignAll(posts);
      }
    } finally {
      isLoading(false);
    }
  }

Listview.builder: Listview.builder:

                  child: ListView.builder(
// Here we are giving the length of the local list we filled in the
 //controller
                    itemCount: postsController.postsList.length,
                    shrinkWrap: true,
                    controller: _postsController.scrollController,
                    itemBuilder: (context, index) {
// And finally we are using the data from the list to display in the screen
                      var data = postsController.postsList[index];
                      if (index == postsController.postsList.length - 1) {
                        return const Padding(
                          padding: EdgeInsets.all(10.0),
                          child: CostumeProgressIndicator(),
                        );
                      } else {
                        return PostItemWidget(
                          data: data,
                          index: index,
                        );
                      }
                    },
                  ),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM