flutterflutter-layoutsnackbar

Flutter Snackbar on screen initState


Three Questions:

  1. How to load snackbar in flutter in initState or when app loads the initial screen? I have the code below but it throws an error and doesn't load the screen text.
class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  @override
  void initState() {
    print('In Init State Stream Builder');
  
    _showSnackbar(context);
    
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("Hello World"),
      ),
    );
  }

  void _showSnackbar(BuildContext ctx) {
    Scaffold.of(ctx).showSnackBar(
      SnackBar(
        content: ListTile(
          onTap: () {
            Scaffold.of(ctx).hideCurrentSnackBar();
          },
          subtitle: Text("and i'm a subtitle"),
          trailing: Icon(Icons.check),
        ),
        duration: Duration(
          days: 1,
        ),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        behavior: SnackBarBehavior.floating,
      ),
    );
  }
}

The above code throws an error when loading.


Solution

  • To initialise a Snackbar on initState(), either you put a delay or you can execute a function after the layout is built like this :

    void initState() {
     super.initState();
    WidgetsBinding.instance
        .addPostFrameCallback((_) => _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Your message here..")));
    }