How to Update CheckBox and Return Value From Dialog In Flutter

How to Update CheckBox and Return Value From Dialog In Flutter?

If the user needs to have an input where the user can select multiple choices, using Checkbox Widget is the common solution. Flutter has a widget called Checkbox Widget for that purpose. However, in many cases, you may also want to add text or icons to the checkbox.

How to Update CheckBox and Return Value From Dialog In Flutter?

Your dialog needs to be a Stateful Widget. The member variable that tracks the selection state needs to be in the dialog class. You can use a callback to update a member variable in your parent class with the List of selected cities.

Consider a code snippet like the below:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Checkbox Dialog Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Checkbox Dialog Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State {
  bool checkboxValueCity = false;
  List allCities = ['Alpha', 'Beta', 'Gamma'];
  List selectedCities = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) {
              return _MyDialog(
                  cities: allCities,
                  selectedCities: selectedCities,
                  onSelectedCitiesListChanged: (cities) {
                    selectedCities = cities;
                    print(selectedCities);
                  });
            },
          );
        },
      ),
    );
  }
}

class _MyDialog extends StatefulWidget {
  const _MyDialog({
    required this.cities,
    required this.selectedCities,
    required this.onSelectedCitiesListChanged,
  });

  final List cities;
  final List selectedCities;
  final ValueChanged<List> onSelectedCitiesListChanged;

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

class _MyDialogState extends State<_MyDialog> {
  List _tempSelectedCities = [];

  @override
  void initState() {
    _tempSelectedCities = List.of(widget.selectedCities);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                'CITIES',
                style: TextStyle(fontSize: 18.0, color: Colors.black),
                textAlign: TextAlign.center,
              ),
              RaisedButton(
                onPressed: () {
                  widget.onSelectedCitiesListChanged(_tempSelectedCities);
                  Navigator.pop(context);
                },
                color: const Color(0xFFfab82b),
                child: const Text(
                  'Done',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ],
          ),
          Expanded(
            child: ListView.builder(
              itemCount: widget.cities.length,
              itemBuilder: (BuildContext context, int index) {
                final cityName = widget.cities[index];
                return CheckboxListTile(
                  title: Text(cityName),
                  value: _tempSelectedCities.contains(cityName),
                  onChanged: (bool? value) {
                    if (value != null && value) {
                      if (!_tempSelectedCities.contains(cityName)) {
                        setState(() {
                          _tempSelectedCities.add(cityName);
                        });
                      }
                    } else {
                      if (_tempSelectedCities.contains(cityName)) {
                        setState(
                          () {
                            _tempSelectedCities
                                .removeWhere((String city) => city == cityName);
                          },
                        );
                      }
                    }
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

Use StatefulBuilder to update widgets only inside Dialog. StatefulBuilder is best for update subsection of the widget tree where the state is needed. Code Snippet will look like the below:

Output

How to Update CheckBox and Return Value From Dialog In Flutter

Conclusion:

Thanks for reading !!!

In this article, we have been through how to update the checkbox and return value from dialog in flutter?

Keep Learning !!! Keep Fluttering !!!

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *


ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields

✓ Valid number ✕ Invalid number
our share of the limelight

as seen on