Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This class inherits from a class marked as @immutable, and therefore should be immutable (all instance fields must be final)

Getting the below issue, and not able to solve it, Can anyone help me in solving this.

This class inherits from a class marked as @immutable, and therefore should be immutable (all instance fields must be final). dart(must_be_immutable)

Click the image here

Thanks.

like image 990
Sai Sushmitha Avatar asked Feb 15 '19 10:02

Sai Sushmitha


5 Answers

This issue occurs when all the class variables are not declared as final. You can either make them final or for ignoring this warning you can add the following comment above the class declaration:

//ignore: must_be_immutable
like image 185
Saheb Singh Avatar answered Nov 17 '22 14:11

Saheb Singh


All fields in a class extending StatelessWidget should be final.

From the documentations.

StatelessWidget class. A widget that does not require mutable state.

https://api.flutter.dev/flutter/widgets/StatelessWidget-class.html

like image 29
Sumit Vairagar Avatar answered Nov 17 '22 13:11

Sumit Vairagar


Make sure that all your instances variable in class are marked as final and the object is also marked as final.

In class

class Items {
  final String title;
  final String author;
  final String event;
  final String img;
  Items({this.title, this.author, this.event, this.img});
}

Inside widget that you in,

 final Items item2 = new Items(
    title: "Country",
    author: "Balaji",
    event: "4 Items",
    img: "assets/panda.png",
  );
like image 13
Balaji A Avatar answered Nov 17 '22 14:11

Balaji A


Use That way

   class Frog extends StatelessWidget {
      const Frog({
      Key key,
      this.color = const Color(0xFF2DBD3A),
      this.child,
   }) : super(key: key);

  final Color color;
  final Widget child;

  @override
  Widget build(BuildContext context) {
    return Container(color: color, child: child);
  }
}
like image 3
Abir Ahsan Avatar answered Nov 17 '22 13:11

Abir Ahsan


From flutter doc:

The following is a skeleton of a stateless widget subclass called GreenFrog. Normally, widgets have more constructor arguments, each of which corresponds to a final property.

Just like this

class IconContainer extends StatelessWidget {
final double size;
final Color color;
final IconData icon;
IconContainer(this.icon, {this.color=Colors.white, this.size=32});
Widget build(BuildContext context) {
 //TODO...
}
like image 2
LanMegumi Avatar answered Nov 17 '22 14:11

LanMegumi