dart - 如何知道用户是否看到了 flutter 图像

我在可滚动屏幕中有一个 Image 组件。刚开屏时看不到图片,需要向下滚动才能看到。

如何确保图像在用户滚动到该图像后完全被用户看到?我想统计用户的形象印象。

你是如何在 Flutter 中实现这一点的?

最佳答案

我没有太多关于您的代码的信息,所以这就是我解决它的方法。仅当图像在屏幕上完全可见时才会计算展示次数,您可以使用 _count = 表达式进行更改。我为 Image 使用了简单的 Container

先看看这个截图。


代码

void main() => runApp(MaterialApp(home: HomePage()),);

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  ScrollController _scrollController;
  double _heightListTile = 56, _heightContainer = 200, _oldOffset = 0, _heightBox, _initialAdd;
  int _initialCount, _count, _previousCount = 0, _itemsInList = 4;

  @override
  void initState() {
    super.initState();
    _heightBox = ((_itemsInList) * _heightListTile) + _heightContainer;
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      double offset = _scrollController.offset;
      if (offset >= _oldOffset) {
        _oldOffset = offset;
        _count = _initialCount + (offset + _initialAdd) ~/ _heightBox;
        if (_count != _previousCount) setState(() {});
        _previousCount = _count;
      }
    });

    Timer.run(() {
      bool isIos = Theme.of(context).platform == TargetPlatform.iOS;
      var screenHeight = MediaQuery.of(context).size.height - (isIos ? 100 : 80); // for non notches phone use 76 instead of 100 (it's the height of status and navigation bar)
      _initialCount = screenHeight ~/ _heightBox;
      _initialAdd = screenHeight % _heightBox;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(_count == null ? "Let's count" : "Images shown = ${_count}")),
      body: ListView.builder(
        itemCount: 100,
        controller: _scrollController,
        itemBuilder: (context, index) {
          if (index == 0) return Container();

          if (index != 0 && index % (_itemsInList + 1) == 0) {
            return Container(
              height: _heightContainer,
              alignment: Alignment.center,
              color: Colors.blue[(index * 20) % 1000],
              child: Text("Image #${(index + 1) ~/ 5}"),
            );
          }

          return SizedBox(height: _heightListTile, child: ListTile(title: Text("Item ${index}")));
        },
      ),
    );
  }
}

https://stackoverflow.com/questions/55358150/

相关文章:

dart - 我们如何在flutter中更改appbar背景颜色

dart - 在 TextInputType 更改后 Controller 重置的 Flutter

flutter - 它们在 flutter 中是什么意思 'cross axis' ?

dart - 构造函数可选参数

user-interface - Flutter slideTransition没有动画

dart - 如何在 Widget 构建方法中调用异步属性

dart - 如何调整 ShowDialog 子项的大小

android-studio - 如何使 Flutter 应用的 Navigation Drawer

android - Flutter 中的 ListView 居中

flutter - 无法在 flutter 中同步 build.gradle 中的依赖项