Dart: implementing Null Safety in Factory Constructors Leading to advanced patterns
I'm trying to implement a factory constructor in my Dart class that returns an instance based on some conditions. However, I'm working with a null safety scenario where the object being returned is unexpectedly null, even though I think I've accounted for all possible cases. Here's a simplified version of my code: ```dart class User { final String name; final int age; User._(this.name, this.age); factory User.create({String? name, int? age}) { if (name == null || age == null) { return null; // This causes a question with null safety } return User._(name, age); } } ``` When I try to create a `User` object with: ```dart User? user = User.create(name: null, age: 25); ``` I expected this to return a `User` instance, but it results in a type behavior since the factory constructor is returning `null`. I've tried making the factory constructor return `User?`, but that feels wrong according to best practices. I also attempted to throw an exception instead of returning null, but then I would have to handle that exception everywhere I instantiate `User`. How can I handle this situation properly while making sure that I adhere to Dart's null safety features? Is there a more elegant way to manage this without compromising on the usability of my factory constructor? Any advice would be greatly appreciated!