簡體   English   中英

如何最好地轉換觸發“參數不能為 'null' 但隱式默認值為 'null' 的舊 Dart 代碼。” 錯誤?

[英]How best to convert old Dart code that triggers "parameter can't be 'null' but the implicit default value is 'null'." error?

采用以下非空安全 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 運算符進行“強制展開”可能是不受歡迎的。

所以我的解決方案看起來很hacky......所以在這種情況下,將這段代碼轉換為空安全的優雅,適當甚至性感的方式是什么,如果有多種方式,那么利弊是什么?

謝謝!

有幾種方法可以遷移到空安全代碼,正如您所說,使所有變量都可以為空是一種可能的解決方案,這里有另外兩種方法:

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

如果我是你,我會讓顏色有一個默認值,標題和 onPressed 是必需的參數。 但你會比我更清楚。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM