3

有没有办法将 aSnackBar与 a 一起使用CupertinoPageScaffold

我收到以下错误:

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使用以下方法在子小部件中调用 a :

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);
4

2 回答 2

4

您需要包含 a ScaffoldasCupertinoPageScaffold不是它的子级,然后您需要将调用showSnackBar函数的代码与 of的代码Scaffold分开到一个单独的类中,SnackBarBody因为 aSnackBar和 aScaffold不能从同一个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'),
     ),
   );
  }
}
于 2019-03-27T18:10:55.643 回答
2

Cupertino 小部件应该是特定于 iOS 的,SnackBar用来取代 Android Toasts,但ToastiOS 中没有 Android 等价物,因此您不能将 a 添加SnackBar到 aCupertinoScaffold中,因为它不会遵循 iOS 指南。

一种解决方案是扩展CupertinoScaffold并添加SnackBar代码。

另一个是 Mazin Ibrahim 的答案,请注意不建议嵌套 Scaffolds。

于 2021-06-04T18:05:45.777 回答