Shazamo Morebucks
Shazamo Morebucks

Reputation: 50

Flutter: How do I show a snackbar through a method

I'd like to have a snackbar in a method so i can change what the text says depending on certain variables.

This is some sample code showing what I have so far, and I've been stuck for ages searching how to move the snackbar to within an onclicked method. I'm for some reason unable to pass the Scaffold Context to a method so the snackbars fail

import 'package:flutter/material.dart';

void main() => runApp(new SnackBarDemo());

class SnackBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        body: new SnackBarPage(),
      ),
    );
  }
}

class SnackBarPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Center(
      child: SnackBarButton(),
    );
  }
}

class SnackBarButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Container(
      child: new RaisedButton(
        onPressed: () {Scaffold.of(context).showSnackBar(SnackBar(content: Text("HERE'S A SNACKBAR")));},
        child: Text("CLICK ON ME FOR A SNACKBAR"),
      ),
    );
  }
}

changing the onpressed to a method like this just fails. I don't understand why:

  void _onPress() {
    Scaffold.of(context).showSnackBar(SnackBar(content: Text("Snackbar from a method")));
  }

Upvotes: 4

Views: 8089

Answers (1)

Jonah Williams
Jonah Williams

Reputation: 21441

The problem is the a StatelessWidget doesn't have a context member - it only has access to the context which is passed in it's build method. In general, if you need access to a context and don't have one you should consider a StatefulWidget. The State object, being persistent, always has access to context.

class SnackBarButton extends StatefulWidget {
  @override
  State createState() => new _SnackBarButtonState();
} 

class _SnackBarButtonState extends State<SnackBarButton> {
  void _onPress() {
    Scaffold.of(context).showSnackBar(...);
  }

  Widget build(BuildContext context) {
    ...
  }
}

You also shouldn't try to save the context object in a StatelessWidget, since the framework doesn't guarantee the saved context is valid when your callback fires.

Upvotes: 6

Related Questions