how could i add checkbox to all the value in a list

55 Views Asked by At

i am trying to add check box to all the values in a list i need to individually take values of every person in the list in below code says in the onchange(bool val):

A value of type 'bool?' can't be assigned to a variable of type 'bool'.⏎Try changing the type of the variable, or casting the right-hand type to 'bool'.

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

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

  @override
  State<TestFile> createState() => _TestFileState();
}

class _TestFileState extends State<TestFile> {
  Map<String, bool> values = {
    'foo': true,
    'bar': false,
  };
  List<dynamic> items = [];

  String? _selectedItem;
  bool _ischecked = false;
  DateTime _selectedDate = DateTime.now();
  List<String> myList = [];
  List<String> checklist = [];
  //!database reference and query
  final auth = FirebaseAuth.instance;
  final ref = FirebaseDatabase.instance.ref('attendance').child('studentlist');

  //!

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.purple,
        bottom: PreferredSize(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                child: Padding(
                  // padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),

                  padding: const EdgeInsets.only(left: 16.0),
                  child: DropdownButton<String>(
                    value: _selectedItem,
                    onChanged: (String? newValue) {
                      setState(() {
                        _selectedItem = newValue;
                      });
                    },
                    items: <String>[
                      'period 1',
                      'period 2',
                      'period 3',
                      'period 4',
                      'period 5',
                      'period 6',
                      'period 7',
                    ].map<DropdownMenuItem<String>>((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                    icon: Icon(Icons.arrow_drop_down),
                    iconSize: 40,
                    underline: Container(),
                    iconEnabledColor: Colors.white, //Icon color
                    style: TextStyle(
                        //te
                        color: Colors.white, //Font color
                        fontSize: 20 //font size on dropdown button
                        ),
                    dropdownColor: Colors.purple,
                  ),
                ),
              ),
              SizedBox(
                width: 100,
              ),
              Container(
                child: Center(
                  child: IconButton(
                    icon: Icon(Icons.calendar_month, color: Colors.white),
                    onPressed: () async {
                      final DateTime? picked = await showDatePicker(
                        context: context,
                        initialDate: _selectedDate,
                        firstDate: DateTime(1900),
                        lastDate: DateTime.now(),
                      );
                      if (picked != null && picked != _selectedDate) {
                        setState(() {
                          _selectedDate = picked;
                        });
                      }
                    },
                  ),
                ),
              ),
              SizedBox(width: 5),
              Text(
                DateFormat('dd/MM/yyyy').format(_selectedDate),
                style: TextStyle(
                    //te
                    color: Colors.white, //Font color
                    fontSize: 20 //font size on dropdown button
                    ),
              ),
            ],
          ),
          preferredSize: Size.fromHeight(30.0),
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: StreamBuilder(
              stream: ref.onValue,
              builder: (context, AsyncSnapshot<DatabaseEvent> snapshot) {
                List<bool> checked = List<bool>.filled(items.length, false);
                if (!snapshot.hasData) {
                  return CircularProgressIndicator();
                } else {
                  Map<dynamic, dynamic> map =
                      snapshot.data!.snapshot.value as dynamic;
                  items.clear();
                  items = map.values.toList();
                  return ListView.builder(
                    itemCount: snapshot.data!.snapshot.children.length,
                    itemBuilder: (context, Index) {
                      return new ListView(
                        children: values.keys.map((String key) {
                          return new CheckboxListTile(
                              title: Text(items[Index]['sname'],
                                  style: TextStyle(
                                      fontSize: 19,
                                      fontWeight: FontWeight.w500)),
                              value: values[key],
                              onChanged: (  val) {
                                setState(() {
                                   values[key] = val;
                                  // if(values!=null){
                                  //   values[key] = val;
                                  // }else{
                                  //   values[key] = false;
                                  // }
                                  
                                });
                              });
                        }).toList(),
                      );
                    },
                  );
                }
              },
            ),
          ),
        ],
      ),
      floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            padding: EdgeInsets.fromLTRB(28, 0, 0, 0),
            child: FloatingActionButton.extended(
              onPressed: () {
                for (int i = 0; i < items.length; i++) {
                  print(items[i]);
                }
                // Add your onPressed code here!
              },
              label: const Text('ADD'),
              icon: const Icon(Icons.add),
              backgroundColor: Colors.purple,
            ),
          ),
        ],
      ),
    );
  }
}
1

There are 1 best solutions below

0
Frank van Puffelen On

If seems like the answer happens here:

values[key] = val;

The error message says that your val is of type bool?, while your values[key] is of type bool.

This means that val can be true, false or null, while values[key] can only be true or false. So you need to determine what you want to do when val is null.

One way to do that is to check for that value, and skip the assignment in that case:

if (val != null) {
  values[key] = val!;
}
else {
  print('val is null, skipping assignment');
}