使用SnackBar和CupertinoPageScaffold

问题描述 投票:0回答:1

有没有办法使用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);
dart flutter flutter-cupertino
1个回答
1
投票

你需要包含一个Scaffold,因为CupertinoPageScaffold不是它的孩子,那么你需要将你称之为showSnackBar函数的代码与Scaffold的代码分离成一个单独的类,这里是SnackBarBody,因为SnackBarScaffold可以'从相同的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'),
     ),
   );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.