DEV Community

Andrei Lesnitsky
Andrei Lesnitsky

Posted on

2 1

How to access Scaffold methods in stateless Flutter widget

Built with

Git Tutor

GitHub stars
Twitter Follow

Hi đź‘‹

This post will demonstrate how to access ScaffoldState methods (like showSnackBar) in StatelessWidget.

Let's reproduce a simple example demonstrating the issue and create a HomePage stateless widget with a Scaffold

đź“„ lib/main.dart

      );
    }
  }
+ 
+ class HomePage extends StatelessWidget {
+   @override
+   Widget build(BuildContext context) {
+     return Scaffold(
+       appBar: AppBar(
+         title: Text('Stateless Widget Scaffold'),
+       ),
+     );
+   }
+ }

Add a button which will call _showSnackbar when pressed

đź“„ lib/main.dart

        appBar: AppBar(
          title: Text('Stateless Widget Scaffold'),
        ),
+       body: Center(
+         child: FlatButton(
+           child: Text("Show snackbar"),
+           onPressed: _showSnackbar,
+         ),
+       ),
      );
    }
  }

We can use GlobalKey to access ScaffoldState, so let's create one

đź“„ lib/main.dart

  }

  class HomePage extends StatelessWidget {
+   final scaffoldKey = new GlobalKey();
+ 
    @override
    Widget build(BuildContext context) {
      return Scaffold(

pass it to Scaffold

đź“„ lib/main.dart

    @override
    Widget build(BuildContext context) {
      return Scaffold(
+       key: scaffoldKey,
        appBar: AppBar(
          title: Text('Stateless Widget Scaffold'),
        ),

and implement method _showSnackbar

đź“„ lib/main.dart

  class HomePage extends StatelessWidget {
    final scaffoldKey = new GlobalKey();

+   _showSnackbar() {
+     (scaffoldKey.currentState as ScaffoldState).showSnackBar(
+       SnackBar(
+         content: Text("I'm snackbar!"),
+       ),
+     );
+   }
+ 
    @override
    Widget build(BuildContext context) {
      return Scaffold(

That's it! 🎉

Soruce code is available here

Stateless widget scaffold screenshot

Built with

Git Tutor

GitHub stars
Twitter Follow

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay