簡體   English   中英

ListView.builder 不顯示 JSON 響應數據

[英]ListView.builder not showing JSON response data

["

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);

}

模型期望數據沒有“email_clinica”。 將其標記為可選。

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

在這里,我顯示了對帖子列表的簡單獲取並將它們轉換為列表並在ListView.builder中顯示

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;
    }
  }

帖子型號:

// 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'];
    }
  }
}

我的帖子控制器(因為我使用 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:

                  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