我在JSON中有很多数据,超过8个数据。我想显示JSON中的7个数据和1个硬编码数据(用于“更多”功能)。我设法从JSON显示了7个数据,如下所示。
但是如何在我制作的框中将最后1个数据/索引与硬编码数据相加?
这是我显示数据的功能。
Widget _cardCategory(AsyncSnapshot<CatlistResult> snapshot) {
var numItems = snapshot == null ? 0 : snapshot.data.catlist.sublist(1, 8).length;
return Card(
elevation: 5.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5))),
margin: EdgeInsets.all(20.0),
child: GridView.builder(
shrinkWrap: true,
itemCount: numItems,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4),
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
child: Card(
elevation: 0.0,
child: Column(
children: <Widget>[
Expanded(
child: Image.asset('assets/images/main/cat_${snapshot.data.catlist[index].a}.png', fit: BoxFit.cover),
),
Text(
snapshot.data.catlist[index].c,
style: TextStyle(fontSize: 10),
),
],
),
),
);
},
),
);
}
我有来自 Rodrigo Lopez 的Telegram Group的Flutter社区的参考,这是代码。
Widget _cardCategory(AsyncSnapshot<CatlistResult> snapshot) {
var numItems = snapshot == null ? 0 : snapshot.data.catlist.sublist(1, 8).length;
return Card(
elevation: 5.0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(5))),
margin: EdgeInsets.all(20.0),
child: numItems == 0
? Container()
: GridView.builder(
shrinkWrap: true,
itemCount: numItems + 1,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4),
itemBuilder: (BuildContext context, int index) {
String imagePath;
String itemText;
if (index == (numItems+1)) {
imagePath = 'assets/images/main/cat_999.png';
itemText = 'More';
} else {
imagePath = 'assets/images/main/cat_${snapshot.data.catlist[index].a}.png';
itemText = snapshot.data.catlist[index].c;
}
return GestureDetector(
child: Card(
elevation: 0.0,
child: Column(
children: <Widget>[
Expanded(
child: Image.asset(imagePath, fit: BoxFit.cover),
),
Text(
itemText,
style: TextStyle(fontSize: 10),
),
],
),
),
);
},
),
);
}
如果我运行此代码,则结果如下: here
最后一个索引(8)不是来自硬编码的,而是来自索引8中的JSON。那么如何从硬编码中调用1个项目以显示在列表GridView的最后一个索引(8)中?
答案 0 :(得分:1)
基本上,您需要执行以下操作:
struct HapticButton : View {
@GestureState var isDetectingTap = false
var body: some View {
let tap = TapGesture()
.updating($isDetectingTap) { (body, stateType, transaction) in
// nothing happens below
print(body)
print(stateType)
print(transaction)
}.onEnded { _ in
// this one works but it is to late
// I need to figure out the beginning of the tap
print("Button was tapped, will invoke haptic feedback, maybe with UIKit")
}
return Button(action: {
print("Action executed")
}) {
HStack {
Image("icon")
Text("Login")
}
}.simultaneousGesture(tap)
}
}
答案 1 :(得分:0)
您只需要在Flutter社区的Telegram组代码中更改if语句
来自
if (index == (numItems+1))
到
if (index == numItems)
无论列表大小如何,这都会将您的硬编码内容放在列表的最后。重要提示:保持
itemCount: numItems + 1, //+1 is important