dimanche 5 juin 2022

Flutter - How to implement multiple checkboxes with a "SelectAll"?

Minimal Reproducible Code:

import 'package:flutter/material.dart';


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

  @override
  State<Test> createState() => _TestState();
}

class _TestState extends State<Test> {
  bool isSelectAll = false;
  //bool isChecked = false;

  List<bool> isCheckedList = List.generate(10, (index) => false);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Checkbox(
                value: isSelectAll,
                onChanged: (checked) {
                  setState(
                    () {
                      isSelectAll = checked!;
                    },
                  );
                }),
            Container(
              child: ListView.builder(
                shrinkWrap: true,
                itemBuilder: ((context, index) {
                  return ExpansionTile(
                    title: const Text('sample'),
                    leading: Checkbox(
                        value: isCheckedList[index],
                        onChanged: (checked) {
                          setState(
                            () {
                              // if (isSelectAll == true) {
                              //   checked = true;
                              // }
                              isCheckedList[index] =
                                  (isSelectAll == true) ? true : checked!;
                              //_title = _getTitle();
                            },
                          );
                        }),
                  );
                }),
                itemCount: 10,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Selecting the top checkbox should select all the checkboxes. How do I achieve this?




Aucun commentaire:

Enregistrer un commentaire