【问题标题】:Flutter, break out private method to a helper class. Arguments problemFlutter,将私有方法分解为辅助类。参数问题
【发布时间】:2021-12-27 14:52:02
【问题描述】:

我想打破这个方法并在帮助类中公开它,但是在尝试将上下文传递给它时遇到了这个错误?它需要两个必需的上下文和BuildContext,但我不知道如何实现?我得到这个错误。两个上下文参数似乎也有问题:

“需要 2 个位置参数,但找到 0 个。尝试添加缺少的参数”

或者如果我输入第一个上下文是:

“需要 1 个位置参数,但找到 0 个。尝试添加缺少的参数”

私有方法:

_showDialog() {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text('Title'),
        content: Text('Body'),
        actions: <Widget>[
          OutlinedButton(
            child: Text('Close'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}

公共方法(带有两个上下文参数):

class _LegendScreenState extends State<LegendScreen> {
  showDialog(context, BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Title'),
          content: Text('Body'),
          actions: <Widget>[
            OutlinedButton(
              child: Text('Close'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
}

【问题讨论】:

    标签: flutter dart private public


    【解决方案1】:

    问题来了,因为您正在定义已在 material.dart 上定义的 showDialog 方法。它与名称重叠。尝试将帮助类重命名为 appDialog 之类的其他名称并传递 context

      appDialog(BuildContext context) {
        showDialog(
          context: context,
          builder: (BuildContext context) {
    

    更多关于showDialog

    【讨论】:

    • 谢谢Yeasin!有时你可能会对某些事情视而不见:)
    【解决方案2】:

    删除一个上下文参数。你只需要一个。

    showDialog(context, BuildContext context) {
    

    应该是:

    showDialog(BuildContext context) {
    

    【讨论】:

    • 我猜它的上下文是一样的 :) 不幸的是仍然错误:1 预期但找到 0。
    • 嗯,你怎么称呼它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 2012-02-07
    • 2011-08-03
    • 2014-05-23
    • 1970-01-01
    • 2017-05-14
    • 2012-10-01
    相关资源
    最近更新 更多