【问题标题】:Flutter adding an item each x time on sliver list颤振在 sliver 列表上每次 x 次添加一个项目
【发布时间】:2021-09-04 15:14:35
【问题描述】:

我需要在我的银色列表的第 6 个帖子之后展示一个广告,现在我正在执行以下方法并且它正在工作,但它正在替换广告中的帖子而不是实际添加它。

SliverList(
   delegate: SliverChildBuilderDelegate((context, i) {
      if ( i != 0 && i % 6 == 0 ) { // this replacing each 6th on the list not adding new
         // return ad widget
      }
      // return list item
   },
   childCount: dynamicListLength
)

【问题讨论】:

  • 将 i % 6 = 0 更改为 i % 6 == 0
  • 很抱歉,这是一个错字,但我的代码中当然已经是 ==

标签: android ios flutter dart flutter-layout


【解决方案1】:

以下是使用ListView.builder 的方法(很容易适应SliverList):

import 'package:flutter/material.dart';

// Represents the default item
class ItemWidget extends StatelessWidget {
  final String text;
  
  const ItemWidget(this.text);
  
  @override
  Widget build(BuildContext context) {
    return Container(color: Colors.green, child: Text(text));    
  }
}

// Represents the ad widget
class AdWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(color: Colors.red, child: Text("Ad"));    
  }
}

class Screen extends StatelessWidget {
  final List<Widget> children;
  
  const Screen({this.children});
  
  @override
  Widget build(BuildContext context) {
    const int every = 6;
    
    final int size = children.length + children.length ~/ every;
    final List<Widget> items = List.generate(size, (i) {
      if (i != 0 && i % every == 0) return AdWidget();
      return children[i - i ~/ every];
    });
    
    return ListView.builder(
      itemBuilder: (_, i) => items[i],
      itemCount: items.length,
    );  
  }
}

那么你可以这样使用它:

Screen(children: [for (int i = 0; i < 30; i++) ItemWidget("$i")]);

【讨论】:

  • 它正在替换我的一些数据列表以添加仍然在列表视图上的广告小部件,您的代码与我的相似,唯一的区别是[i - i ~/ every];
  • 您是否正在更改 ListView 的项目数(例如 children.length + children.length ~/ every)?如果是这样,您能否编辑您的问题以显示您如何创建 dynamicListLength 变量?
  • 是的,这就是它现在可能工作的原因,谢谢。
猜你喜欢
  • 2019-08-19
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多