我試圖在每 3 個索引之后放置一個廣告。我得到了所需的輸出,但我的問題是我有兩種型別的串列,
- 串列一中有 50 個資料。
- 清單二只有 5 個資料。
當我嘗試使用以下代碼時。
ListView.separated(
physics: NeverScrollableScrollPhysics(),
padding: EdgeInsets.all(15),
shrinkWrap: true,
itemCount: articles.length,
separatorBuilder: (context, index) => SizedBox(
height: 15,
),
itemBuilder: (BuildContext context, int index) {
final Article article = articles[index];
final Sponsor sponsor = sponsors[index];
if(index %3 == 0 && index != 0) return SponsorCard(sponsor: sponsor, scaffoldKey: widget.scaffoldKey);
return Card4(article: article, heroTag: 'recent${article.id}', scaffoldKey: widget.scaffoldKey);
widget.scaffoldKey);
},
),
自從贊助商串列到達最后一個位置后,我收到了范圍錯誤。錯誤
The following RangeError was thrown building:
RangeError (index): Invalid value: Not in inclusive range 0..4: 49
我需要的是我需要將贊助商串列設為回圈,以便如果串列到達最后一個位置,它必須再次移動到第一個位置。
有人可以幫我解決這個問題。
uj5u.com熱心網友回復:
您可以創建一個新的組合串列,并確保 Article 和 Sponsor 類都應該是 ListItem 的子類。或者您需要在 ListItem Wrapper 類下包裝 Article & Sponsor 類
列出專案 = []
現在將這些專案與 ListView 一起使用:
ListView.separated(
physics: NeverScrollableScrollPhysics(),
padding: EdgeInsets.all(15),
shrinkWrap: true,
itemCount: items.length,
separatorBuilder: (context, index) => SizedBox(
height: 15,
),
itemBuilder: (BuildContext context, int index) {
if (item[index] is Articles){
return SponsorCard(..);
}else{
return Card4(...);
}
},
);
在請求評論中添加了示例:
class _ListItem {
final bool isArticleType;
final dynamic value;
_ListItem(this.isArticleType, this.value);
}
class Article {}
class Sponsor {}
List<_ListItem> createList(List<Article> articles, List<Sponsor> sponsors) {
List<_ListItem> items = [];
items.addAll(articles.map((e) => _ListItem(true, e)).toList());
var index = 0;
var sIndex = 0;
for (var i = 0; i < articles.length && sIndex < sponsors.length; i ) {
if (i != 0 && i % 3 == 0) {
items.insert(index, _ListItem(false, sponsors[sIndex]));
sIndex ;
index ;
}
index ;
}
return items;
}
uj5u.com熱心網友回復:
謝謝你們的回復。
我可以通過下面的代碼來實作。
itemBuilder: (BuildContext context, int index) {
actualIndex = actualIndex 1;
if(sponsorIndex 1 >= sponsors.length){
sponsorIndex = -1;
}
if(index == 0 ){
articleIndex = -1;
}
if ((actualIndex-tempIndex) % 3 == 0 && actualIndex != 0 && (actualIndex-prevIndex) >=3 ) {
tempIndex = tempIndex 1;
prevIndex = actualIndex;
sponsorIndex = sponsorIndex 1;
final Sponsor sponsor = sponsors[sponsorIndex];
return SponsorCard(sponsor: sponsor, scaffoldKey: widget.scaffoldKey);
}
articleIndex = articleIndex 1;
final Article article = articles[articleIndex];
return Card4(article: article, heroTag: 'recent${article.id}', scaffoldKey: widget.scaffoldKey);
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/506383.html