skip to Main Content

How do I set the height of SnackBar in Flutter?

I have this code from flutter documentation:

import 'package:flutter/material.dart';

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

class SnackBarDemo extends StatelessWidget {
  const SnackBarDemo({super.key});

  @override
  Widget build(BuildContext context) {
  return MaterialApp(
  title: 'SnackBar Demo',
  home: Scaffold(
    appBar: AppBar(
      title: const Text('SnackBar Demo'),
    ),
    body: const SnackBarPage(),
   ),
  );
 }
}

class SnackBarPage extends StatelessWidget {
  const SnackBarPage({super.key});

 @override
 Widget build(BuildContext context) {
   return Center(
     child: ElevatedButton(
      onPressed: () {
      final snackBar = SnackBar(
        content: const Text('Yay! A SnackBar!'),
        action: SnackBarAction(
          label: 'Action name',
          onPressed: () {
            // Some code to undo the change.
          },
        ),
      );

      // Find the ScaffoldMessenger in the widget tree
      // and use it to show a SnackBar.
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    },
    child: const Text('Show SnackBar'),
   ),
  );
 }
}

And this is the result:

enter image description here

How do I prevent the snack bar to be that big?
I want the text and the action to be on the same line.

Thanks

2

Answers


  1. You can put that button in content, like this:

    onPressed: () {
        final snackBar = SnackBar(
            content: Row(
                children: [
                  Expanded(
                    child: Text('Yay! A SnackBar!'),
                  ),
                  TextButton(
                     onPressed: () {
                        
                        if (mounted) { // <==== add this for hide snackBar
                           ScaffoldMessenger.of(context).hideCurrentSnackBar();     
                        }
    
                        // Some code to undo the change.
                     },
                     child: Text(
                       'Action name',
                       style: TextStyle(color: Theme.of(context).primaryColor),
                     ),
                   )
                ],
              ),
          );
    
        if (mounted) {
           ScaffoldMessenger.of(context).showSnackBar(snackBar);     
        }
    }
    

    enter image description here

    Login or Signup to reply.
  2. This is automatic. If there is enough space for both message and action items, it will be shown on same line.

    You can try changing the padding of Snackbar. You can try making it float but overall, it is there for responsiveness.

    Here is how the framework calculates if items should be placed in single row or across multiple rows.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search