有没有办法在Dart中使用两种类型的参数? [英] Is there a way to have an argument with two types in Dart?

查看:686
本文介绍了有没有办法在Dart中使用两种类型的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于导航,我构建了一个简单的工厂类,该类生成一个ListTile,将ListPile推送到导航器:

For navigation, I built a simple factory class that generates a ListTile that pushes a route to the Navigator:

static Widget simpleNavRow(String text, BuildContext context, String route) {
  return Column(
    children: <Widget>[
      ListTile(
        title: Text(text),
        onTap: () {
          Navigator.pushNamed(context, route);
        },
      ),
      Divider(),
    ],
  );
}

但是,我很快意识到,支持推送小部件也很方便(如果可能的话,也可以从其类中实例化).我不知道如何使"route"参数接受String或Widget,因此我创建了一个使用这两种类型之一进行初始化的类.这段代码有效,但是有更好的方法吗?

However, I soon realized that it would be convenient to support pushing widgets as well (or instantiate from their class if possible). I couldn't figure out how to make the "route" argument accept either a String or a Widget, so I created a class that initializes with one of those two types. This code works, but is there a better way to achieve this?

class NavTo {
  String route;
  Widget widget;

  NavTo.route(this.route);
  NavTo.widget(this.widget);

  push(BuildContext context) {
    if (route != null) {
      Navigator.pushNamed(context, route);
    }
    if (widget != null) {
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return widget;
      }));
    }
  }
}

class ListHelper {
  static final padding = EdgeInsets.all(12.0);

  static Widget simpleNavRow(String text, BuildContext context, NavTo navTo) {
    return Column(
      children: <Widget>[
        ListTile(
          title: Text(text),
          onTap: () {
            navTo.push(context);
          },
        ),
        Divider(),
      ],
    );
  }
}

// usage:
// ListHelper.simpleNavRow('MyWidget', context, NavTo.widget(MyWidget()))

推荐答案

我不认为Dart中提供联合类型.我喜欢您的解决方案,而不是使用动态类型,因为它是强类型的. 您可以使用命名参数.

I don’t believe the union type is available in Dart. I like your solution over the use of dynamic as it is strongly typed. You could use named parameters.

NavTo({this.route,this.widget})

但是然后您就不必对一个参数和一个参数进行编译类型检查了.

But then you don’t have compile-type checking for one and only one parameter.

我对构造函数的唯一改进是添加@required.

The only improvement I would make to your constructors is to add @required.

这篇关于有没有办法在Dart中使用两种类型的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆