Reputation: 67
I am using a stateful widget and have to declare final variables to receive data from another page. However one of the int variables I have declared has to be changed on that same page again so I removed the Final and the code is working fine but it is warning me that:
"info: This class (or a class which this class inherits from) is marked as '@immutable', but one or more of its instance fields are not final".
I need to send my count value from a different page
Navigator.of(context)
.push(MaterialPageRoute(builder: (BuildContext context) {
return EditScheduleScreen(
count: widget.count + 1,
);
}));
But this count value is updated again in the page I send it to:
widget.count--;
Therefore I have to state the int value without final :
class EditScheduleScreen extends StatefulWidget {
int count;
EditScheduleScreen({
Key key,
this.count,
}) : super(key: key);
@override
_EditScheduleScreenState createState() => _EditScheduleScreenState();
}
Which gives me the warning.
Is this something I should be worried about or is there a way I change the value of this int with keeping it Final (as it needs to be received from different pages)?
Upvotes: 0
Views: 696
Reputation: 1397
usually, if you are going to change value of a variable... it is best to place it inside the State. however, if you are passing the value as a parameter, you can declare a separate variable in the State object then initialize it in the initState() method
Upvotes: 0
Reputation: 390
I am using a stateful widget and have to declare final variables to receive data from another page. However one of the int variable I have declared has to be changed on that same page again so I removed the Final and the code is working fine but it is warning me that.
It won't break your code but still, it's better not to avoid the warnings as much as possible. You can assign the value of count
to a new variable inside the state class and simply make the count
final or const whatever suits you.
So the advantages of doing things in the following style are that it will remove the warning first of all and you will be able to change the value as well.
import 'package:flutter/material.dart';
class EditScheduleScreen extends StatefulWidget {
final int count;
EditScheduleScreen({
Key key,
this.count,
}) : super(key: key);
@override
_EditScheduleScreenState createState() => _EditScheduleScreenState();
}
class _EditScheduleScreenState extends State<EditScheduleScreen> {
// Creating a variable to receive the count's value from the stateful class
int stateCount;
@override
void initState() {
super.initState();
// Passing the count's value to stateCount variable
stateCount = widget.count;
}
@override
Widget build(BuildContext context) {
return Center(
child: FlatButton(
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (BuildContext context) {
return EditScheduleScreen(
count: stateCount + 1,
);
}));
},
child: Text("Flat Button")),
);
}
}
Upvotes: 1