Home > OS >  How to get first item on screen of a listview while scroll?
How to get first item on screen of a listview while scroll?

Time:11-11

I'm creating a listview in which i'm adding an animation. the idea is that the transformation of the first item will be centered. and the the items below will be 45 deg from X axis. but the issue I'm facing is that when the list is scrolling and the first item is out of the screen i wanted to make the next index centered (0 deg from X axis). this goes on untill the last index / item is centered. how can i make this?

ListView.builder(
    itemCount: posts.length,
    itemBuilder: (context, index) {
      final item = posts[index];
      return Transform(
               transform: Matrix4.identity()..setEntry(3,2,0.001)..rotateX(index != 0 ? 45 : 0),
              child: Container(
                height: 200,
                width: 300,
                child: Center(
                   child: Text(index.toString())
                 )
               )
             );
              },
            )

CodePudding user response:

Try with ScrollController to get current position. Also here every item is having same height.

  final itemHeight = 200.0;
  int topIndex = 0;
  late final ScrollController constroller = ScrollController()
    ..addListener(() {
      final currentPoss = constroller.offset;
      topIndex = currentPoss ~/ itemHeight;
      setState(() {});
    });
return Transform(
  transform: Matrix4.identity()
    ..setEntry(3, 2, 0.001)
    ..rotateX(index == topIndex ? 0 : 45),

class TFA extends StatefulWidget {
  const TFA({super.key});

  @override
  State<TFA> createState() => _TFAState();
}

class _TFAState extends State<TFA> {
  final itemHeight = 200.0;
  int topIndex = 0;
  late final ScrollController constroller = ScrollController()
    ..addListener(() {
      final currentPoss = constroller.offset;
      topIndex = currentPoss ~/ itemHeight;
      setState(() {});
    });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: 44,
        controller: constroller,
        itemBuilder: (context, index) {
          return Transform(
            transform: Matrix4.identity()
              ..setEntry(3, 2, 0.001)
              ..rotateX(index == topIndex ? 0 : 45),
            child: Container(
              height: itemHeight,
              width: 300,
              child: Center(
                child: Text(
                  index.toString(),
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

  • Related