Home > Net >  How to declare check boxes values to String values and save firestore on flutter?
How to declare check boxes values to String values and save firestore on flutter?

Time:11-07

In my code can select multiple checkboxes, but I want to print the selected checkboxes titles.And also then application run checkboxes are unselecting ( checkboxes values are bool = false)

enter image description here

Ex: Like as this Image I selected dart and java checkboxes so I want to insert those names in the firestore.I have no idea how to equal the check box value to string values. How to insert that values?

code

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class HomePageWidget extends StatefulWidget {
  const HomePageWidget({Key? key}) : super(key: key);

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

class _HomePageWidgetState extends State<HomePageWidget> {
  bool? checkboxListTileValue1;
  bool? checkboxListTileValue2;
  bool? checkboxListTileValue3;
  bool? checkboxListTileValue4;
  bool? checkboxListTileValue5;
  String checkboxListTileValue1 = "c  "
  String checkboxListTileValue2 = "c"
  String checkboxListTileValue3 = "java"
  String checkboxListTileValue4 = "react"
  String checkboxListTileValue5 = "dart"

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text(
          'Page Title',
        ),
        actions: [],
        centerTitle: false,
        elevation: 2,
      ),
      body: SafeArea(
        child: GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: [
              Theme(
                data: ThemeData(
                  unselectedWidgetColor: Color(0xFF95A1AC),
                ),
                child: CheckboxListTile(
                  value: checkboxListTileValue1 ??= false,
                  onChanged: (newValue) async {
                    setState(() => checkboxListTileValue1 = newValue!);
                  },
                  title: Text(
                    'c  ',
                  ),
                  tileColor: Color(0xFFF5F5F5),
                  dense: false,
                  controlAffinity: ListTileControlAffinity.trailing,
                ),
              ),
              Theme(
                data: ThemeData(
                  unselectedWidgetColor: Color(0xFF95A1AC),
                ),
                child: CheckboxListTile(
                  value: checkboxListTileValue2 ??= false,
                  onChanged: (newValue) async {
                    setState(() => checkboxListTileValue2 = newValue!);
                  },
                  title: Text(
                    'c',
                  ),
                  tileColor: Color(0xFFF5F5F5),
                  dense: false,
                  controlAffinity: ListTileControlAffinity.trailing,
                ),
              ),
              Theme(
                data: ThemeData(
                  unselectedWidgetColor: Color(0xFF95A1AC),
                ),
                child: CheckboxListTile(
                  value: checkboxListTileValue3 ??= false,
                  onChanged: (newValue) async {
                    setState(() => checkboxListTileValue3 = newValue!);
                  },
                  title: Text(
                    'java',
                  ),
                  tileColor: Color(0xFFF5F5F5),
                  dense: false,
                  controlAffinity: ListTileControlAffinity.trailing,
                ),
              ),
              Theme(
                data: ThemeData(
                  unselectedWidgetColor: Color(0xFF95A1AC),
                ),
                child: CheckboxListTile(
                  value: checkboxListTileValue4 ??= false,
                  onChanged: (newValue) async {
                    setState(() => checkboxListTileValue4 = newValue!);
                  },
                  title: Text(
                    'react',
                  ),
                  tileColor: Color(0xFFF5F5F5),
                  dense: false,
                  controlAffinity: ListTileControlAffinity.trailing,
                ),
              ),
              Theme(
                data: ThemeData(
                  unselectedWidgetColor: Color(0xFF95A1AC),
                ),
                child: CheckboxListTile(
                  value: checkboxListTileValue5 ??= false,
                  onChanged: (newValue) async {
                    setState(() => checkboxListTileValue5 = newValue!);
                  },
                  title: Text(
                    'dart',
                  ),
                  tileColor: Color(0xFFF5F5F5),
                  dense: false,
                  controlAffinity: ListTileControlAffinity.trailing,
                ),
              ),
              ElevatedButton(onPressed: press(), child: Text('submit'))
            ],
          ),
        ),
      ),
    );
  }

  press() {
    FirebaseFirestore.instance
        .collection("users")
        .doc()
        .set({
      "checkboxes": checkboxListTileValue1   checkboxListTileValue2   checkboxListTileValue3   checkboxListTileValue4   checkboxListTileValue5,
    });
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const HomePageWidget()),
    );
  }
}

errors enter image description here

enter image description here

this

enter image description here

CodePudding user response:

First you need to define class model for your checkbox like this:

class CheckBoxModel {
  final String title;
  final bool value;

  CheckBoxModel({required this.title, required this.value});
}

then use it like this:

class TestingDesign2 extends StatefulWidget {
  const TestingDesign2({super.key});

  @override
  State<TestingDesign2> createState() => _TestingDesign2State();
}

class _TestingDesign2State extends State<TestingDesign2> {
  

  List<CheckBoxModel> checkboxes = [
    CheckBoxModel(title: 'C  ', value: false),
    CheckBoxModel(title: 'java', value: false),
    CheckBoxModel(title: 'C', value: false),
  ];

  @override
  Widget build(BuildContext context) {
    
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: ListView.builder(
              itemBuilder: (context, index) {
                return buildCheckBox(checkboxes[index], index);
              },
              itemCount: checkboxes.length,
            ),
          ),
          ElevatedButton(onPressed: press(), child: Text('submit'))
        ],
      ),
    );
  }

  buildCheckBox(CheckBoxModel checkbox, int index) {
    return Theme(
      data: ThemeData(
        unselectedWidgetColor: Color(0xFF95A1AC),
      ),
      child: CheckboxListTile(
        value: checkbox.value,
        onChanged: (newValue) async {
          setState(() => checkboxes[index] =
              CheckBoxModel(title: checkbox.title, value: newValue!));
        },
        title: Text(
          checkbox.title,
          style: TextStyle(
             fontSize: 12,
          ),
        ),
        tileColor: Colors.transparent,
        dense: false,
        controlAffinity: ListTileControlAffinity.trailing,
      ),
    );
  }

  press() {
    List<CheckBoxModel> checked =
        checkboxes.where((element) => element.value).toList();
    String result = '';
    checked.forEach((element) {
      result = result   element.title;
    });
    FirebaseFirestore.instance.collection("users").doc().set({
      "checkboxes": result,
    });
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const HomePageWidget()),
    );
  }
}
  • Related