📜  toast flutter - Dart (1)

📅  最后修改于: 2023-12-03 14:48:00.727000             🧑  作者: Mango

Toast Flutter - Dart

Toast is a popular feature in mobile development applications that displays a message or notification to the user in a floating view. In Flutter, the toast function is provided by the Fluttertoast package. This package provides cross-platform APIs for showing Toast.

Installation

To use the Fluttertoast package, you need to add the package to your dependencies in the pubspec.yaml file:

dependencies:
  fluttertoast: ^8.0.8

Then run flutter pub get to download and install the package.

Usage

Here is an example of how you can use the Fluttertoast package to display a simple Toast message:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Toast'),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Fluttertoast.showToast(
              msg: 'Hello, Toast Flutter - Dart!',
              backgroundColor: Colors.grey,
            );
          },
          child: Text('Show Toast Message'),
        ),
      ),
    );
  }
}

In the example above, we first imported the Fluttertoast package, and then created a simple Flutter app using the MaterialApp widget.

In the MyApp class, we created a RaisedButton widget and, in its onPressed property, called the Fluttertoast.showToast method, which displays a Toast message with the text 'Hello, Toast Flutter - Dart!' and grey background color.

Customization

You can customize the Toast message by setting additional properties on the Fluttertoast.showToast method:

void showToast() {
  Fluttertoast.showToast(
    msg: 'Hello, Toast Flutter - Dart!',
    backgroundColor: Colors.grey,
    textColor: Colors.white,
    fontSize: 16.0,
    gravity: ToastGravity.BOTTOM,
    toastLength: Toast.LENGTH_LONG,
  );
}

In the example above, we set the text color to white, font size to 16.0, gravity to ToastGravity.BOTTOM, and length of the Toast message to Toast.LENGTH_LONG.

You can find more customizable properties in the Fluttertoast package.

Conclusion

Toast is an essential component in any mobile application for displaying small information or notification messages to the user. Fluttertoast is an excellent package to implement Toast messages in Flutter app development with ease.