Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

non final field in stateless flutter widget

I have a stateless widget and while writing the code I am using a non-final field in the stateless widget and the ide keeps giving me warning that all the fields in stateless widget should be final

But I don't understand why having a non-final field in stateless widget be a problem.

I think it should be perfectly fine to have non-final field because there could be a field that we don't want to modify later but this field can only be initialized inside the constructor function so, for that you need to use non-final field

example:

class Temp extends StatelessWidget {
  final int a;
  final int b;
  int c;
  temp({this.a, this.b}) {
    this.c = this.a + this.b;
  }
  @override
  Widget build(BuildContext context) {}
}

In the above widget, I can't make c as final because it is initialized inside the constructor function even though I have no plans to change the c variable in the future.

If having a non-final field in a Stateless widget is not a good Idea then How to handle the above situation.

Note: I cannot use the Constructor() : [initialization] {} because the initialization can involve the function or loops

like image 428
rahul Kushwaha Avatar asked Nov 16 '22 16:11

rahul Kushwaha


1 Answers

StatelessWidget class A widget that does not require mutable state, so the class is marked as @immutable, Dart language do the best to fix your errors, so "final" keyword will just warn you about that but will not stop the compiling, you can use your code normally without final keyword if you are sure it will initialized one time and not change again at run-time ..

and this is the main reason to have 2 keywords (final, const) for define constants in Dart language

Both final and const prevent a variable from being reassigned.

const value must be known at compile-time, const birth = "2020/02/09". Can't be changed after initialized

final value must be known at run-time, final birth = getBirthFromDB(). Can't be changed after initialized

like image 88
Ayman Al Ahnomi Avatar answered Jan 12 '23 20:01

Ayman Al Ahnomi