Home > Software design >  Flutter source code, why should we put assertion here?
Flutter source code, why should we put assertion here?

Time:03-16

When I read flutter source code, Text widget, I founded this:

const Text(
    String this.data, {
    Key? key,
    this.style,
    this.strutStyle,
    this.textAlign,
    this.textDirection,
    this.locale,
    this.softWrap,
    this.overflow,
    this.textScaleFactor,
    this.maxLines,
    this.semanticsLabel,
    this.textWidthBasis,
    this.textHeightBehavior,
  }) : assert(
         data != null,
         'A non-null String must be provided to a Text widget.',
       ),
       textSpan = null,
       super(key: key);

I can't get why should we put assertion data!=null here?
My thought is that this.data would always be assign(because it is not optional), and never be null. Or is there any concern?

CodePudding user response:

This is still useful for projects that are not running with null safety yet.

Flutter is now fully null-safe, and you are right: it "should" never be null because the type is not nullable.


This comes from when Flutter and dart were not supporting null safety yet. Before null safety, you could have done Text(null) and the linter wouldn't have complained.

So why is it still there now that Flutter is null safe?

Flutter puts a lot of effort into not introducing breaking changes and supports older versions. So an old flutter project that didn't migrate to null-safety will run without the null safety feature and could do Text(null).

  • Related