Flutter / Changing a Dropdown List after pressing a button

Asked

Viewed 328 times

0

Good afternoon/night,

I’m developing an application where on one of the screens I want to make a "chat" equal to Whatsapp. In terms of functionality, my chat differs from Whatsapp for being totally offline and instead of the user having a "Textfild" to type and send messages, I made a "Dropdown" for him to choose a possible answer and send.

But by clicking the send button, in addition to sending the message, I want to change this dropdown, IE, I would like to change the 'List' of this dropdown to a new and give new response options.

Follows my code:

_enviarMensagem(
      ){
    if(valueChoose != null){
      print(valueChoose);
      listaMensagens.add(valueChoose);
      listItem.remove(listItem[0]);
      listItem.add(listItem2[0]);
      setState(() {
        tamanhoLista = tamanhoLista + 1;
      });
    }
}
List <String>listItem2 = ['item5','item6'];

String valueChoose;

  List <String>listItem = [


'item 1',
'item 2',
'item 3',
'item 4',


 ];

int tamanhoLista = 0;

 List<String> listaMensagens=[];
 
 
  Widget build(BuildContext context) {


var listView = Expanded(child: ListView.builder(
  itemCount: tamanhoLista,
    itemBuilder: (context, indice){

    double larguraContainer = MediaQuery.of(context).size.width * 0.8;

    Color corTexto = Colors.grey;
    Alignment alinhamento = Alignment.centerRight;
    if( indice % 2 == 0){
      alinhamento = Alignment.centerLeft;
      corTexto = Colors.white;
    }

    return Align(
      alignment: alinhamento,
      child: Padding(padding:EdgeInsets.all(8),
      child: Container(
        width: larguraContainer,
        padding: EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: corTexto,
          borderRadius: BorderRadius.all(Radius.circular(30))
        ),
        child: Text(listaMensagens[indice],
        style: TextStyle(
          fontSize: 14,
        ),),
      ),),

    );
    }
));

var caixaMensagem = Container(
  padding: EdgeInsets.all(8),
  child: Row(
    children: [
      Expanded(child: Padding(
        padding: EdgeInsets.only(right: 8),
        child:
          Padding(
            padding: const EdgeInsets.all(5),
            child: Container(
              height: 40,
              padding: EdgeInsets.only(left: 16, right: 16),
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(color: Colors.white, width: 1),
                borderRadius: BorderRadius.circular(30)
              ),
              child: DropdownButton(

                hint: Text('Selecione sua resposta...',
                style: TextStyle(color: Colors.black),),
              dropdownColor: Colors.white,
              icon: Icon(Icons.arrow_drop_down,
              color: Colors.black),
              iconSize: 36,
              isExpanded: true,
              underline: SizedBox(),
              style: TextStyle(
                color: Colors.black,
                fontSize: 16,
              ),
              value: valueChoose,
                onChanged: (newValue){
                setState(() {
                  valueChoose = newValue;
                });
                },
                items: listItem.map<DropdownMenuItem<String>>((String valueItem){
                  return DropdownMenuItem<String>(
                    value: valueItem,
                    child: Text(valueItem),

                  ) ;
                }).toList()
              ),
            ),
          )
      )),
      FloatingActionButton(
        backgroundColor: Colors.white,
        child: Icon(Icons.send, color: Colors.blue,),
        mini: true,
        onPressed: _enviarMensagem,
      )
    ],
  ),
);

To illustrate how my code works in practice:

inserir a descrição da imagem aqui

so far is perfect, but when I put the following command lines inside _send message, everything starts to go wrong:

   listItem.remove(listItem[0]);
      listItem.add(listItem2[0]);

In my view, they serve to remove the first item from the list and then add the first item of listItem2, all after sending the message, but look what happens when trying to select an item that I will delete after sending...

inserir a descrição da imagem aqui

And exactly the same error happens if I try to send the new item I added:

inserir a descrição da imagem aqui

ERROR:

There should be exactly one item with [DropdownButton]'s value: item5. 
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 834 pos 15: 'items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1'

From now on, I’m grateful for all the answers and help attempts. That’s all I need to finish my APP.

1 answer

1


I believe the error happens for the following reason. Dropdownbutton value is set to be the valueChoose variable. So far so good because it starts with null value. If it is not null, its value must exist within the list that is populating Dropdownbutton. It turns out that when you remove the item from the list, the variable is still set with that value, then Dropdownbutton gets value with a value that does not exist in the list.

An attempt would be to leave the valueChoose variable null before removing the item from the list

 if(valueChoose != null){
      print(valueChoose);
      listaMensagens.add(valueChoose);

      valueChoose = null; //Faz com que o value do DropDownButton seja null;

      listItem.remove(listItem[0]);
      listItem.add(listItem2[0]);
      setState(() {
        tamanhoLista = tamanhoLista + 1;
      });
    }
  • Perfect! Thank you so much! That’s really it, I was cracking my head on this! Now it works perfectly! Thank you very much!

Browser other questions tagged

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