dart - 将 SnackBar 与 CupertinoPageScaffold 结合使用

标签 dart flutter flutter-cupertino

有没有办法将 SnackBarCupertinoPageScaffold 一起使用?

我收到以下错误:

Scaffold.of() called with a context that does not contain a Scaffold.
No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of().

使用以下方法在子部件中调用 SnackBar:

final snackBar = SnackBar(
      content: Text('Yay! A SnackBar!'),
      action: SnackBarAction(
      label: 'Undo',
      onPressed: () {
      // Some code to undo the change!
      },
      ),
      );

// Find the Scaffold in the Widget tree and use it to show a SnackBar!
Scaffold.of(context).showSnackBar(snackBar);

最佳答案

您需要包含一个 Scaffold作为CupertinoPageScaffold不是它的子项,那么您需要在调用 showSnackBar 的地方分隔代码来自 Scaffold 的函数进入一个单独的类,这里是 SnackBarBody因为 SnackBar和一个 Scaffold不能从同一个 Build 调用功能。这是一个完整的工作示例:

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

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

class SnackBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
     title: 'SnackBar Demo',
     home: CupertinoPageScaffold(
    child: SnackBarPage(),
       ),
     );
   }
 }

class SnackBarPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
   body: SnackBarBody(),
   );
 }
}

class SnackBarBody extends StatefulWidget {
  SnackBarBody({Key key,}):
      super(key: key);

  @override
  _SnackBarBodyState createState() => new _SnackBarBodyState();
}

class _SnackBarBodyState extends State<SnackBarBody> {

@override
Widget build(BuildContext context) {
  return Center(
    child: RaisedButton(
      onPressed: () {
        final snackBar = SnackBar(content: Text('Yay! A SnackBar!'),action: SnackBarAction(label: 'Undo',
          onPressed: () {
            // Some code to undo the change!
          },
        ),
      );

        // Find the Scaffold in the Widget tree and use it to show a SnackBar!
        Scaffold.of(context).showSnackBar(snackBar);
       },
      child: Text('Show SnackBar'),
     ),
   );
  }
}

关于dart - 将 SnackBar 与 CupertinoPageScaffold 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55382651/

相关文章:

android - 如何分别在android和ios上原生运行flutter应用?

dart - 如何在带有颜色的 Flutter 上设置强制性 DropDownButton?

flutter - 如何将iOS原生框架导入Flutter?

Flutter BottomNavigationBarItem 只接受 Icon 而没有其他小部件?

flutter - Flutter:从另一个小部件更改主题亮度

android - 抽屉上的工具提示

flutter - 如何在 Flutter 中更改 CupertinoDatePicker 的字体大小?

flutter - 如何在 Flutter Cupertino 底部导航栏中导航到同级项

xml - 解析xml并按属性获取

flutter - 未处理的异常 : type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String