How do I add padding to a listView item based on its position on the screen. For example, If a listView item is in the middle of the screen, I would like to increase its padding by 10 points, If the listView item is near the top of the screen I would like to increase its padding by 15 points.
Asked
Active
Viewed 4,526 times
3
-
you can use `ScrollController` and `itemExtent` for detect scroll position and item position. – Saman Mar 26 '19 at 18:17
1 Answers
5
You can achieve this by attaching a ScrollController
to your ListView
and use it creatively :
First you need to define a ScrollController
which will be used to get the ScrollController.offset
to determine the list current position. Then I added a bunch of variable to adjust this dynamic list while keeping its intended functionality:
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)),
]
),
),
),
);
}),
);
}
}

Mazin Ibrahim
- 7,433
- 2
- 33
- 40