2

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);
}
UglyBob
  • 247
  • 1
  • 14

1 Answers1

1

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;
  }
}
Ilya Sulimanov
  • 7,636
  • 6
  • 47
  • 68