带有图像和类别名称的类别网格显示在图像下方
Widget build(BuildContext context) {
return FutureBuilder(
future: categoriesService.getCategories(1),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.error != null) {
print('error ${snapshot.error}');
return Text(snapshot.error.toString());
}
// YOUR CUSTOM CODE GOES HERE
return Container(
// padding: const EdgeInsets.all(0.0),
child: GridView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
// childAspectRatio: 19 / 12,
mainAxisSpacing: 10.0,
crossAxisSpacing: 10.0,
),
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
Category category = snapshot.data[index];
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
child: Image.network(
category.image,
fit: BoxFit.cover,
),
decoration: BoxDecoration(
border: Border.all(width: 1.0),
),
),
Text(category.name)
],
);
},
),
);
} else {
return new CircularProgressIndicator();
}
});
Run Code Online (Sandbox Code Playgroud)
}
我的子项目有一个图像和类别名称。如图所示,当前子项溢出,我们无法看到图像下方的类别名称,并且无法删除图像和边框之间的顶部空间。
原创设计在这里
您可以使用设备的宽度和高度来动态计算纵横比。我添加了一个基于你的代码示例,展示了如何做到这一点。请注意,您可能需要稍微调整提供的纵横比以满足您的特定要求。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class Category {
String name;
String image;
Category({this.name, this.image,});
}
class CategoriesService {
Future<List<Category>> getCategories(int value) async {
return <Category>[
Category(
name: 'FRESH CHICKEN',
image: 'https://picsum.photos/400/300',
),
Category(
name: 'FRESH MUTTON',
image: 'https://picsum.photos/400/300',
),
Category(
name: 'HALAL FROZEN FISH',
image: 'https://picsum.photos/400/300',
),
Category(
name: '2X STORE',
image: 'https://picsum.photos/400/300',
),
Category(
name: 'FROZEN NONVEG DELIGHTS',
image: 'https://picsum.photos/400/300',
),
Category(
name: 'FROZEN VEG DELIGHTS',
image: 'https://picsum.photos/400/300',
),
Category(
name: 'DAL & PULSES',
image: 'https://picsum.photos/400/300',
),
Category(
name: 'SPICES',
image: 'https://picsum.photos/400/300',
),
Category(
name: 'DRY FRUITS & NUTS',
image: 'https://picsum.photos/400/300',
),
];
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: FutureBuilder(
future: CategoriesService().getCategories(1),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.error != null) {
print('error ${snapshot.error}');
return Text(snapshot.error.toString());
}
// YOUR CUSTOM CODE GOES HERE
return Container(
// padding: const EdgeInsets.all(0.0),
child: GridView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
childAspectRatio: MediaQuery.of(context).size.width /
(MediaQuery.of(context).size.height / 1.4),
mainAxisSpacing: 10.0,
crossAxisSpacing: 10.0,
),
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
Category category = snapshot.data[index];
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
child: Image.network(
category.image,
fit: BoxFit.cover,
),
decoration: BoxDecoration(
border: Border.all(width: 1.0),
),
),
Padding(
padding: const EdgeInsets.only(
top: 8.0,
),
child: Text(
category.name,
textAlign: TextAlign.center,
),
)
],
);
},
),
);
} else {
return new CircularProgressIndicator();
}
}),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
GridView如果您还没有看到以下答案,您可能会发现以下答案对有关小部件纵横比的附加信息很有用。
我找到了一种方法来动态设置最大孩子的纵横比到我们的网格视图。它是如何工作的 ?首先请看这个答案。我们如何在构建过程中找到小部件的大小overlayEntery
之后,我们在 childAspectRatio 中为我们的网格视图设置正确的纵横比(使用 overlayEntery 测量)。
我希望这对你有帮助。
我举个例子...
https://dartpad.dev/4821d71ec618d7d1f1f92f27458fde61
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class GridItemModel {
String longtext;
GlobalKey itemKey;
double width;
double height;
GridItemModel(this.longtext) {
itemKey = GlobalKey();
}
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return _StateHomePage();
}
}
class _StateHomePage extends State<MyHomePage> {
// this first assign very important don't change it .
// if you change this part overlayEntry cant find biggest widget correctly .(cant see not scrolled items.)
// for test change to 1/1 and see what happening.
var myDynamicAspectRatio = 1000 / 1;
OverlayEntry sticky;
List<GridItemModel> myGridList = new List();
double maxHeight = 0;
double maxWidth = 0;
@override
void initState() {
if (sticky != null) {
sticky.remove();
}
sticky = OverlayEntry(
builder: (context) => stickyBuilder(context),
);
WidgetsBinding.instance.addPostFrameCallback((_) {
Overlay.of(context).insert(sticky);
setState(() {});
});
super.initState();
}
@override
void dispose() {
WidgetsBinding.instance.addPostFrameCallback((_) {
sticky.remove();
});
super.dispose();
}
@override
Widget build(BuildContext context) {
final title = 'Grid List';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: GridView.count(
crossAxisCount: 2,
childAspectRatio: myDynamicAspectRatio,
children: List.generate(20, (index) {
myGridList.add(new GridItemModel(longTextMaker(index)));
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
key: myGridList[index].itemKey,
decoration: BoxDecoration(
border: Border.all(color: Colors.black),
color: Colors.teal[index*100]
),
child: Text(
'Item $index' + myGridList[index].longtext,
style: Theme.of(context).textTheme.headline5,
),
),
],
);
}),
),
),
);
}
String longTextMaker(int count){
String result = "longText";
for(int i = 0 ; i < count; i++){
result += "longText" ;
}
return result;
}
shouldUpdateGridList(){
bool isChanged =false;
for(GridItemModel gi in myGridList) {
if(gi.width != null) {
if (gi.height > maxHeight) {
maxHeight = gi.height;
maxWidth = gi.width;
isChanged = true;
}
}
}
if(isChanged) {
myDynamicAspectRatio = maxWidth / maxHeight;
print("AspectRatio" + myDynamicAspectRatio.toString());
}
}
Widget stickyBuilder(BuildContext context) {
for(GridItemModel gi in myGridList) {
if(gi.width == null) {
final keyContext = gi.itemKey.currentContext;
if (keyContext != null) {
final box = keyContext.findRenderObject() as RenderBox;
print(box.size.height);
print(box.size.width);
gi.width = box.size.width;
gi.height = box.size.height;
}
}
}
shouldUpdateGridList();
return Container();
}
}
Run Code Online (Sandbox Code Playgroud)
有一个flutter包可以方便的解决这个问题。请访问https://pub.dev/packages/dynamic_height_grid_view进行查看。这样您就可以指定横轴计数,而无需考虑纵横比。
小智 5
您可以在 GridView.builder 中提供 childAspectRatio,如下所示:
GridView.builder(
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount:3,childAspectRatio: (150.0 / 220.0)
)
)
Run Code Online (Sandbox Code Playgroud)
小智 5
对于大多数儿童身高是静态的或需要静态的用例,请使用mainAxisExtent。
官方文档
/// The extent of each tile in the main axis. If provided it would define the
/// logical pixels taken by each tile in the main-axis.
///
/// If null, [childAspectRatio] is used instead.
final double? mainAxisExtent;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9947 次 |
| 最近记录: |