老实说,我是 Flutter 的新手和开发者。我一直在尝试让每个按钮在点击时改变颜色;它确实有效,但我遇到了按钮占用所有水平空间的问题。我尝试并寻找我能做到的方法。有什么办法可以改变宽度吗?
看起来像这样:https://ibb.co/rFNfSf4
class Home extends StatefulWidget {
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<bool> isSelected = [false, false, false, false];
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.grey[850],
appBar: AppBar(
title: Text(
"A Sample Quiz",
style: TextStyle(
letterSpacing: 1.3,
fontFamily: "SourceCodePro",
),
),
centerTitle: true,
backgroundColor: Colors.grey[900],
elevation: 2.0,
),
body: Center(
child: Column(
children: <Widget>[
SizedBox(
height: 20.0,
),
Text(
"Choose all that apply:",
style: TextStyle(
fontFamily: "NotoSans",
letterSpacing: 1.2,
fontSize: 18.0,
color: Colors.white,
),
),
SizedBox(
height: 9.0,
),
answerButtonBoxes("Answer"),
],
),
),
),
);
}
Column answerButtonBoxes(String label) {
return Column(
children: [
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: isSelected.length,
itemBuilder: (BuildContext context, int index) {
return ElevatedButton(
onPressed: () {
setState(() => isSelected[index] = !isSelected[index]);
},
child: Text(
"$label ${index + 1}",
style: TextStyle(fontFamily: "NotoSans", fontSize: 15.0),
),
style: ElevatedButton.styleFrom(
primary:
isSelected[index] ? Colors.blue : Colors.transparent,
elevation: 0.0,
side: BorderSide(
color: Colors.white,
width: isSelected[index] ? 0 : 1,
style: isSelected[index]
? BorderStyle.none
: BorderStyle.solid,
),
),
);
}),
],
);
}
}
你阻止你的
button
得到expanded
你可以将你的ElevatedButton包装到Center小部件然后你不必assign
具体width
到你的按钮
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: isSelected.length,
itemBuilder: (BuildContext context, int index) {
return Center(
child: ElevatedButton(
onPressed: () {
setState(() => isSelected[index] = !isSelected[index]);
},
child: Text(
"$label ${index + 1}",
style:
TextStyle(fontFamily: "NotoSans", fontSize: 15.0),
),
style: ElevatedButton.styleFrom(
primary: isSelected[index]
? Colors.blue
: Colors.transparent,
elevation: 0.0,
side: BorderSide(
color: Colors.white,
width: isSelected[index] ? 0 : 1,
style: isSelected[index]
? BorderStyle.none
: BorderStyle.solid,
),
),
),
);
})
尝试下面的代码并设置按钮的
fixedSize
。
参考
ElevatedButton
这里
ElevatedButton(
style: ElevatedButton.styleFrom(
fixedSize: const Size(
200,
50,
),
),
onPressed: () {
print('Button Presssed');
// add your onPressed function here
},
child: const Text(
'Button',
),
),
你可以像这样用
Elevated Button
重构Padding
,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 40.0),
child: ElevatedButton();
您可以将按钮包裹在
FittedBox
中。
像这样:
FittedBox(
child: ElevatedButton(
child: Text("GO"),
onPressed: () {},
),
),