Use constructor arguments to evaluate final values depending on each other. Flutter / Dart

2,490

If you want to use a parameter in the initializer list, the parameter can't be an initializing parameter, and you need to do the initializing in the initializer list instead:

class _A {
  _A(bool limitPages, int pagesToDisplay)
      : limitPages = limitPages,
        pagesToDisplay = limitPages ? 10 : pagesToDisplay;

  final int pagesToDisplay;
  final bool limitPages;
}
Share:
2,490
Joel Broström
Author by

Joel Broström

Updated on December 09, 2022

Comments

  • Joel Broström
    Joel Broström over 1 year

    I have a widget that takes a number representing pages allowed to be displayed on the screen. If the device is weak a bool can be passed that overrides the initial value. However, since all values are final I must evaluate it in the constructor before the value is set.

    class _A extends StatefullWidget{
    
      _A(this.limitPages, 
        this.pagesToDisplay: limitPages ? 10 : pagesToDisplay,
      )
    
      final int pagesToDisplay;
      final bool limitPages;
    }
    

    I could declare it in the initializer list, but then I can't pass an argument for pagesToDisplay.

    class _A extends StatefullWidget{
      _A(this.limitPages)
        :this.pagesToDisplay: limitPages ? 10 : pagesToDisplay
    
      final int pagesToDisplay;
      final bool limitPages;
    }
    

    Is there any way to assert a statement in/before the constructor sets the final value?