我正在嘗試使用左側的文本標簽和右側的堆疊小部件在顫動中創建狀態指示器,我設法使用 Row 排列它們,但每個小部件的寬度沒有均勻分開,堆疊最大寬度隨容器溢位。
到目前為止,這是我的代碼。
import 'package:flutter/material.dart';
class CustomIndicatorBar extends StatelessWidget {
const CustomIndicatorBar({
Key key,
@required this.percent,
@required this.title,
}) : super(key: key);
final double percent;
final String title;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final double maxBarWidth = constraints.maxWidth;
double barWidth = percent * maxBarWidth;
if (barWidth < 0) {
barWidth = 0;
}
return Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
title,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
Stack(
children: [
Container(
height: 20.0,
decoration: const BoxDecoration(
color: Color(0xFF555454),
),
),
Container(
height: 20.0,
width: barWidth,
decoration: const BoxDecoration(
color: Color(0xFFFA9F1D),
),
)
],
)
],
),
);
},
),
);
}
}
這是輸出

我想要實作的是將它們均勻地隔開,并且堆疊寬度不會從容器中溢位。
uj5u.com熱心網友回復:
請嘗試我的解決方案:

結果:

完整代碼:
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(
title: 'Demo',
home: FirstRoute(),
));
}
class FirstRoute extends StatefulWidget {
const FirstRoute({Key? key}) : super(key: key);
@override
State<FirstRoute> createState() => _FirstRouteState();
}
class _FirstRouteState extends State<FirstRoute> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('First Route'),
),
body: Column(
children: const [
SizedBox(height: 16),
CustomIndicatorBar(
title: 'Mood',
percent: 0.5,
),
SizedBox(height: 16),
CustomIndicatorBar(
title: 'Hunger',
percent: 0.7,
),
],
),
);
}
}
class CustomIndicatorBar extends StatelessWidget {
const CustomIndicatorBar({
Key? key,
required this.percent,
required this.title,
}) : super(key: key);
final double percent;
final String title;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
title,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
),
Expanded(
child: Stack(
children: [
Container(
height: 20.0,
decoration: const BoxDecoration(
color: Color(0xFF555454),
),
),
LayoutBuilder(builder: (context, constraints) {
return Container(
height: 20.0,
width: constraints.maxWidth * percent,
decoration: const BoxDecoration(
color: Color(0xFFFA9F1D),
),
);
})
],
),
)
],
),
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/372218.html
標籤:扑
下一篇:當另一個元素懸停時更改svg路徑
