flutter checkbox not working in StatelessWidget

2,233

Solution 1

You need to use a StatefulWidget since you're dealing with changing values. I've provided an example:

class MyAppOne extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyAppOne> {
  bool _myBoolean = false;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Checkbox(
        value: _myBoolean,
        onChanged: (value) {
          setState(() {
            _myBoolean = value; // rebuilds with new value
          });
        },
      ),
    );
  }
}

Solution 2

One way you can achieve this is using the provider package. I tried to create the shortest possible app to show how you can use it. The neat part is that you get to keep your widget stateless.

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:provider/provider.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 Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const Home(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ChangeNotifierProvider(
          create: (_) => CheckboxProvider(),
          child: Consumer<CheckboxProvider>(
            builder: (context, checkboxProvider, _) => Checkbox(
              value: checkboxProvider.isChecked,
              onChanged: (value) {
                checkboxProvider.isChecked = value ?? true;
              },
            ),
          ),
        ),
      ),
    );
  }
}

class CheckboxProvider with ChangeNotifier {
  bool _isChecked = false;

  bool get isChecked => _isChecked;

  set isChecked(bool value) {
    _isChecked = value;
    notifyListeners();
  }
}

It took me quite some time to understand the package but it is very useful and recommended if you want an easier way to manage state in your application. Here's a video from the Flutter team explaining how to use Provider. I would still recommend spending some time looking further into it.

P.S.: Don't forget to change the pubspec.yaml file.

Share:
2,233
Ashique bzq
Author by

Ashique bzq

// Just commented the about me section !

Updated on December 16, 2022

Comments

  • Ashique bzq
    Ashique bzq over 1 year

    Here is my class

    class Home extends StatelessWidget {
    

    and the Checkbox goes here.

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.all(20.0),
                  child: Column(
                    children: <Widget>[
                      TextField(
                          controller: ctrlMotherName,
                          decoration: InputDecoration(
                              labelText: "Name of Mother",
                              border: OutlineInputBorder()
                          )
                      ),
                      SizedBox(height: 10,),
                      Checkbox(
                        value: false,
                        onChanged: (bool val){
    
                        },
                      ),
    

    I can't able to check the checkbox. Same issue found when I use Radiobutton also.