I use in my application a list of posts, I would like to know on which item is the user to update a boolean of the post posts.hasBeenSeen = true.
List<PostModel> posts = snapshot.data.cast<PostModel>();
return ListView.builder(
itemCount: posts.length,
itemBuilder: (context, index)
{
return ChangeNotifierProvider.value(
value: posts[index],
child: PostItem(postModel: posts[index]));
},
);
Here for example I want that the boolean is true only for the post 1, because the post 2 has not been seen yet.
CodePudding user response:
You can use VisibilityDetector
from this package. If you wrap all your list items into it, you can detect which items are visible, also the percent of their visibility. So you can set your hasBeenSeen
value to true
for each post that at least once became 100% visible (or you can set a lower threshold if you like).
This is a simple example, based on the package's example:
import 'package:flutter/material.dart';
import 'package:visibility_detector/visibility_detector.dart';
void main() {
runApp(
MyApp(),
);
}
class MyApp extends StatelessWidget {
final List<String> items = List<String>.generate(1000, (i) => 'Post $i');
MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Posts',
home: SafeArea(
child: Scaffold(
appBar: AppBar(
title: const Text('Posts'),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return VisibilityDetector(
key: Key('postkey$index'),
onVisibilityChanged: (visibilityInfo) {
var visiblePercentage = visibilityInfo.visibleFraction * 100;
debugPrint(
'Post ${visibilityInfo.key} is $visiblePercentage% visible');
},
child: SizedBox(
height: 100,
child: ListTile(
title: Text(items[index]),
),
),
);
},
),
)));
}
}