Home > database >  Can I have access to the scafold in a child widget from a parent widget in flutter?
Can I have access to the scafold in a child widget from a parent widget in flutter?

Time:03-10

if i want to use a snack bar inside my custom widget can I do it? does the CustomWidget have access to the scaffold? since a snack bar is supposed to be in the scaffold?

return Scaffold(
  backgroundColor: HexColor("f4f4f4"),
  body: SafeArea(
      child: Column(
    children: [
      CustomAppBar(
        width: width,
        topBarHeight: topBarHeight,
        height: height,
      ),
      CustomWidget(),
      ]))

CodePudding user response:

Yes, you can use it inside your widget like this:

CustomWidget(BuildContext ctx) {
   if(condition) // it can also be a button action or something like that
     ScaffoldMessenger.of(ctx)
       .showSnackBar(
           SnackBar(content: Text(''))); //Replace Text('') with your widget
}

and pass context to your CustomWidget(context).

CodePudding user response:

You can pass the ScaffoldState key to the constructor.

For example:

Create Global ScaffoldState key

final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

here is the full code:

class Test extends StatefulWidget {
  const Test({Key? key}) : super(key: key);

  @override
  TestState createState() => TestState();
}

class _TestState extends State<Test> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      body: GetData(
        scaffoldKey: _scaffoldKey,
      ),
    );
  }
}

child widget:

class GetData extends StatefulWidget {
  const GetData({
    Key? key,
    required this.scaffoldKey,
  }) : super(key: key);

  final GlobalKey<ScaffoldState> scaffoldKey;
  @override
  GetDataState createState() => GetDataState();
}

class _GetDataState extends State<GetData> {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
        onPressed: () {
          widget.scaffoldKey.currentState
              ?.showSnackBar(const SnackBar(content: Text('content')));
        },
        child: Text('Show SnackBar'));
  }
}
  • Related