Search code examples
androidfluttertoast

Toast appears at the wrong time


I'm testing s new toast for my app (bot_toast) and I need to call it from another file to improve my code, but i cant make it work the right way. I know its something basic but i tried for hours and still cant solve. The problem is: the toast pops up when i run the app, and not when i click the button (that should be the right behaviour).

Heres the code:

main.dart

import 'package:teste_toast/notification.dart';
import 'package:bot_toast/bot_toast.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BotToastInit(
      child: MaterialApp(
        navigatorObservers: [BotToastNavigatorObserver()],
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Toast test'),
          ])),
      floatingActionButton: FloatingActionButton(
        onPressed: ShowToast(context),
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

notification.dart:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

ShowToast(BuildContext context) {
  return BotToast.showText(text: 'toast message');
}

And i'm using this toast: https://pub.dev/packages/bot_toast#Online-Demo


Solution

  • make sure you are calling method in onPressed method like below :

    floatingActionButton: FloatingActionButton(
            onPressed:(){ ShowToast(context),}
            child: Icon(Icons.add),
          ),