Class marked as @immutable, instance field not final using StatefulWidget Class marked as @immutable, instance field not final using StatefulWidget dart dart

Class marked as @immutable, instance field not final using StatefulWidget


I think your mixing State and StatefulWidget class. The Widget class itself is immutable and both StatelessWidget and StatefulWidget extends from Widgetclass.

In your specific case, isSelectedType variable can be final, because final collections can grow or shrink. Only constant collections won't allow you to grow or shrink.

What you need to do:

class ToggleButtonsList extends StatefulWidget {  ToggleButtonsList({this.type, this.stringList});  final String type;  final List<String> stringList;  @override  _ToggleButtonsListState createState() => _ToggleButtonsListState();}class _ToggleButtonsListState extends State<ToggleButtonsList> {  List<bool> isSelectedType = [];  @override  Widget build(BuildContext context) {        }}


Both stateful and stateless widgets need to be immutable.This is enforced by @immutable on Widget class.

See Flutter: Mutable fields in stateless widgets:

Stateless widgets should only have final fields, with no exceptions. Reason: When the parent widget is rebuilt for some reason (screen rotation, animations, scrolling...), the build method of the parent is called, which causes all widgets to be reconstructed.

Classes the extend StatefulWidget must follow the same rule, because those are also reconstructed. Only the State, which can contain mutable fields, is kept during the lifetime of widget in the layout tree.