flutterstaticstatefuliconbutton

How to use static constructor in stateful widget flutter?


I want to make a clickable iconButton with a different boolean value init.

get the IconButton code :

Row(
 children: [
  CheckIcon(isCheck: true,),
  CheckIcon(isCheck: false,),
  CheckIcon(isCheck: true,),
 ],
),

IconButton Code :

import 'package:flutter/material.dart';

class CheckIcon extends StatefulWidget {
  static bool? isCheck;

  //the error is hire
  const CheckIcon({
    Key? key,
    // I can't initialize the static boolean in constructor
  }) : super(key: key);

  @override
  State<CheckIcon> createState() => _CheckIconState();
}

class _CheckIconState extends State<CheckIcon> {
  @override
  Widget build(BuildContext context) {
    return IconButton(
      splashRadius: 18.0,
      icon: Icon(
        CheckIcon.isCheck!
            ? Icons.check_circle_rounded
            : Icons.check_circle_outline_rounded,
        color: Colors.lightBlue,
        size: 20,
      ),
      onPressed: () {
        setState(() {
          CheckIcon.isCheck = !CheckIcon.isCheck!;
        });
      },
    );
  }
}

How to initialize the static boolean in the constructor stateful widget in flutter?

I hope you have the idea to share, cheers... thanks


Solution

  • Why use static? Static field is shared across all instances, you won't have different states.

    Instead use State field and change it in setState method:

    class CheckIcon extends StatefulWidget {
      final bool isCheck;
    
      const CheckIcon({
        Key? key,
        required this.isCheck, // here we set first value
      }) : super(key: key);
    
      @override
      State<CheckIcon> createState() => _CheckIconState();
    }
    
    class _CheckIconState extends State<CheckIcon> {
      late bool checked = widget.isCheck; // here we set first value and then change it in setState
    
      @override
      Widget build(BuildContext context) {
        return IconButton(
          splashRadius: 18.0,
          icon: Icon(
            checked
                ? Icons.check_circle_rounded
                : Icons.check_circle_outline_rounded,
            color: Colors.lightBlue,
            size: 20,
          ),
          onPressed: () {
            setState(() {
              checked = !checked;
            });
          },
        );
      }
    }