一尘不染

如何在Flutter中创建Toast?

flutter

我可以在Flutter中创建类似于Toasts的东西吗?只是一个很小的通知窗口,它不直接在用户面前,并且不会锁定或淡化后面的视图?


阅读 326

收藏
2020-08-13

共1个答案

一尘不染

您可以ScaffoldState使用Scaffold.of(context)

然后做类似的事情

Scaffold.of(context).showSnackBar(SnackBar(
      content: Text("Sending Message"),
    ));

小吃店是材料设计中的官方“吐司”。参见https://material.io/design/components/snackbars.html#usage

这是一个完整的示例:

在此处输入图片说明

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

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

class Home extends StatelessWidget {
  const Home({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Snack bar'),
      ),

      /// We use [Builder] here to use a [context] that is a descendant of [Scaffold]
      /// or else [Scaffold.of] will return null
      body: Builder(
        builder: (context) => Center(
              child: RaisedButton(
                child: const Text('Show toast'),
                onPressed: () => _showToast(context),
              ),
            ),
      ),
    );
  }

  void _showToast(BuildContext context) {
    final scaffold = Scaffold.of(context);
    scaffold.showSnackBar(
      SnackBar(
        content: const Text('Added to favorite'),
        action: SnackBarAction(
            label: 'UNDO', onPressed: scaffold.hideCurrentSnackBar),
      ),
    );
  }
}
2020-08-13