Issue
I have a ButtonBar
which has either 5 or 6 buttons.
I.e. it always has 5 buttons and based on a condition, it gets an extra 6th button.
I want to assign an icon size to each button (each button has the same size), but the problem is that the iconSize is dependent on the number of buttons in the bar (since I always need the buttonbar to be exactly one row)
var iconSize = MediaQuery.of(context).size.width / 5 / 2;
var buttons = <IconButton>[];
// Add 5 buttons
buttons.add(
IconButton(
icon: Icon(
Icons.settings,
),
color: Colors.white,
iconSize: iconSize,
onPressed: () {
_goToSettings(context);
}),
);
// add 4 more
...
// Maybe add a 6th button
buttons.add(IconButton(
...
));,
if(myCondition) { buttons.Add(IconButton(...)); }
So iconSize
should simply be iconSize = MediaQuery.of(context).size.width / buttons.length / 2
;
But the problem is, the length of the array buttons
is known only after butons
is filled. But once buttons
is filled, I cannot set the iconSize any longer
var size = MediaQuery.of(context).size.width / buttons.length / 2`
for(var x in buttons){
x.iconSize = size; // iconSize is final.
}
Isn't there a clean way to know the size beforehand or to set the size afterwards? I am aware I can simply do this
var iconSize = MediaQuery.of(context).size.width / (myCondition)?6:5 / 2;
But this is a code smell. It does not scale. What if there are other conditions? I simply want the length of the acutal array as it will be and then set the icon size.
I also cannot assign the IconButton.iconSize
to a variable and later on change it. The previous value will still be used.
Solution
There are of course many different ways to solve this problem, here goes one:
Instead of creating a list of created IconButton
s, create a list of functions that return an icon button:
var buttonBuilders = <IconButton Function()>[];
late double iconSize;
Now add functions that create your buttons:
buttonBuilders.add(
() => IconButton(
icon: Icon(
Icons.settings,
),
color: Colors.white,
iconSize: iconSize,
onPressed: () {
_goToSettings(context);
},
),
);
Now that you have your list you can determine what is the appropriate iconSize
:
iconSize = MediaQuery.of(context).size.width / buttonBuilders.length / 2;
Now you can either just use the buttonBuilders
list and call each element when using it or turn it to a buttons
list:
final buttons = buttonBuilders.map((b) => b()).toList();
Answered By - Hossein Yousefi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.