Home > Back-end >  How to access parent widget inside child widget?
How to access parent widget inside child widget?

Time:10-18

I have a widget:

class MyWidget extends StatelessWidget {
  final Color? color;
  final EdgeInsetsGeometry? padding;
  final Widget child;
  // ... many more properties

  const MyWidget({
    super.key,
    this.color = Colors.blue,
    this.padding = const EdgeInsets.all(4),
    required this.child,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      color: color,
      padding: padding,
      child: child,
    );
  }
}

I also have another widget which wraps the above widget in SliverToBoxAdapter like this:

class MySliverWidget extends MyWidget {
  MySliverWidget({
    super.color,
    super.padding,
    required super.child,
    // ... many more properties
  });

  @override
  Widget build(BuildContext context) {
    // Unable to use "child: super".
    return SliverToBoxAdapter(child: super);
  }
}

But the problem is I am unable to use the parent widget (MyWidget) instance using super inside the child widget (MySliverWidget).

So, the question is how do I access MyWidget instance inside MySliverWidget?


Note:

  1. In MySliverWidget.build() method, I don't want to use child: MyWidget(...) and pass all the parameters to it (which is redundant).

  2. I also don't to simply use SliverToBoxAdapter(child: MyWidget(...)) instead of having a MySliverWidget in the first place.

CodePudding user response:

Maybe like this :

  return SliverToBoxAdapter(child: super.build(context));
  • Related