【发布时间】:2020-07-01 22:24:30
【问题描述】:
【问题讨论】:
-
添加您尝试过的示例代码以便我们为您提供帮助,也许是dartpad example
标签: listview flutter gridview flutter-layout
【问题讨论】:
标签: listview flutter gridview flutter-layout
您将不得不使用 childAspectRatio。我已经通过下面的示例说明了横向和纵向模式。如果你想要一个方形网格,那么考虑使用 childAspectRatio 作为 1。
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<String> cities = ['Kathmandu', 'Baglung', 'Pokhara'];
var width = 100;
var height = 200;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
color: Colors.blueAccent,
child: GridView.builder(
itemCount: cities.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: MediaQuery.of(context).orientation ==
Orientation.landscape ? 3: 2,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
childAspectRatio: width / height),
itemBuilder: (context, position) {
return Container(
alignment: Alignment.center,
color: Colors.black,
child: Text(
cities[position],
style: TextStyle(color: Colors.white),
),
);
}),
));
}
}
【讨论】:
使用flutter_staggered_grid_view插件。
代码:
class MyHomeScreen extends StatefulWidget {
@override
_MyHomeScreenState createState() => _MyHomeScreenState();
}
class _MyHomeScreenState extends State<MyHomeScreen> {
List<ItemDetailsModel> itemDetails = [
ItemDetailsModel(
name: "Hello 1",
color: Colors.teal
),
ItemDetailsModel(
name: "Hello 2",
color: Colors.teal[100]
),
ItemDetailsModel(
name: "Hello 3",
color: Colors.teal[200]
),
ItemDetailsModel(
name: "Hello 4",
color: Colors.teal[300]
),
ItemDetailsModel(
name: "Hello 5",
color: Colors.teal
),
ItemDetailsModel(
name: "Hello 6",
color: Colors.tealAccent
),
ItemDetailsModel(
name: "Hello 7",
color: Colors.tealAccent[200]
),
ItemDetailsModel(
name: "Hello 8",
color: Colors.tealAccent[300]
),
ItemDetailsModel(
name: "Hello 9",
color: Colors.green
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Staggered Grid View"),),
body: Center(
child: sliverGridWidget(context),
),
);
}
Widget sliverGridWidget(BuildContext context){
return StaggeredGridView.countBuilder(
padding: const EdgeInsets.all(8.0),
crossAxisCount: 4,
itemCount: itemDetails.length,
itemBuilder: (context, index){
return Container(
color:itemDetails[index].color,
child:Text(itemDetails[index].name)
);
},
staggeredTileBuilder: (index) => StaggeredTile.count(2,3), //Make size as you want.
mainAxisSpacing: 8.0,
crossAxisSpacing:8.0,
);
}
}
模型类:
class ItemDetailsModel{
String name;
Color color;
ItemDetailsModel({this.name, this.color});
}
输出:
【讨论】: