Home > Software design >  Required parameters per set flutter
Required parameters per set flutter

Time:12-30

let's say I have a class that has a particular style and placement for 2 buttons. I need the style and placement of buttons to be the same across some aspects of the app. As a result a programmer can add a text and the onTap function of the primary button, and if UI contains a second button programmer can add that as well.

class ButtonPlacement extends StatelessWidget {
  const ButtonPlacement({required this.primaryButtonText,required this.primaryButtonOnTap,
   this.secondaryButtonText,this.secondaryButtonOnTap, super.key});
etc

My question is, is there a way to throw a compile error just like in null safety required, if programmer adds lets say a secondary text but not a secondary onTap function, as these two go together as you understand.

CodePudding user response:

You can use assert which will only work in development.

class ButtonPlacement extends StatelessWidget {
  final String primaryButtonText;
  final Function() primaryButtonOnTap;
  final String? secondaryButtonText;
  final Function()? secondaryButtonOnTap;
  const ButtonPlacement({
    required this.primaryButtonText,
    required this.primaryButtonOnTap,
    this.secondaryButtonText,
    this.secondaryButtonOnTap,
    super.key,
  }) : assert((secondaryButtonText == null && secondaryButtonOnTap == null) ||
            (secondaryButtonText != null && secondaryButtonOnTap != null));
}

So if you try to create an instance of ButtonPlacement with one asserted parameter provided but not the other, it will throw and error in the console when you run it.

ButtonPlacement(
  primaryButtonOnTap: () {},
  primaryButtonText: 'text',
  secondaryButtonText: '', // throws a Failed assertion error in the console
)

CodePudding user response:

I just created a new class with these two variables, so programmer should input at most two of these classes instead of 4 variables. I will keep question open as I am intrigued to see other solutions

 class ButtonAttributes {
  String text;
  Function() onTap;

  ButtonAttributes({required this.text, required this.onTap});
}
  • Related