Flutter空安全升级报错:可空类型User?无法赋值给非空类型User的代码修改请求
Hey there! Let's work through this null safety error together. The core issue here is that Dart can't automatically promote the nullable event.user (a class property) to a non-nullable auth.User — even after you check event.user != null — because class properties aren't guaranteed to stay non-null between the check and usage (even if they're final, the compiler plays it safe).
Here are two solid fixes for your code:
Option 1: Use a local variable for type promotion (Recommended)
This is the safest approach because it lets Dart's compiler properly recognize that user is non-null in the authenticated branch:
Stream<AuthState> _mapAuthUserChangedToState(AuthUserChanged event) async* { // Assign the property to a local variable first final user = event.user; if (user != null) { yield AuthState.authenticated(user: user); } else { yield AuthState.unauthenticated(); } }
By moving event.user to a local variable, Dart can track that we've checked for null, so it promotes user to a non-nullable auth.User inside the if block. No risky assertions needed!
Option 2: Use the null assertion operator (!)
If you're 100% confident that event.user is non-null when the ternary runs (which your null check ensures), you can use ! to tell Dart you know it's safe:
Stream<AuthState> _mapAuthUserChangedToState(AuthUserChanged event) async* { yield event.user != null ? AuthState.authenticated(user: event.user!) : AuthState.unauthenticated(); }
Just keep in mind: if for some reason event.user ends up being null here (even though your check says it shouldn't), this will throw a runtime error. That's why Option 1 is better for safety.
Quick note on your existing code
Your AuthState.authenticated constructor is correctly enforcing a non-null user (since an authenticated state should always have a valid user), so we don't want to change that. The fix is all about how we pass the user to that constructor.
内容的提问来源于stack exchange,提问作者Levent Demirci

