-1

采用以下非空安全 Dart 代码:

class RoundedButton extends StatelessWidget {
  RoundedButton({this.title, this.color, @required this.onPressed});

  final Color color;
  final String title;
  final Function onPressed;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 16.0),
      child: Material(
        elevation: 5.0,
        color: color,
        borderRadius: BorderRadius.circular(30.0),
        child: MaterialButton(
          onPressed: onPressed,
          minWidth: 200.0,
          height: 42.0,
          child: Text(
            title,
            style: TextStyle(
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }
}

关于构造函数的参数,Android Studio 表示,“参数 [parameter] 由于其类型的原因,不能具有 'null' 的值,但隐含的默认值是 'null'。”

我理解错误并发现我可以像这样简单地修改代码:

class RoundedButton extends StatelessWidget {
  RoundedButton({this.title, this.color, required this.onPressed});

  final Color? color;
  final String? title;
  final Function onPressed;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 16.0),
      child: Material(
        elevation: 5.0,
        color: color,
        borderRadius: BorderRadius.circular(30.0),
        child: MaterialButton(
          onPressed: onPressed.call(),
          minWidth: 200.0,
          height: 42.0,
          child: Text(
            title!,
            style: TextStyle(
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }
}

这样,我满足了语言规则,但使用 bang 运算符进行“强制展开”可能是不受欢迎的。

所以我的解决方案似乎很老套......所以在这种情况下,将这段代码转换为空安全的优雅、适当甚至性感的方法是什么,如果有多种方法,那么优缺点是什么?

谢谢!

4

1 回答 1

1

正如您所说,有几种方法可以迁移到 null 安全代码,使所有变量都可以为 null 是一种可能的解决方案,这里有另外两种:

1. 使变量具有默认值

从:

final String title;

至:

final String title = '';

或者

MyClass {
  MyClass({this.title=''});
  final String title;
}

何时使用

如果您有一个变量应该以某个值开头并随着时间的推移而变化,或者如果您有一个变量不太可能对每个实例都是唯一的。

好的

int timesOpened = 0;

坏的

int uniqueValue = 0 // if it should be unique, it shouldn't be default.

2. 在构造函数处强制一个值

从:

MyClass {
  MyClass({this.title});
  final String title;
}

至:

MyClass {
  MyClass({required this.title});
  final String title;
}

何时使用

当您有一个必须传递给每个实例的值并且每​​个实例可能不同时

好的

MyClass({required this.onPressed});

坏的

MyClass({required this.textSize}); // probably should have a default text size value

如果我是你,我会让 color 有一个默认值,并且 title 和 onPressed 是必需的参数。但你会比我更清楚。

于 2021-11-10T00:25:33.093 回答