Search code examples
flutterflutter-layout

Flutter : No ScaffoldMessenger widget found


I am trying to create a snackbar on the click of a button in flutter, but getting exception that No ScaffoldMessenger widget found. The same code seems to work properly in the Flutter sample mentioned in docs. Am I missing something here? Thanks.

Here's my main.dart file

import 'package:flutter/material.dart';

void main() => runApp(MyAppWidget());

class MyAppWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyAppWidget> {
  final _inputKey = GlobalKey<FormState>();
  final _messangerKey = GlobalKey<ScaffoldMessengerState>();
  String inputText = "";

  String appendString() {
    setState(() {
      inputText += inputText;
    });
    return inputText;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      scaffoldMessengerKey: _messangerKey,
      home: Scaffold(
        appBar: AppBar(
          title: Text("Assignment"),
        ),
        body: Form(
          key: _inputKey,
          child: Column(
            children: [
              TextFormField(
                validator: (inputString) {
                  inputText = inputString;
                  if (inputString.length < 5) {
                    return 'Please enter a longer string';
                  }
                  return null;
                },
              ),
              ElevatedButton(
                onPressed: () {
                  if (_inputKey.currentState.validate()) {
                    ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(content: Text('Processing Data')));
                  }
                },
                child: Text("Enter"),
              ),
              Text(appendString())
            ],
          ),
        ),
      ),
    );
  }
}

Here's the exception I am getting

════════ Exception caught by gesture ═══════════════════════════════════════════
The following assertion was thrown while handling a gesture:
No ScaffoldMessenger widget found.

MyAppWidget widgets require a ScaffoldMessenger widget ancestor.

Handler: "onTap"

#4      _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:991
#3      _MyAppState.build.<anonymous closure>
package:assignment_1/main.dart:48
#2      ScaffoldMessenger.of
package:flutter/…/material/scaffold.dart:224
#1      debugCheckHasScaffoldMessenger
package:flutter/…/material/debug.dart:153
#0      debugCheckHasScaffoldMessenger.<anonymous closure>
package:flutter/…/material/debug.dart:142
When the exception was thrown, this was the stack

Typically, the ScaffoldMessenger widget is introduced by the MaterialApp at the top of your application widget tree.

        renderObject: RenderView#a5074
    [root]
The ancestors of this widget were
    state: _MyAppState#a2cb9
Restarted application in 691ms.

════════ Exception caught by gesture ═══════════════════════════════════════════
The following assertion was thrown while handling a gesture:
No ScaffoldMessenger widget found.

MyAppWidget widgets require a ScaffoldMessenger widget ancestor.
The specific widget that could not find a ScaffoldMessenger ancestor was: MyAppWidget


Solution

  • scaffoldMessengerKey.currentState.showSnackBar(mySnackBar); scaffoldMessengerKey.currentState.hideCurrentSnackBar(mySnackBar); scaffoldMessengerKey.currentState.removeCurrentSnackBar(mySnackBar);