Search code examples
flutterimmutabilityfinalstatelesswidget

How to initialize final member with other final member in StatelessWidget subclass?


I have a simple StatelessWidget that creates a new StatefulWidget in its constructor. The problem is that to create that widget, another object needs to be created first. And then when I pass it to the constructor, I get the error

error: Only static members can be accessed in initializers.

I have made a small example below, in this case it is the member 'a' that can not be passed to B's constructor. How to solve this? Do I have to make a StatefulWidget instead even though it can be immutable?

import 'package:flutter/material.dart';

class Test extends StatelessWidget {
  final A a;
  final B b;

  Test() : a = new A(), b = new B(a), super();

  @override
  Widget build(BuildContext context) {
    return null;
  }
}

class A {

}

class B {
  B(A a);
}

Solution

  • Not sure about posibility to achive it by initializer but at least you can do the same via Factory method

    class Test extends StatelessWidget {
      final A a;
      final B b;
    
      Test._(this.a, this.b);
    
      factory Test.create() {
        final a = new A();
        final b = B(a);
        return Test._(a, b);
      }
    
      @override
      Widget build(BuildContext context) {
        return null;
      }
    }