Ruchira Swarnapriya
Ruchira Swarnapriya

Reputation: 1025

Flutter SnackBar not showing

I have implemented a function to form submitting.I want to have SnackBar Alert to after submitted. I have tried but it doesn't work.After I added SnackBar routing also doesn't work.

addTicket() async {
if (_formKey.currentState.validate()) {
  _formKey.currentState.save();

  try{
    DocumentReference ref = await db.collection('CostalLineTicketDetails').
    document(ticketCato).collection("Tickets").add(
        {
          'startStation':startStation,
          'endStation':endStation,
          'price':price,
          'ticketType':ticketCato,
          'contactNo':contactNo,
          'dateTime':dateTime,
        });
    setState(() => id = ref.documentID);
    Navigator.push(context, new MaterialPageRoute(builder: (context) => CostalLine()));

    Scaffold.of(context).showSnackBar(SnackBar(content: Text('Ticket Added Sucessfully')));

  }catch(e){
    print(e);
  }
}

} }

Upvotes: 4

Views: 13434

Answers (3)

Ravinder Kumar
Ravinder Kumar

Reputation: 8010

  1. You cannot show showSnackBar on same page after going to another screen.
  2. You can declare _scaffoldKey and pass it to Scaffold like this
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

Scaffold(
      key: _scaffoldKey,

then open snackbar like this

_scaffoldKey.currentState.showSnackBar(SnackBar(
        content: Text(
         'Welcome',
        ),
        duration: Duration(seconds: 2),
      ));

Output:

enter image description here


Edit

You can also use flash where you don't need to pass _scaffoldKey every time.

example:

   void _showBasicsFlash({
    Duration? duration,
    flashStyle = FlashBehavior.floating,
  }) {
    showFlash(
      context: context,
      duration: duration,
      builder: (context, controller) {
        return Flash(
          controller: controller,
          behavior: flashStyle,
          position: FlashPosition.bottom,
          boxShadows: kElevationToShadow[4],
          horizontalDismissDirection: HorizontalDismissDirection.horizontal,
          child: FlashBar(
            content: Text('This is a basic flash'),
          ),
        );
      },
    );
  }

Upvotes: 17

Asim Khan
Asim Khan

Reputation: 584

Define this code in any of the generalized dart file, and you can call this function at any place and will display a generic type scaffold.

import 'package:flutter/material.dart';

void showWarningSnackBar(BuildContext context, String message) {
// Find the Scaffold in the widget tree and use it to show a SnackBar.
  ScaffoldFeatureController<Widget, dynamic> _scaffold;

  // Find the Scaffold in the widget tree and use it to show a SnackBar.
  _scaffold = Scaffold.of(context).showSnackBar(SnackBar(
    content: InkWell(
      onTap: () {
        _scaffold.close();
      },
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          AppImage.asset(
              assetName: YOUR_IMAGE_NAME,
              fit: BoxFit.contain,
              width: 20,
              color: COLOR),
          const SizedBox(
            width: 10,
          ),
          Text(
            '$message',
            maxLines: 2,
          ),
        ],
      ),
    ),
    duration: const Duration(seconds: 10),
    backgroundColor: COLOR,
  ));
}

Upvotes: 0

Jay Gadariya
Jay Gadariya

Reputation: 1951

try this,

addTicket() async {
if (_formKey.currentState.validate()) {
  _formKey.currentState.save();

  try{
    DocumentReference ref = await 
    db.collection('CostalLineTicketDetails').
    document(ticketCato).collection("Tickets").add(
        {
          'startStation':startStation,
          'endStation':endStation,
          'price':price,
          'ticketType':ticketCato,
          'contactNo':contactNo,
          'dateTime':dateTime,
        });
    setState(() => id = ref.documentID);
   // Navigator.push(context, new MaterialPageRoute(builder: (context) => CostalLine()));

    Scaffold.of(context).showSnackBar(SnackBar(content: 
    Text('Ticket Added Sucessfully')));

  }catch(e){
    print(e);
   }
   }
   }
   } 

Upvotes: 1

Related Questions