-1

Hi I am trying to create a stateful widget that accepts some required arguements and some optional ones. The optional ones will have a set default value if nothing has been passed. I have applied the same process as you would for achieving this in a general class or function but for some reason it does not like it when using it within the stateful widget. Why is this and is there a way to get this working?

Currently getting this from VS code linting:

This class (or a class that this class inherits from) is marked as '@immutable', but one or more of its instance fields aren't final: Example.inActivedartmust_be_immutable

This is my code:

class Example extends StatefulWidget {
  Example({super.key, required this.name, required this.age, inActive = false});

  final String name;
  final int age;
  bool? inActive;

  @override
  State<Example> createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Thank you appreciate your time and effort, with my query.

RishV
  • 17
  • 3
  • Widgets should be immutable. If their parameters change, then they should be rebuilt with the new parameters. If you need mutable state, then place it in your state class. – offworldwelcome Aug 16 '23 at 15:15

1 Answers1

2

Just make the inActive field final.

class Example extends StatefulWidget {
      Example({super.key, required this.name, required this.age, this.inActive = false});

      final String name;
      final int age;
      final bool inActive;
      ....
S. M. JAHANGIR
  • 4,324
  • 1
  • 10
  • 30