如何根据列表在屏幕上的位置向列表视图项目添加填充。例如,如果listView项目位于屏幕中间,我想将其填充增加10点,如果listView项目位于屏幕顶部附近,我希望将其填充增加15点。>
答案 0 :(得分:0)
您可以通过将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)),
]
),
),
),
);
}),
);
}
}