flutter - 为什么Navigator.pop无法传递回参数?

标签 flutter dart navigation dialog

我正在启动一个警报对话框,以确认用户保存或清除过滤器的操作,并且我想根据用户的选择返回一个 bool(boolean) 值。我正在尝试通过Navigator.pop()传递它,但始终收到此错误:

The following _TypeError was thrown while handling a gesture:
type 'bool' is not a subtype of type 'AlertDialog' of 'result' 

有人知道为什么会这样吗?这是我的代码。我在将showDialog的结果分配给var shouldClear的onPressed上发生了特定的错误。
import 'package:flutter/material.dart';

class FilterNavbar extends StatelessWidget {

  final VoidCallback clearFilter;

  const FilterNavbar({@required this.clearFilter});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 60,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width * .3,
            child: RaisedButton(
              onPressed: () async {
                var shouldClear = await showDialog<AlertDialog>(
                  context: context,
                  builder: (context) { 
                    return generateDialog(context, attemptSave: false);
                  }
                );

              },
              child: const Text("Clear"),
            ),
          ),
          Container(
            width: MediaQuery.of(context).size.width * .3,
            child: RaisedButton(
              onPressed: () async {
                await showDialog<AlertDialog>(
                  context: context,
                  builder: (context) { 
                    return generateDialog(context, attemptSave: true);
                  }
                );
                Navigator.pop(context, true);
              },
              child: const Text("Save"),            
            ),
          )
        ]
      ),
    );
  }
}

AlertDialog generateDialog(BuildContext context, {bool attemptSave}){

  return AlertDialog(
    title: Center(child: Text("${attemptSave ? "Save": "Clear"} filter?")),
    actions: [
      FlatButton(
        onPressed: () {
          if (attemptSave) {
            Navigator.pop(context, false);
          }
          else {
            Navigator.pop(context, true);
          }
        }, 
        child: Text("${attemptSave ? "Save": "Clear"}")
      )
    ],
  );
}

最佳答案

您可以在下面复制粘贴运行完整代码
请将AlertDialog更改为bool

await showDialog<AlertDialog>


await showDialog<bool>

工作演示

enter image description here

完整的代码
import 'package:flutter/material.dart';

class FilterNavbar extends StatelessWidget {
  final VoidCallback clearFilter;

  const FilterNavbar({@required this.clearFilter});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 60,
      child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Container(
              width: MediaQuery.of(context).size.width * .3,
              child: RaisedButton(
                onPressed: () async {
                  var shouldClear = await showDialog<bool>(
                      context: context,
                      builder: (context) {
                        return generateDialog(context, attemptSave: false);
                      });
                },
                child: const Text("Clear"),
              ),
            ),
            Container(
              width: MediaQuery.of(context).size.width * .3,
              child: RaisedButton(
                onPressed: () async {
                  await showDialog<bool>(
                      context: context,
                      builder: (context) {
                        return generateDialog(context, attemptSave: true);
                      });
                  Navigator.pop(context, true);
                },
                child: const Text("Save"),
              ),
            )
          ]),
    );
  }
}

AlertDialog generateDialog(BuildContext context, {bool attemptSave}) {
  return AlertDialog(
    title: Center(child: Text("${attemptSave ? "Save" : "Clear"} filter?")),
    actions: [
      FlatButton(
          onPressed: () {
            if (attemptSave) {
              Navigator.pop(context, false);
            } else {
              Navigator.pop(context, true);
            }
          },
          child: Text("${attemptSave ? "Save" : "Clear"}"))
    ],
  );
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(
                child: FilterNavbar(
              clearFilter: () {},
            )),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

关于flutter - 为什么Navigator.pop无法传递回参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61239820/

相关文章:

authentication - Flutter:应用生命周期之间的导航问题

entity-framework - 预加载 Entity Framework 导航属性错误

Flutter:在 Web、Android 和 ios 中使用相同的应用程序

php - CSS Bootstrap 响应式菜单差异

flutter - 如何在 Flutter 的 StreamBuilder 中获取文档详细信息

dart - 如何使容器拉伸(stretch)以占据与行相同的高度?

dart - Flutter 根 Column 小部件扩展到整个屏幕,为什么?

dart - Flutter 检查滚动能力

flutter - 如何获取 Flutter/Dart 变量的内存地址?这可能吗?

dart - 可滚动的 flutter 弹出菜单