9. Flutter Tutorial for Beginners – Toast Messages

0
445

For toast messages into flutter we are going to use a flutter package called ‘fluttertoast’

To do that follow the instruction.

Step 1. Go to https://pub.dev/packages/fluttertoast#-installing-tab-

Step 2. Open your flutter project, then open pubspec.yml file

Step 3. Add fluttertoast dependencies to your package’s pubspec.yaml file

For example:

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  fluttertoast: ^4.0.1

Step 4. Then click “Packages get”

Step 5. Import it into your dart file.

import 'package:fluttertoast/fluttertoast.dart';

Step 6. Use the following code for your toast messages.

Fluttertoast.showToast(
  msg: "This is your toast message",
  toastLength: Toast.LENGTH_SHORT,
);

You can use more properties of fluttertoast.

Fluttertoast.showToast(
  msg: "This is your toast message",
  toastLength: Toast.LENGTH_SHORT,
  gravity: ToastGravity.CENTER,
  timeInSecForIosWeb: 1,
  backgroundColor: Colors.red,
  textColor: Colors.white,
  fontSize: 16.0,
);

Full example:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  final GlobalKey _scaffoldKey = new GlobalKey();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text('First Page'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Show Toast'),
          onPressed: (){
            Fluttertoast.showToast(
              msg: "This is your toast message",
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.red,
              textColor: Colors.white,
              fontSize: 16.0,
            );
          },
        ),
      ),
    );
  }

}

LEAVE A REPLY

Please enter your comment!
Please enter your name here