我正在尝试将GridView放在手机屏幕的中央。
我已经尝试使用crossAxisAlignment和mainAxisAlignment,但无济于事。下面是我当前的代码。
class CommanderDamage extends StatefulWidget {
int damage = 0;
CommanderDamage({this.damage, Key key});
@override
State<StatefulWidget> createState() {
return CommanderDamageState();
}
}
class CommanderDamageState extends State<CommanderDamage> {
var damage = [0, 0, 0, 0, 0, 0];
@override
Widget build(context) {
return MaterialApp(
home: Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xfff6921e), Color(0xffee4036)],
),
),
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2),
itemCount: damage.length,
itemBuilder: (BuildContext context, index) {
return Column(
children: <Widget>[
Expanded(
child: InkWell(
onTap: () {
setState(() {
damage[index]++;
});
},
onLongPress: () {
setState(() {
damage[index] = 0;
});
},
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(15),
child: Text(
'Player ${index + 1}',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold),
),
),
Text(
damage[index].toString(),
style: TextStyle(
color: Colors.white,
fontSize: 35.0,
fontWeight: FontWeight.bold),
),
],
),
),
),
],
);
},
),
),
),
],
),
),
);
}
}
当前,网格从屏幕顶部开始,我希望它位于屏幕中央。 Here is a mockup是什么样子与我的期望。
答案 0 :(得分:0)
Container
对准中心。Expanded
,因为它将填满主轴上的所有剩余空间。shrinkWrap: true
添加到您的GridView
中,这样它就不会填满所有垂直空间。Column
的主轴与中心对齐。您最终会得到这样的东西:
@override
Widget build(context) {
return MaterialApp(
home: Scaffold(
body: Container(
alignment: Alignment.center,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xfff6921e), Color(0xffee4036)],
),
),
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemCount: damage.length,
shrinkWrap: true,
itemBuilder: (BuildContext context, index) {
return InkWell(
onTap: () {
setState(() {
damage[index]++;
});
},
onLongPress: () {
setState(() {
damage[index] = 0;
});
},
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(15),
child: Text(
'Player ${index + 1}',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
),
Text(
damage[index].toString(),
style: TextStyle(
color: Colors.white,
fontSize: 35.0,
fontWeight: FontWeight.bold,
),
),
],
),
),
);
},
),
),
),
);
}
但是,当您收缩包装时,由于您的GridView
不再使用整个垂直空间,因此Android的过度滚动效果将变得怪异。我建议将GridView
的物理性质更改为BouncingScrollPhysics
。