当用户滚动列表时,我希望列表中屏幕项目的顶部可见更改颜色。
我最接近的是插件 ScrollablePositionedList: https ://pub.dev/packages/scrollable_positioned_list
当我热重载时,列表中的第一项现在会改变颜色或顶部屏幕上的任何一项。但是当我滚动时,它们不会实时进行。
我真的很感激任何帮助。请在下面找到相关代码。提前致谢!
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:scrollviewexperiment/models/place_data.dart';
import 'package:scrollviewexperiment/widgets/place_tile.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
class PlacesList extends StatefulWidget {
@override
_PlacesListState createState() => _PlacesListState();
}
class _PlacesListState extends State<PlacesList> {
final ItemPositionsListener itemPositionsListener =
ItemPositionsListener.create();
ItemScrollController _itemScrollController = ItemScrollController();
int currentIndex = 0;
@override
void initState() {
super.initState();
currentVisibleIndex();
}
@override
Widget build(BuildContext context) {
return Consumer<PlaceData>(
builder: (context, placeData, child) {
return ScrollablePositionedList.builder(
itemCount: placeData.placeCount,
itemPositionsListener: itemPositionsListener,
itemBuilder: (context, index) {
final place = placeData.places[index];
return Card(
color: index == currentIndex ? Colors.blue : Colors.white,
elevation: 2.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
child: PlaceTile(
placeName: place.name,
distance: place.distance,
),
);
},
);
},
);
}
currentVisibleIndex() {
itemPositionsListener.itemPositions.addListener(() {
int min;
if (itemPositionsListener.itemPositions.value.isNotEmpty) {
min = itemPositionsListener.itemPositions.value
.where((ItemPosition position) => position.itemTrailingEdge > 0)
.reduce((ItemPosition min, ItemPosition position) =>
position.itemTrailingEdge < min.itemTrailingEdge
? position
: min)
.index;
print('Min Index $min');
currentIndex = min;
}
});
}
}