jsonflutterdart

How to parse json in flutter Dart


{0: {id: 1, user_id: 1, title: Group A, open: true}, 1: {id: 2, user_id: 1, title: yiuyi, open: false}, pagination: {total: 2, per_page: 10, current_page: 1, last_page: 1, next_page_url: null, prev_page_url: null}}

how can i parse each value in dart


Solution

  • Try below code to parse json data

    Map<int, Map<String, dynamic>> data = {0: {id: 1, user_id: 1, title: Group A, open: true}, 1: {id: 2, user_id: 1, title: yiuyi, open: false}, pagination: {total: 2, per_page: 10, current_page: 1, last_page: 1, next_page_url: null, prev_page_url: null}}
    
      print('data-> 0: ${data[0]}');
      print('data-> 1: ${data[1]}');
    
      Map<String, dynamic> pagination = data['pagination'];
      int totalItems = pagination['total'];
      int currentPage = pagination['current_page'];
    
      print('Total items: $totalItems');
      print('Current page: $currentPage');
    }
    

    for dynamic 0,1,2... take data in forEach loop with if data key is int then get 0,1,2 json data else pagination data.

     data.forEach((key, value) {
        if (key is int) {
          print('Data for key $key:');
          print('id: ${value['id']}');
          print('user_id: ${value['user_id']}');
          print('title: ${value['title']}');
          print('open: ${value['open']}');
        } else if (key == 'pagination') {
          Map<String, dynamic> pagination = value;
          int totalItems = pagination['total'];
          int currentPage = pagination['current_page'];
          print('Pagination:');
          print('Total items: $totalItems');
          print('Current page: $currentPage');
        }