如何根据listView项目在屏幕上的位置添加填充。例如,如果listView项目在屏幕中间,则希望将其填充增加10点,如果listView项目靠近屏幕顶部,则希望将其填充增加15点。
您可以通过将ScrollController
附加到ListView
并进行创意使用来实现此目的:
首先,您需要定义一个ScrollController
,它将用于获取ScrollController.offset
以确定列表的当前位置。然后,我添加了一堆变量来调整这个动态列表,同时保持其预期的功能:
class DynamicPadding extends StatefulWidget {
DynamicPadding({Key key,}) : super(key: key);
@override
_DynamicPaddingState createState() => _DynamicPaddingState();
}
class _DynamicPaddingState extends State<DynamicPadding> {
ScrollController _controller;
var _middlePadding = 10.0 ; // padding of centered items
var _edgesPadding = 15.0 ; // padding of non-centered items
var _itemSize = 100.0 ;
int _centeredItems = 3 ;
int _numberOfEdgesItems ; // number of items which aren't centered at any moment
int _aboveItems ; // number of items above the centered ones
int _belowItems ; // number of items below the centered ones
@override
void initState() {
_controller = ScrollController(); // Initializing ScrollController
_controller.addListener(_scrollListener); add a listener to ScrollController to update padding
super.initState();
}
_scrollListener() {
setState(() {});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.grey.shade200,
appBar: new AppBar(title: new Text('Dynamic Padding Example'),),
body: ListView.builder(
controller: _controller ,
itemCount: 20,
itemBuilder: (context, index) {
// This is how to calculate number of non-centered Items
_numberOfEdgesItems = ( (MediaQuery.of(context).size.height - _centeredItems*(_itemSize + 2*(_middlePadding))) ~/ (_itemSize + 2*(_edgesPadding)) ) ;
_aboveItems = ( ( (_controller.offset) / (_itemSize + 2*(_edgesPadding)) ) + _numberOfEdgesItems/2 ).toInt() ;
_belowItems = _aboveItems + _centeredItems ;
return Container(
padding: index >= _aboveItems && index < _belowItems ? EdgeInsets.all(_middlePadding) : EdgeInsets.all(_edgesPadding) ,
child: Card(
child: Container(
height: _itemSize,
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(index.toString(), style: TextStyle(fontSize: 36.0, fontWeight: FontWeight.bold)),
]
),
),
),
);
}),
);
}
}
ScrollController
和itemExtent
来检测滚动位置和项目位置。 - Saman