firebase 我如何添加复选框到列表中的所有值

7lrncoxx  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(127)

我试图添加复选框的列表中的所有值,我需要单独采取的值列表中的每个人在下面的代码中说的onchange(boolval):
无法将类型为“bool?”的值赋给类型为“bool”的变量。请尝试更改变量的类型,或将右侧类型强制转换为“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,
            ),
          ),
        ],
      ),
    );
  }
}
sg3maiej

sg3maiej1#

答案似乎就在这里:

values[key] = val;

错误消息指出您的val的类型为bool?,而您的values[key]的类型为bool
这意味着val可以是truefalsenull,而values[key]只能是truefalse。因此,您需要确定当valnull时要做什么。
一种方法是检查该值,并在这种情况下跳过赋值:

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

相关问题