Flutter 显示 Toast

10 min read

原生

// Step 1
ElevatedButton(
  onPressed: () {
    // Step 2
    var snackBar = SnackBar(content: Text('Hello, I am here'));
    // Step 3
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  },
  child: const Text(
    'Show SnackBar Message',
    style: TextStyle(fontSize: 24),
  ),
),

第三方包

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: ^1.0.2
  fluttertoast: ^8.0.8 # <-- SEE HERE
// Step 2
ElevatedButton(
  onPressed: () {
    // Step 3
    Fluttertoast.showToast(
      msg: "THE toast message",
      toastLength: Toast.LENGTH_SHORT,
      timeInSecForIosWeb: 1,
      backgroundColor: Colors.black,
      textColor: Colors.white,
      fontSize: 16.0,
    );
  },
  child: const Text(
    'Show Toast Message',
    style: TextStyle(fontSize: 24),
  ),
),