Flutter Dart -> Capturing data from a class that receives json

Asked

Viewed 670 times

-1

Good guys? I’m a beginner in flutter, and I’m working on a ready-made template. In this template I have the class Category.Dart that receives the json values of service.Dart and so far everything is ok. What I need to do is call the Category class data into the Appdata class in the data.Dart file, thus replacing the fixed sample data with the dynamic data.

Service.Dart

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:../src/model/category.dart';


class Connection {

  static const ROOT = 'http://localhost/get_category.php';
  static const _GET_ALL_ACTION = 'GET_ALL';
  static const _ADD_CAT_ACTION = 'ADD_CAT';
  static const _UPDATE_CAT_ACTION = 'UPDATE_CAT';
  static const _DELETE_CAT_ACTION = 'DELETE_CAT';

  static Future<List<Category>> getCategories() async {
    try {
      var map = Map<String, dynamic>();
      map['acao'] = _GET_ALL_ACTION;
      final response = await http.post(ROOT, body: map);
      print('getCategories -> Response :: ${response.body}');

      if(response.statusCode == 200) {
        List<Category> list = parseResponse(response.body);
        return list;
      }else{
        return List<Category>();
      }

    }catch (e) {
        return List<Category>();
    }
  }

  static List<Category> parseResponse(String response) {
    final parsed = json.decode(response).cast<Map<String, dynamic>>();
    return parsed.map<Category>((json) => Category.fromJson(json)).toList();
  }

Category.Dart

class Category{
  String id ;
  String name ;
  String image ;
  String description;
  bool isSelected;
  Category({this.id,this.name,this.image, this.description, this.isSelected});

  factory Category.fromJson(Map<String, dynamic> json) {
    return Category(
    id: json['cod'] as String,
    name: json['nome'] as String,
    image: json['thumb'] as String,
    description: json['descricao'] as String,
    );
  }
}

data.Dart

import 'package:flutter/material.dart';
import 'package:klug_ml/src/model/category.dart';

class AppData {
  static List<Category> categoryList = [
Category() //quero chamar os dados da categoria aqui

//Os dados dinâmicos, devem carregar como o exemplo abaixo.
Category(id:1,name: "Sneakers",image: 'assets/shoe_thumb_2.png',isSelected: true),
Category(id:2,name: "Jacket", image: 'assets/jacket.png'),
Category(id:3,name: "Watch", image: 'assets/watch.png'),

];
}

Call of the Appdata Class in the project.

  Widget _categoryWidget() {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10),
      width: AppTheme.fullWidth(context),
      height: 80,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: AppData.categoryList
            .map(
              (category) => ProductIcon(
                model: category,
                onSelected: (model) {
                  setState(() {
                    AppData.categoryList.forEach((item) {
                      item.isSelected = false;
                    });
                    model.isSelected = true;
                  });
                },
              ),
            )
            .toList(),
      ),
    );
  }

  • Your search code in the API then is all right the way you want it isn’t? The problem you don’t know how to do is just call the method that fetches the data from your API? If this is all within your Appdata class, there needs to be a method that calls the API. It will get the list ready for what is in its implementation. The data from your Category will all come ready. You don’t have to do anything else, you’re just gonna use them. If this is not your question comment here below the part that did not understand so I change or even remove my published answer.

  • That’s exactly it, I’m not sure how to call the data into Static List<Category> categoryList = [ ]

2 answers

0

Following are examples:

void main() {
  String catJson = '{"cod": "1", "nome": "Sneakers","thumb":"assets/shoe_thumb_2.png"}';
  final catMap = jsonDecode(catJson);
  var cat = Category.fromJson(catMap);
  print(cat.name);

  
  Map<String, dynamic> catMap2 = {"cod": "1", "nome": "Sneakers","thumb":"assets/shoe_thumb_5.png"};
  cat = Category.fromJson(catMap2);
  print(cat.image);  
}

The first example is what best suits you if you receive a json

Source: https://dartpad.dev/32e42d2720b04b0bef90c5b38a8266d4

  • Sorry my ignorance, but so far I have not understood. I edited the Post, I also put the code service.dart. Thanks in advance for your contribution.

  • Specify what exactly you don’t understand and what exactly you want to get, from what I understand you’re getting data from a service and want to turn into an object list Category. If that’s the case the other answer has a solution chamadaNaApiRetornandoListaDeMaps would be your getCategories() If you first contact Dart recommend a study on the fundamentals of language.

0

The initial idea of this "serialization" that you mounted on your model is to receive a map of some method and turn it into objects of the class type. Then you will build a Category from a Map.

# Edited

In your class AppData is where the call of the method that returns API data will be made:

void main() {
  final appData = AppData();

  appData.metodoQueBuscaDadosNaApi();
}

class AppData {
  List<Category> categoryList = [];

  Future<void> metodoQueBuscaDadosNaApi() async {
    final categorias = await Connection.getCategories();

    // Preencher a lista de categorias aqui
    categoryList = categorias;

    for(final categoria in categoryList){
      print(categoria.name);
    }
  }
}

class Connection {
  static Future<List<Category>> getCategories() async {
    // Aqui é apenas uma simulação para o POST da requisição
    // esses dados são exemplo apenas
    final categorias = [
      Category(name: "Cat 1"),
      Category(name: "Cat 2"),
      Category(name: "Cat 3"),
    ];

    return categorias;
  }
}

class Category {
  String id;
  String name;
  String image;
  String description;
  bool isSelected;
  Category({
    this.id,
    this.name,
    this.image,
    this.description,
    this.isSelected,
  });

  factory Category.fromJson(Map<String, dynamic> json) {
    return Category(
      id: json['cod'] as String,
      name: json['nome'] as String,
      image: json['thumb'] as String,
      description: json['descricao'] as String,
    );
  }
}

Go to the Dartpad and paste all this code. So you can better understand how it works and even play with the implementation to adjust your need.

  • Sorry my ignorance, but so far I have not understood. I edited the Post, I also put the code service.dart. Thanks in advance for your contribution.

  • So just call? As it is a list, would not have to create a loop? If not how would this call?

  • In the part put as a comment I mentioned that other treatments can be done. Among them can rather use a loop. It is normal programming that part. Your method that searches the Api data has the signature the return of a list. So when you receive this list you can do any treatment you would with any list.

  • Your class Connection has the method that makes the post and this method was declared as static. His call then would be await Connection.getCategories(). I recommend checking the documentation for the http requisition part for a better understanding of the topic. Ready-made examples are excellent for references but are not the best to start in the concept.

  • So that’s all right, what I’m not able to do is pass the list of methodQueBuscaDadosNaApi() to Static List<Category> categoryList = [ ]

  • Take the example that is now in the answer. I refreshed it again to see it working. Paste it into the Dartpad that has the link at the end of the answer and see how it works. Do the tests you think necessary.

  • I couldn’t receive the data, is it because my categoyList variable is of the Static type? Static List<Category> categoryList = []; If I withdraw Static I get Error: Getter not found: 'categoryList'. Appdata.categoryList.foreach(((item)

  • But in the example I posted there is no static, the example didn’t work for you? Why do you want this categoryList to be of the class and not of the class instance? How are you using the Class AppData in your project?

  • See in the edited post, how the Appdata class is called in the project. Grateful

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.