Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Stateless widget called ToggleButtonsList and one of my instance fields, isSelectedType, is not set to final. This is the warning I am receiving because of this:

"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: ToggleButtonsList.isSelectedType"

Here is a portion of my code:

class ToggleButtonsList extends StatefulWidget {
  ToggleButtonsList({this.type, this.stringList});

  final String type;
  final List<String> stringList;
  List<bool> isSelectedType = [];

  @override
  _ToggleButtonsListState createState() => _ToggleButtonsListState();
}

class _ToggleButtonsListState extends State<ToggleButtonsList> {
  @override
  Widget build(BuildContext context) {
   
   
  }
}

My question: I thought instance fields needed to be set to final only for Stateless widgets, NOT Stateful Widgets. Is this true? Is this a warning I should worry about since I'm not using a StatelessWidget or can I ignore it? My app seems to be working perfectly fine when I ignore the warning.

Reading the "or a class that this class inherits from" part of the warning made me try searching my project for any StatelessWidgets this class may inherit from and the only StatelessWidget I have in my project is from my main.dart :

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
          primaryColor: Colors.blueGrey,
          scaffoldBackgroundColor: Colors.blueGrey),
      home: PriceScreen(),
    );
  }
}

Changing my MyApp class to a StatefulWidget didn't get rid of the warning.

like image 501
London Tran Avatar asked Feb 06 '26 05:02

London Tran


1 Answers

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) {
   
   
  }
}
like image 178
Esen Mehmet Avatar answered Feb 08 '26 22:02

Esen Mehmet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!