Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

flutter - Equivalent of if let and guard let of Swift in Dart

Just started Flutter with native iOS background, so I just have a quick question about Dart beta null safety.

So in Swift, because they have the idea of null safety from the beginning just like Kotlin, there are 2 features that I really like about the language is if let and guard let. These 2 make working with optional values so much easier. I'm not sure if the beta version of Dart has anything like that.

Thanks

question from:https://stackoverflow.com/questions/65937353/equivalent-of-if-let-and-guard-let-of-swift-in-dart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not an expert on Swift, but Dart will use null checks to automatically promote types, and I think that mostly does the job of if let and guard let.

For example:

String? x = possiblyReturnsNull();
if (x != null) {
  // All code within this block treats `x` as non-nullable.
}
// All code outside the block continues to treat `x` as nullable.

Note that promotion won't be performed on non-local variables, so for those you would need to explicitly introduce a local reference. (There is a language proposal to provide a mechanism to allow a nicer mechanism to add a local reference without polluting the outer scope.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...