How to compare Map and Json values in flutter?

Asked

Viewed 785 times

2

I need to search inside this Json what I type into TextField

The controller:

TextEditingController searchController = TextEditingController();
String variavel_json = '{"nome":"Marcelo", "email":"[email protected]"}';

The search function:

void printJson() {
  setState(() { 
    Map json = jsonDecode(variavel_json);
    if(json["nome"] == searchController){
      print(json["nome"]);
    }else{
      print("Nenhum nome encontrado");
    }
  });
}

The TextField:

TextField(
  keyboardType: TextInputType.text,
  decoration: InputDecoration(
    labelText: searchText,
    labelStyle: TextStyle(color: Colors.blue),
  ),
  textAlign: TextAlign.center,
  controller: searchController,
),

And the button that calls the controller:

ButtonTheme(
  height: 30.0,
  child: RaisedButton(
    onPressed: printJson,
    shape: new RoundedRectangleBorder(
        borderRadius: new BorderRadius.circular(30.0)),
    child: Text(
      "Printar JSON",
      style: TextStyle(color: Colors.white, fontSize: 30),
    ), //Text
    color: Colors.blue,
  ), //RaisedButton
),

The return I have on the console is always the else. I would like to understand how I could do this research within the Map. I am new to the language.

2 answers

2

I think the problem is here:

if(json["nome"] == searchController){
  print(json["nome"]);
}

You’re comparing an object String (map value) with an object of type TextEditingController, that will never be the same, so always falls in the else.

You need to pick up the value through the property text.

if(json["nome"] == searchController.text){
  print(json["nome"]);
}

A quick and practical example comparing a map value:

import 'dart:convert';

main() {
  final json = '{"nome":"Marcelo", "email":"[email protected]"}';
  print('Json: $json');

  final map = jsonDecode(json);
  print('Map: $map');

  final nomeUm = 'Marcelo';
  if(map['nome'] == nomeUm) {
    print('Nome igual');
  }
}
  • I understand, but in this case you are assigning the nameOne to Marcelo so the comparison will always work. How I would pick up the text the user types to make the comparison ?

  • It will always work because it is an example, if you see there in the answer, a little above, has how you should do if(json["nome"] == searchController.text){. Using the searchController text.

  • Ah yes, but even with this property text the search still falls on else

  • What value is printing on text? Debug and inspect this variable

  • How could I do this debug ? has some tool or something like php with a kind of var_dump($variavel) ?

  • You can use the functions debugPrint or print to simply print the values. Or use your IDE to run in debug mode and be able to inspect the variables. Further information: https://flutter.dev/docs/testing/debugging

  • I managed to find the error here. After printing what was on searchController I noticed an error in the Json syntax. Thanks for the help

  • Just one more question, when I add another user with email name always picks up the last one. Any idea what this might be ?

  • @Marcelol in this case you are architecting your problem wrong, a Map will never allow a key duplicate. Only possible with different Maps or a list of values for the key.

Show 4 more comments

1


Seeking to complement the reply of @Juliohenrique, brought some improvements to its development. How can you come to have other data in this JSON informed, it would be a good thing if you put the data in structured classes and work on it.

Below is an example that can be tested on Dartpad

Create the class that will receive the data of each object of your JSON

class Conta {
    String nome;
    String email;

    Conta({
      this.nome,
      this.email
    });

    factory Conta.fromJson(Map<String, dynamic> json) => Conta(
        nome: json["nome"],
        email: json["email"]
    );
}

To filter the text typed by the user, transform your JSON in a List that will receive objects of the type Conta

  String json = '[{"nome":"Marcelo", "email":"[email protected]"}, {"nome":"Caio", "email":"[email protected]"}, {"nome":"Caio", "email":"[email protected]"}]';
  final jsonMap = jsonDecode(json);

  List<Conta> contas;

  contas = (jsonMap as List).map((item) => Conta.fromJson(item)).toList();

With this you will have a list of all existing accounts in your JSON, to perform the search simply create the search method

  void buscarConta({String nome}){
    List<Conta> contasFiltradas = contas.where((item) => item.nome.toLowerCase()==nome.toLowerCase()).toList();

    for (var x=0; x<contasFiltradas.length; x++){
      print("Registro encontrado");
      print('  Nome filtrado: '+ contasFiltradas[x].nome +'\n  Email Filtrado:'+ contasFiltradas[x].email);
    }
  }

To use the created method do as follows

bucarConta(searchController.text);

The result is only being printed on the screen, but you can modify the method to return an object or more.

Follow the full code:

import 'dart:convert';

void main() {
  String json = '[{"nome":"Marcelo", "email":"[email protected]"}, {"nome":"Caio", "email":"[email protected]"}, {"nome":"Caio", "email":"[email protected]"}]';
  final jsonMap = jsonDecode(json);

  List<Conta> contas;

  contas = (jsonMap as List).map((item) => Conta.fromJson(item)).toList();

  void buscarConta({String nome}){
    List<Conta> contasFiltradas = contas.where((item) => item.nome.toLowerCase()==nome.toLowerCase()).toList();

    for (var x=0; x<contasFiltradas.length; x++){
      print("Registro encontrado");
      print('  Nome filtrado: '+ contasFiltradas[x].nome +'\n  Email Filtrado:'+ contasFiltradas[x].email);
    }
  }

  buscarConta(nome: searchController.Text);
}

class Conta {
    String nome;
    String email;

    Conta({
      this.nome,
      this.email
    });

    factory Conta.fromJson(Map<String, dynamic> json) => Conta(
        nome: json["nome"],
        email: json["email"]
    );
}
  • Sensational guy, thank you so much

Browser other questions tagged

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