Flutter SnackBar Duration

Change Flutter SnackBar Duration

You can change the duration which a SnackBar is displayed by assigning a required duration to the backgroundColor property of SnackBar, as a Duration object.

Following is a quick code snippet of SnackBar with deep orange background color.

SnackBar(
  content: Text('This is a SnackBar.'),
  duration: Duration(seconds: 2, milliseconds: 500),
)

You can provide the duration with of resolution of days, hours, minutes, seconds, milliseconds and microseconds.

Example: SnackBar Duration

In this example, we shall display a SnackBar on pressing a button. But the duration for which this SnackBar is displayed is controlled by us.

main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<MyApp> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  void _showMessageInScaffold(String message){
    try {
      _scaffoldKey.currentState.showSnackBar(
          SnackBar(
            content: Text(message),
            duration: Duration(seconds: 2, milliseconds: 500),
          )
      );
    } on Exception catch (e, s) {
      print(s);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          title: Text('Flutter Tutorial - googleflutter.com'),
        ),
        body: Center(
            child: RaisedButton(
              textColor: Colors.white,
              color: Colors.blue,
              child: Text('Show SnackBar'),
              onPressed: (){
                _showMessageInScaffold("Hello dear! I'm SnackBar.");
              },
            )
        )
    );
  }
}

Screenshot

Change Flutter SnackBar Duration

You may play with the Duration object and find a correct duration you need for you Android or iPhone.

Summary

In this Flutter Tutorial, we learned how to change the SnackBar duration, with the help of well detailed example Flutter Application.



Desclaimer: We are not affiliated, associated, authorized, endorsed by, or in any way officially connected with the Google, Apple or Flutter, or any of its subsidiaries or its affiliates. The names Google, Apple and Flutter as well as related names, marks, emblems and images are registered trademarks of their respective owners. This site googleflutter.com covers tutorials related to Flutter developed by Google.