Flutter use context in super

Viewed 34

I have the following widget

class MyContainer extends Container {
  MyContainer ({
      required String text, 
      Key? key,
  }) : super(
      height: 51,
      decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(20)),
          color: Colors.grey,
      ),
      child: Center(
        child: Text(
          text,
          style: Theme.of(context).textTheme.button?.copyWith(color: UIColors.greyText),
        ),
      ),
      key: key,
  );
}

Now the keen eyed might have noticed that this line style: Theme.of(context).textTheme.button?.copyWith(color: UIColors.greyText), will not work, because we are missing the BuildContext.

My issue is that, as you can see, it's a very simple widget and I would hate it if I had to make it a StatelessWidget just because I want to use Theme.of(context).

Is there any way to make my idea work or will I have to resort to StatelessWidget?

1 Answers

Pass BuildContext as a parameter and name the constructor same as the class name.

class MyContainer extends Container {
  MyContainer({
    required BuildContext context,
      required String text, 
      Key? key,
  }) : super(
      height: 51,
      decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(20)),
          color: Colors.grey,
      ),
      child: Center(
        child: Text(
          text,
          style: Theme.of(context).textTheme.button?.copyWith(color: UIColors.greyText),
        ),
      ),
      key: key,
  );
}
Related