Firebase data checkbox in Flutter

Asked

Viewed 548 times

0

I created a method that returns data from Firebase and creates a checklist containing the name.

The problem is, when I select a checkbox, it selects all of them. What I did was extract Firebase (from the same document that returns the name), an "isSelected" as a bool. It then pulls the document value and, when selecting the checkbox, enters the selected user document and updates the value in Firebase.

How to resolve this without using the check-box bool in Firebase?

Another thing, when you add the "post", I want you to take the UID of the selected users and create a document in Firebase with an array containing the uid of the selected users. How I will get the selected user’s UID?

Like, I know how to add the data and etc in Firebase, but I don’t know how to get the UID’s only from the selected users and create an array containing it...

In short: I want to create a checkbox list with the names of the users (this is already done in the code below), with a checkbox value for each one (selected or not selected - because the variable is declared and used, when selecting a user selects all boxes of all items).

And I want that when you enter it into Firebase, it takes the UID of the selected users (only the selected ones) and creates a field in the document called "uids" containing the users' UID.

Here’s the code I created to create the checkbox with Firebase data:

Widget _sendFor() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          'Send for',
          style: kLabelStyle,
        ),
        Container(
          alignment: Alignment.centerLeft,
          decoration: BoxDecoration(color: Colors.transparent),
          child: new StreamBuilder(
            stream: Firestore.instance
                .collection('users')
                .document(_idUsuarioLogado)
                .collection("friends")
                .snapshots(),
            builder:
                (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
              if (!snapshot.hasData) return new Text('Loading...');
              return new ListView(
                shrinkWrap: true,
                children: snapshot.data.documents.map((document) {
                  //Dgir130wejV0zDERzUgNqr1ItFN2
                  return new CheckboxListTile(
                    title: Text(
                      document["name"],
                      style: TextStyle(color: Colors.white),
                    ),
                    value: _valueCheckbox,
                    onChanged: (bool newValue) {
                      Map<String, dynamic> dadosUpdate = {
                        "isSelected": _valueCheckbox,
                      };
                      setState(() {
                        Firestore.instance
                            .collection('users')
                            .document(document["uid"])
                            .updateData(dadosUpdate);
                        _valueCheckbox = newValue;
                        print(newValue);
                      });
                    },
                  );
                }).toList(),
              );
            },
          ),
        )
      ],
    );
  }
  • Your question is confused, try to elaborate on it please! From what I understand, you want to create a list with the name of the users returned from firebase and then at the time you save, create a document with only the code of those users you selected? That’s right? Edith your question right there to make it clear.

  • 1

    I want to create a checkbox list containing the name returning from Firebase. I’ve already done this, but the problem is that when I select a checkbox all ps items are selected. I would also like to create an array with the user Uids selected to add in Firebase, but how do I do that? I edited the post

  • I get your point now, as soon as I have some free time, I build an answer to your problem!

  • No problem, buddy. Thanks!

1 answer

0


I created a quick example on dartpad for you to understand how your scheme should work, if you cannot understand, then I better implement my answer based on the example given in your question (What have you tried so far).

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

/* Classe para fazer o controle de cada registro chego do firebase */
class Item{
  Item({this.nome, this.checked = false});
  String nome;
  bool checked;
}

class MyApp extends StatelessWidget {

  /* Uma lista que você irá implementar com os dados dos nomes vindo do firebase 
    Alimente ela dentro do seu StreamBuilder
  */
  final List<Item> itens = [
    Item(nome: "Matheus"), 
    Item(nome: "Júlio"), 
    Item(nome: "Caio")];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: ListView.builder(
          itemCount: itens.length,
          itemBuilder: (_, int index){
            return ItemLista(item: itens[index]);
          },
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.save),
          onPressed: salvar,
        )
      ),
    );
  }

  /* Aqui é como você vai pegar os registros selecionados apenas */
  void salvar(){
    List<Item> itensMarcados = List.from(itens.where((item) => item.checked));

    itensMarcados.forEach((item){
      print(item.nome);
    });
  }
}


/* Criei aqui um widget que irá controlar o próprio estado */

class ItemLista extends StatefulWidget {
  const ItemLista({ Key key, this.item }) : super(key: key);

  final Item item;

  @override
  _ItemListaState createState() => _ItemListaState();
}

class _ItemListaState extends State<ItemLista> {

  @override
  Widget build(BuildContext context) {
    return CheckboxListTile(
      title: Text(widget.item.nome),
      value: widget.item.checked,
      onChanged: (bool value){
        setState((){
          widget.item.checked = value;
        });
      },
    );
  }
}
  • I’ll try here buddy, thank you very much!

  • Matheus, I’ve stayed so far and I haven’t gotten kkkk If you can help me, I’ll be grateful

  • Friend, it seems that worked, I pulled the data and print with the name, checked and uid it shows in debug. I will try to insert now. Look at the code, this is how msm? https://pastebin.com/c18iMaSA

  • That’s right, this way it is organized and functional! Just now you apply your data saving scheme, understood right.

  • 1

    It worked well to save the data in Firebase. Look what I did, I created another list that gets uid only from the selected users and I put it inside the foreach, dps pass this list on the map that adds in Firebase https://pastebin.com/Ew5yz3A

  • 1

    Thank you so much for your help!

Show 1 more comment

Browser other questions tagged

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