Dart中列表内类实例属性返回null:为何qu[0].que输出null?
Hey there! Let's dig into why qu[0].que is returning null instead of the string you passed.
The root issue here is likely tied to how you're initializing class properties in your constructor, combined with potential Dart null safety behavior. Let's break it down:
Your current Q class constructor uses manual assignment in the constructor body:
Q({String q1, bool q2}) { que = q1; qa = q2; }
While this looks correct on the surface, there are a few critical pitfalls here:
- Null Safety Misalignment: If you're using Dart's default null safety (enabled in all recent versions), declaring
String que;without marking it nullable (String? que;) or initializing it immediately will cause compilation issues. Even if you bypassed that, the runtime might default the property to null before your constructor body runs, overriding your manual assignment. - Unenforced Required Parameters: Your named parameters aren't marked
required, which means Dart allows creating aQinstance without passing them. While you are passing them in your list, this leaves room for accidental nulls and makes the code less explicit. - Manual Assignment Risk: Even small typos in manual assignments (like swapping
q1andq2) can lead to unexpected null values, though that doesn't seem to be the case here.
The Fix
The cleanest, most reliable solution is to use Dart's constructor initialization syntax with this to directly bind parameters to class properties. This eliminates manual assignment errors and ensures proper initialization:
First, update your Q class in q.dart:
class Q { String que; bool qa; // Use `required` to enforce these parameters must be passed Q({required this.que, required this.qa}); }
Then, update your instance creation in main.dart to use the property names directly as named parameters (this also makes your code more readable):
List<Q> qu = [ Q( que: 'You can lead a cow downstairs but not upstairs.', qa: false, ), Q( que: 'YAML Ain\'t Markup Language', // Escape the single quote to avoid syntax errors! qa: true, ), ];
Now, when you run print(qu[0].que), it should correctly output the first string as you expected.
内容的提问来源于stack exchange,提问作者akshit.C

