6

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

rahul Kushwaha
  • 2,395
  • 7
  • 32
  • 64

2 Answers2

1

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

-1

You can use initialization even for function invocation.

here is an example:-

class SumWidget extends StatelessWidget {
  final int sum;

  static getSum(List<int> items) {
    int perm = 0;
    for (var value in items) {
      perm += value;
    }
    return perm;
  }

  SumWidget(List<int> roles) : this.sum = getSum(roles);

  @override
  Widget build(BuildContext context) {}
}

but function must be static because The instance member can't be accessed in an initializer.

Ravi Sevta
  • 2,817
  • 21
  • 37