我认为您可以使用Google Fuchsia Authors 制作的scrollable_positioned_list 包来实现这一点。
提供ScrollablePositionedList
了一个ItemPositionsListener
:
_itemPositionsListener.itemPositions.addListener(() {
final positions = _itemPositionsListener.itemPositions.value;
setState(() {
_topItem = positions.isNotEmpty ? positions.first.index : null;
});
});
完整的源代码
import 'package:flutter/material.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
);
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _nbItems = 6;
final _itemHeight = 200.0;
final _itemPositionsListener = ItemPositionsListener.create();
int _topItem = 0;
@override
void initState() {
super.initState();
_itemPositionsListener.itemPositions.addListener(() {
final positions = _itemPositionsListener.itemPositions.value;
setState(() {
_topItem = positions.isNotEmpty ? positions.first.index : null;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: List.generate(
_nbItems,
(index) => Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
padding: EdgeInsets.all(4.0),
decoration: _topItem == index
? BoxDecoration(
color: Colors.black26,
border: Border.all(color: Colors.black54),
)
: BoxDecoration(),
child: Text(
'S$index',
style: TextStyle(
fontWeight: _topItem == index
? FontWeight.bold
: FontWeight.normal,
),
),
),
),
),
),
Expanded(
child: ScrollablePositionedList.builder(
itemCount: _nbItems,
itemBuilder: (context, index) => SizedBox(
height: _itemHeight,
child: Card(
child: Text('Item $index'),
),
),
itemPositionsListener: _itemPositionsListener,
),
),
],
),
);
}
}