Using optional parameters with a stateful widget class in flutter

47 Views Asked by At

I am trying to create a stateful widget that accepts some required arguments 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.

1

There are 1 best solutions below

0
S. M. JAHANGIR On

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;
      ....