我正在尝试在Flutter中创建自己的水平堆叠条形窗口小部件,但遇到了一些困难。这是我的代码的再现:
class StackedBar extends StatefulWidget {
HashMap<int, double> factors = HashMap();
StackedBar(){
factors[0] = 0.1;
factors[1] = 0.3;
factors[2] = 0.5;
factors[3] = 0.1;
}
@override
_StackedBarState createState() => new _StackedBarState();
}
class _StackedBarState extends State<StackedBar> {
@override
Widget build(BuildContext context) {
List<Widget> widgets = [];
for (int i =0; i < widget.factors.length; i++) {
var w = Flexible(
child: FractionallySizedBox(
widthFactor: widget.factors[i],
child: Container(
height: 50,
color: ColorHelper.getColor(i))));
widgets.add(w);
}
return Container(
color: Colors.white,
height: 50,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: widgets));
}
}
结果如下所示: 因此,您可以看到该条没有覆盖整行。我认为问题在于FractionallySizedBox并不是根据行宽度来计算分数,而是根据行内小部件可用于他的空间(在我的情况下,可能是行宽度的1/4)来计算分数。我对么?如果是这样,什么是正确的解决方案?
答案 0 :(得分:1)
使用扩展而不是灵活。像这样更改代码:
final HashMap<int, double> factors = HashMap();
StackedBar(){
factors[0] = 1;
factors[1] = 3;
factors[2] = 5;
factors[3] = 1;
}
并在您的构建方法中:
for (int i =0; i < widget.factors.length; i++) {
var w = Expanded(
flex: widget.factors[i],
child: Container(
height: 50,
color: Colors.accents[i]));
widgets.add(w);
}