Flutter showSnackBar is deprecated

Published May 26, 2021

When i want to show snackbar with Scaffold widget, it showing deprecated. Scaffold.of(context).showSnackBar(snackbar). How could we show snackbar to show simple messages.

'showSnackBar' is deprecated and shouldn't be used. Use ScaffoldMessenger.showSnackBar. This feature was deprecated after v1.23.0-14.0.pre. There will be an other option to show Snackbar that is ScaffoldMessengerState.

 

ScaffoldMessengerState.showSnackBar shows a SnackBar at the bottom of the scaffold.


A scaffold can show at most one snack bar at a time. If this function is called while another snack bar is already visible, the given snack bar will be added to a queue and displayed after the earlier snack bars have closed.

 

To set the duration of the snack bar by duration property.

 

How to hide snack bar in flutter?

To hide snackbar we will use ScaffoldMessengerState.hideCurrentSnackBar() method

 

Let see simple example to show snackbar with ScaffoldMessengerState

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  final _messangerKey = GlobalKey<ScaffoldMessengerState>();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      scaffoldMessengerKey: _messangerKey,
      home: GestureDetector(
        onTap: () {
          
          _messangerKey.currentState.showSnackBar(
            SnackBar(
              duration:Duration(seconds: 2) ,
              content: const Text('A SnackBar has been shown.'),
            ),
          );
          
        },
        
      ),
    );
  }
}

 

Tags: Scaffold, Snackbar, ScaffoldMessengerState, deprecated, showSnackbar

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1993 Views