In app development, lists are commonly used to display structured data, such as contact lists or address books. To enhance user experience and interaction, you need to implement a series of common list operation features. This topic focuses on introducing common functionalities such as list scrolling, list layout, list data updates, and list drag-and-drop, through a simple chat list example to demonstrate typical list operations and their corresponding code implementations.
List scrolling refers to the user scrolling vertically or horizontally to browse content that exceeds the current viewport. It is one of the most common interactions and is widely used in scenarios such as contact lists, product catalogs, and news articles.
List scrolling is primarily controlled by binding a Scroller object to the scroller parameter of the List component, enabling precise scrolling management.
private scroller: Scroller = new Scroller();
@StorageProp('topRectHeight') topRectHeight: number = 0;
// ...
List({ space: 20, initialIndex: this.arr.length - 1, scroller: this.scroller }) {
// ...
} Based on different scroll positions, this topic introduces three common forms of list scrolling: scrolling to the bottom, scrolling by a specified index, and scrolling by a specified offset. The implementation methods are as follows:
Scrolling to the bottom: This can be implemented using the initialIndex or scrollToIndex API.
List({ space: 20, initialIndex: this.arr.length - 1, scroller: this.scroller }) {
ForEach(this.arr, (item: number) => {
ListItem() {
// ...
}
.borderRadius(16)
.backgroundColor(0xDCDCDC)
}, (item: string) => item)
} this.scroller.scrollToIndex(this.arr.length - 1);
Note: While both scrollToIndex and initialIndex can achieve scrolling to the bottom (the last ListItem), if the ListItem height is too large, the very bottom cannot be displayed perfectly. This can be addressed by using scrollEdge() to implement scrolling to the list bottom.
this.scroller.scrollEdge(Edge.Bottom);
Scrolling to a specified index: Use the scrollToIndex() API to scroll to the specified index in the list array.
When using APIs like scrollToIndex(), if the size of ListItem components changes dynamically during scrolling, the obtained currentOffset may be inaccurate, preventing precise navigation to the target position. To ensure accuracy, use childrenMainSize() to assign a fixed height to ListItem components. This property provides the List component with information about the size of all child components along the main axis, ensuring the accuracy of the scroll position.
Scrolling by a specified offset: Use the scrollTo() API to configure the vertical and horizontal offsets, and animation options.
Button('scroll 200')
.height('5%')
.onClick(() => {
let curve = curves.interpolatingSpring(10, 1, 228, 30);
const yOffset: number = this.scroller.currentOffset().yOffset;
this.scroller.scrollTo({ xOffset: 0, yOffset: yOffset + 200, animation: { duration: 1000, curve: curve } })
})
The offset here is relative to the top of the component, not relative to the currently displayed item.
When there are excessive list items, it is often necessary to listen for the scroll offset of the list to display additional information or auxiliary functions. For example, when selecting products, users may wish to return to the top after scrolling a certain distance, which requires scroll event listening. This can be achieved by executing scroller.currentOffset() within the onWillScroll() or onDidScroll() methods of the List component to listen for the displacement offset in real-time.
.onWillScroll(() => {
// Trigger before scrolling component scrolling.
console.info('currentOffset:' + this.scroller.currentOffset().yOffset)
})
.onDidScroll(() => {
// Triggered when scrolling components scroll.
console.info('currentOffset:' + this.scroller.currentOffset().yOffset)
})
The offset returned by scroller.currentOffset() is relative to the top of the component, not to the currently displayed item. To obtain the offset delta of a specific scroll operation, use the callback parameters of the onWillScroll() or onDidScroll() APIs. The offset returned by onWillScroll() represents the calculated intended scroll offset, not the final actual scroll offset. You can specify the intended scroll offset for Scroll through the return value of this callback. For details, see Setting the Scroller.
Nested scrolling refers to a scrolling mechanism where multiple scrollable containers are nested within each other and can cooperate seamlessly. For example, in a mobile app, the entire page may support vertical scrolling, while a child component (for example, tab content, comment section, and image list) may also support independent scrolling. Based on the interacting components, nested scrolling primarily includes: Scroll component nested with List component, Web component nested with List component, and List component nested with List component.

If the onScrollFrameBegin() event and scrollBy() method are used to implement nested scrolling, set the EdgeEffect() property of the scrollable child component to None. For example, if a List is nested in the Scroll component, edgeEffect of the List must be set to EdgeEffect.None.
Scrolling effects refer to how list items smoothly enter and exit the viewport when the user scrolls vertically or horizontally to browse content beyond the current viewport, along with any accompanying visual effects such as unilateral rebound, disabling scrolling during scroll operations, or swiping list items to the left.
Unilateral rebound effect
Unilateral rebound occurs when the user scrolls to one end of a scrollable area and continues applying force, resulting in a visual rebound effect at that end. For example, to implement a top rebound effect, two approaches are available:
List({ space: 20, initialIndex: 0, scroller: this.scroller }) {
// ...
}
.width('90%')
.scrollBar(BarState.Off)
.onDidScroll(() => {
const y = this.scroller.currentOffset().yOffset;
this.isTop = y <= 0;
})
.edgeEffect(this.isTop ? EdgeEffect.Spring : EdgeEffect.None) .edgeEffect(this.isTop ? EdgeEffect.Spring : EdgeEffect.None)
.onScrollIndex((firstIndex: number) => {
this.isTop = firstIndex === 0;
console.info('firstIndex:' + firstIndex + ',' + this.isTop)
}) If the content size of the List component is smaller than the component itself, scrolling is disabled by default. To enable scrolling, set edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true }).

Disabling scrolling during scroll operations: Scrolling can be disabled by calling enabled(false). However, if scrolling was triggered by inertia, the List may still continue to scroll for a short distance. To completely disable both manual and inertial scrolling, use either of the following methods:
.onScrollFrameBegin((offset: number, state: ScrollState) => {
return { offsetRemain: 0 } // If the return value is set to 0, it means that there will be no scrolling.
}) Left-swipe features of list items: To implement left-swipe features (such as swipe-left-to-delete and swipe-left-to-pin) on list items, add the SwiperAction component to the ListItem. For specific implementation and sample code, see "Swipe Left to Delete or Pin an Item" in Case 1: Implementing a Simple Chat List.
Circular scrolling: When users scroll to the end or beginning of the list, the list automatically loops back to the start or end. For example, to implement a horizontally scrollable circular list, use the onScrollFrameBegin event to calculate the sum of the current scroll offset and the impending scroll offset. Compare this value with the total width of the list items to determine whether the user is swiping left or right, and calculate the actual required scroll offset for the list.
.onScrollFrameBegin((offset: number, state: ScrollState) => {
let currentOffset = this.scroller.currentOffset().xOffset;
let newOffset = currentOffset + offset;
let totalWeight = 220 * 10; // The total width of LIST.
if (newOffset < totalWeight * 0.5) {
newOffset += totalWeight;
} else if (newOffset > totalWeight * 2.5) {
newOffset -= totalWeight;
}
return { offsetRemain: newOffset - currentOffset };
}) 
List layout refers to the arrangement of a set of similar or related list items (such as messages and products) based on data content or usage scenarios, following specific organizational patterns to enable users to quickly identify and interact with the items.
The manner in which the list content is displayed directly impacts users' ability to quickly access information, influencing both visual experience and interaction efficiency. Key techniques include sidebar indexing, bottom spacing, sticky headers, and edge blur effects. Details and implementation methods are as follows:
Sidebar Indexing: Implemented by listening for the onScrollIndex event of the List component. The right index bar requires the use of the AlphabetIndexer component. For details, see Handling Scroll Position Changes.
Bottom spacing: Implemented by using contentEndOffset to set an offset at the end of the content area. When the list is scrolled to the end, a specified distance is maintained between the list content and the boundary of the display area.
Sticky headers/footers: The sticky property of the List component, used in conjunction with the ListItemGroup component, determines whether the header component exhibits a sticky-top effect or the footer component exhibits a sticky-bottom effect. Set the sticky property of the List component to StickyStyle.Header to enable sticky headers. To support sticky footers, initialize the footer component of ListItemGroup via the footer parameter and set the sticky property to StickyStyle.Footer. For details, see Adding a Sticky Header.
Edge blur effect: For example, to achieve a fading effect at the top and bottom of the List component, add an overlay to List and apply a blur gradient effect using the linearGradient property.
@Builder
overlayBuilder() {
Stack().width('100%').height('100%')
.linearGradient({
direction: GradientDirection.Bottom, // Gradient direction.
colors: [[0x00000000, 0.0], [0xB3000000, 1.0]]
})
.blendMode(BlendMode.DST_IN, BlendApplyType.OFFSCREEN)
}
build() {
NavDestination() {
List({ space: 20, initialIndex: 0 }) {
ForEach(this.arr, (item: number) => {
ListItem() {
Text('' + item)
.width('100%')
.height(100)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(16)
.backgroundColor(0xDCDCDC)
}
.borderRadius(16)
.backgroundColor(0xDCDCDC)
}, (item: string) => item)
}
.overlay(this.overlayBuilder()) 
Collapsing and expanding: The collapse and expand functionality for list items is widely used in scenarios such as displaying information lists or forms. By changing the state of a ListItem, the expansion state of each list item can be controlled, with animation effects during expanding and collapsing implemented using animation and animateTo. For details, see Collapsing and Expanding.
Implementing list data updates typically involves three aspects: the refresh mechanism, adding/removing items, and maintaining the visible content position during refresh. The corresponding technical descriptions and implementation approaches are detailed below.
List refresh refers to dynamically updating, replacing, or partially refreshing list content based on a new data source without reloading the entire page or component. Main methods include:
Pull-up loading: Add a LoadingProgress() component at the bottom of the list to display a loading animation. Use the onScrollIndex() callback to determine whether the display area has reached the bottom, and load more data when it does. The sample code is as follows:
List({ space: 20 }) {
ForEach(this.arr, (item: number) => {
ListItem() {
Text('' + item)
.width('100%')
.height(100)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(16)
.backgroundColor(0xDCDCDC)
}
}, (item: string) => item)
ListItem() {
Row() {
LoadingProgress().height(32).width(48)
Text('Loading')
}
}
.width('100%')
.height(64)
}
.width('90%')
.onScrollIndex((start: number, end: number) => {
if (end > this.arr.length) {
setTimeout(() => {
for (let i = 0; i < 5; i++) {
this.arr.push(this.arr.length);
}
})
}
}) Pull-to-refresh: Use the Refresh container for pull-down operations and bind the container component that displays refresh animation effects. For details about the implementation solution and sample code, see "Loading More Chat Records upon Pull-Down Gestures" in Case 1: Implementing a Simple Chat List.
Horizontal scroll refresh: Since Refresh does not support horizontal swipe interactions, wrap the Refresh component in a Column container and set the rotate property of the Column container to 90 degrees.
Column() {
Refresh({ refreshing: $$this.isRefreshing }) {
List({ space: 10 }) {
ForEach(this.arr, (item: number) => {
ListItem() {
Text('' + item)
.width(300)
.height(80)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(16)
.backgroundColor(0xFFFFFF)
.translate({ x: (80 - 300) / 2 })
.rotate({
x: 0,
y: 0,
z: 1,
centerX: '50%',
centerY: '50%',
angle: 90
})
}
.width(80)
.height(300)
}, (item: string) => item)
}
.width(300)
.height(300)
.alignListItem(ListItemAlign.Center)
.scrollBar(BarState.Off)
}
.onRefreshing(() => {
setTimeout(() => {
this.isRefreshing = false;
}, 2000)
})
.backgroundColor(0xDCDCDC)
.refreshOffset(64)
.pullToRefresh(true)
}
.justifyContent(FlexAlign.Center)
.width('100%')
.height('100%')
.rotate({
x: 0,
y: 0,
z: 1,
centerX: '50%',
centerY: '50%',
angle: -90
}) 
Partial data refresh: Modify the data source of a single ListItem.
Button('Partial_Refresh')
.height('5%')
.margin({ top: 8, bottom: 8 })
.onClick(() => {
this.arr[0] += 10;
}) Adding and deleting list items allows users to dynamically insert new items or delete existing ones from the list, typically accompanied by data updates and UI refreshes. Use methods such as Push(), Pop(), or splice() on arrays to implement operations like inserting list items, deleting list items, or removing child elements of a ListItem.
public addData(index: number, data: TextClass): void {
this.dataArray.splice(index, 0, data);
this.notifyDataAdd(index);
}
public pushData(data: TextClass): void {
this.dataArray.push(data);
this.notifyDataAdd(this.dataArray.length - 1);
} Maintaining visible content position ensures that content currently being viewed by the user is not replaced or disappears due to data updates, UI refreshes, or component re-rendering during list scrolling. For example, in dynamically updated lists (for example, chat messages, task status updates, and stock quotes), reloading the entire list on every update may cause the user's viewed content to be pushed off-screen or disappear, disrupting the experience. To address this requirement, two main solutions are available:
Solution 1: Use maintainVisibleContentPosition to specify whether to maintain the visible content's position when data is inserted or deleted outside the display area of the component. Note that this solution only takes effect in the lazy data loading (LazyForEach) scenario.
List({ space: 3 }) {
LazyForEach(this.data, (item: TextClass) => {
ListItem() {
Row() {
Text(item.message).fontSize(20)
}
.height(50)
.margin({ left: 10, right: 10 })
}
}, (item: TextClass) => JSON.stringify(item))
}
.width('100%')
.height('100%')
.scrollBar(BarState.Off)
.maintainVisibleContentPosition(true) 
Solution 2: Add a scroller controller to List to scroll back to the original position using this.scroller.scrollToIndex. For details, see How do I enable a list to scroll back to the current display position after a pull-to-refresh operation.
List dragging refers to the interaction where users long-press or tap and drag a ListItem to move it to another position or area. This is commonly used for adjusting item priority or sorting items. By using the List component's drag methods onItemDragStart() and onItemDragMove(), the dragged ListItem can be handled during drag initiation and movement. When dragging ends, the ListItem is inserted at the new position or area. For details about the implementation solution and sample code, see "Dragging and Sorting Messages" in Case 1: Implementing a Simple Chat List.
This section includes two cases: implementing a simple chat list and a common list flow. The simple chat list example is used to demonstrate common list operations, implementation solutions, and sample code.
When to Use
A typical chat UI consists of a contact message list and a chat window. The contact list UI primarily supports the following interactions:
The chat window includes the following functionalities:

Message Badges
Using the Badge component within a ListItem enables adding markers to the list item. Badge is a container component that can be attached to a single component for information tagging. For example, when implementing the Image component for presenting the contact avatar of a list item, use it as a child component of Badge. In the Badge component, the count and position parameters are used to set the number of notifications and the position to display the badge, respectively. You can also use the style parameter to spruce up the badge.

How to Implement
Define a variable isNewMessage to identify whether a list item requires a badge. Then, use the Badge component to add the marker functionality to the list item.
Sample Code
if (item.isNewMessage) {
// The Badge component can be used to add tags to list items.
Badge({
value: '',
position: BadgePosition.RightTop,
style: { badgeSize: 8, badgeColor: '#FA2A2D' }
}) {
Image(item.image)
.width(48)
.height(48)
}
} else {
Image(item.image)
.width(48)
.height(48)
} Swipe Left to Delete or Pin an Item

How to Implement
Use the SwipeAction component to enable left-swiping on a ListItem to display a component. Implement a itemEnd component to display the content in the left-swipe area, and bind it to SwipeAction.
Sample Code
@Builder
itemEnd(item: Item, index: number) {
Row() {
Image($r(item.isTop ? 'app.media.up_off' : 'app.media.up_on'))
.width(24)
.height(24)
.margin({ right: 8 })
.onClick(() => {
this.toggleTop(item);
})
Image($r('app.media.delete'))
.width(24)
.height(24)
.onClick(() => {
this.sortedList.splice(index, 1);
})
}
.padding(4)
.height('100%')
.backgroundColor('#F1F3F5')
.justifyContent(FlexAlign.SpaceEvenly)
} .swipeAction({
end: {
builder: () => {
this.itemEnd(item, index);
},
actionAreaDistance: 56,
onAction: () => {
this.getUIContext().animateTo({ duration: 1000 }, () => {
this.sortedList.splice(index, 1);
})
}
},
edgeEffect: SwipeEdgeEffect.Spring
}) Jumping to a Specific Position After Scrolling

How to Implement
Taking jumping to the top after scrolling as an example. In the onWillScroll() callback, use the currentOffset() API of the Scroll component to obtain the current scroll offset. Compare the offset with a predefined threshold value. If the threshold is exceeded, display a button. When the button is tapped, call scrollToIndex(0) to jump to the top.
Sample Code
.onWillScroll(() => {
if (this.scroller.currentOffset().yOffset > 100) {
this.isFlag = true;
} else {
this.isFlag = false;
}
}) if (this.isFlag) {
Image($r('app.media.arrow_up_circle_fill'))
.width(36)
.height(36)
.margin({ right: 10, bottom: 10 })
.onClick(() => {
this.scroller.scrollToIndex(0, true);
this.isFlag = false;
})
} Dragging and Sorting Messages

How to Implement
Use the drag methods onItemDragStart() and onItemDragMove() of the List component. The main steps are as follows:
.onItemDragStart((event: ItemDragInfo, itemIndex: number) => {
// Triggered when starting to drag and drop list elements.
this.dragItem = this.sortedList[itemIndex];
return this.dragFloatView(this.sortedList[itemIndex]);
}) .onItemDragMove((event: ItemDragInfo, itemIndex: number, insertIndex: number) => {
// Triggered when dragging and moving within the range of a list element.
this.getUIContext().animateTo({ duration: 200, curve: Curve.Linear }, () => {
let deleteIndex = this.sortedList.indexOf(this.dragItem);
this.sortedList.splice(deleteIndex, 1);
this.sortedList.splice(insertIndex, 0, this.dragItem);
})
}) @Builder
dragFloatView(item: Item) {
Row() {
if (item.isNewMessage) {
Badge({
value: '',
position: BadgePosition.RightTop,
style: { badgeSize: 8, badgeColor: '#FA2A2D' }
}) {
Image(item.image)
.width(48)
.height(48)
}
} else {
Image(item.image)
.width(48)
.height(48)
}
Row() {
Column() {
Text(item.name)
.fontSize(16)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 8 })
.textAlign(TextAlign.Start)
Text(item.message[item.message.length - 1].msg)
.fontSize(16)
.maxLines(1)
.constraintSize({ maxWidth: '70%' })
.textOverflow({ overflow: TextOverflow.Ellipsis })
}
.height('100%')
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Start)
Text(item.time)
.fontSize(12)
.margin({ bottom: 20 })
.fontColor(item.isTop ? Color.Black : Color.Gray)
}
.width('80%')
.justifyContent(FlexAlign.SpaceBetween)
}
.width('100%')
.height(72)
.backgroundColor(item.isTop ? '#4497FF' : 'rgba(240,240,240,1)')
.justifyContent(FlexAlign.SpaceAround)
} .visibility(item == this.dragItem ? Visibility.Hidden : Visibility.Visible)
Automatically Scrolling to the Bottom on Initialization

How to Implement
Setting the initialIndex parameter to the maximum length of the message list only displays the last message initially. However, if the last message item is exceptionally long, the view may only show content starting from the top of that item, failing to reveal the very bottom of the conversation history. To guarantee the viewport reaches the absolute bottom, utilize the onAppear() callback, which is triggered after the List component is mounted and rendered. Within this callback, invoke scrollEdge(Edge.Bottom) to programmatically scroll to the very end of the list.
Sample Code
List({ space: 10, scroller: this.scroller, initialIndex: this.itemInfo.message.length - 1 }) {
ForEach(this.showItemMessage, (item: messageObj, index: number) => {
ListItem() {
if (item.sender === 'others') {
Row() {
Image(this.itemInfo.image)
.width(36)
.height(36)
.margin({ right: 8 })
Text(item.msg)
.fontSize(16)
.constraintSize({ maxWidth: '70%' })
.backgroundColor('#F1F3F5')
.borderRadius(12)
.padding({
top: 8,
bottom: 8,
left: 12,
right: 12
})
}
.width('100%')
.constraintSize({ minHeight: 48 })
.justifyContent(FlexAlign.Start)
} else {
Row() {
Text(item.msg)
.fontSize(16)
.backgroundColor('#F1F3F5')
.borderRadius(12)
.padding({
top: 8,
bottom: 8,
left: 12,
right: 12
})
Image($r('app.media.Public_avatar'))
.width(36)
.height(36)
.margin({ left: 8 })
}
.width('100%')
.height(48)
.justifyContent(FlexAlign.End)
}
}
})
}
.onAppear(() => {
// Initialize display to the bottom.
this.scroller.scrollEdge(Edge.Bottom);
}) Loading More Chat Records upon Pull-Down Gestures

How to Implement
Wrap the List component with a Refresh container component to enable pull-to-refresh functionality. When the user pulls down and the list enters the refresh state, the onRefreshing() callback is triggered. Implement the data update operation within this callback to refresh the page content.
Sample Code
Refresh({ refreshing: $$this.isRefreshing }) {
List({ space: 10, scroller: this.scroller, initialIndex: this.itemInfo.message.length - 1 }) {
ForEach(this.showItemMessage, (item: messageObj, index: number) => {
ListItem() {
if (item.sender === 'others') {
Row() {
Image(this.itemInfo.image)
.width(36)
.height(36)
.margin({ right: 8 })
Text(item.msg)
.fontSize(16)
.constraintSize({ maxWidth: '70%' })
.backgroundColor('#F1F3F5')
.borderRadius(12)
.padding({
top: 8,
bottom: 8,
left: 12,
right: 12
})
}
.width('100%')
.constraintSize({ minHeight: 48 })
.justifyContent(FlexAlign.Start)
} else {
Row() {
Text(item.msg)
.fontSize(16)
.backgroundColor('#F1F3F5')
.borderRadius(12)
.padding({
top: 8,
bottom: 8,
left: 12,
right: 12
})
Image($r('app.media.Public_avatar'))
.width(36)
.height(36)
.margin({ left: 8 })
}
.width('100%')
.height(48)
.justifyContent(FlexAlign.End)
}
}
})
}
.onAppear(() => {
// Initialize display to the bottom.
this.scroller.scrollEdge(Edge.Bottom);
})
.scrollBar(BarState.Off)
.contentEndOffset(8)
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
.refreshOffset(64)
.pullToRefresh(true)
.onRefreshing(() => {
setTimeout(() => {
this.getLastTenElements(this.itemMessage);
this.isRefreshing = false;
}, 1500)
}) Adding New Chat Records

How to Implement
The chat message input is captured via the TextInput component. The new message is then added to the chat history using the push() method for appending list items.
Sample Code
TextInput({ placeholder: 'input your word...', text: this.inputMessage })
.height(40)
.width(200)
.margin({
left: 12,
right: 12
})
.onBlur(() => {
this.scroller.scrollEdge(Edge.Bottom);
})
.onChange((value) => {
this.inputMessage = value;
}) When the send icon is tapped, use the push() method to add the input message to the itemMessage array (data source of List); call scrollEdge(Edge.Bottom) to scroll List to its bottom; clear the content of the text box.
Image(this.inputMessage === '' ? $r('app.media.send_off') : $r('app.media.send_on'))
.width(28)
.height(28)
.onClick(() => {
if (this.inputMessage.trim() === '') {
return;
}
this.itemMessage.push({
sender: 'myself',
msg: this.inputMessage
});
this.showItemMessage = this.itemMessage.slice(-10);
this.scroller.scrollEdge(Edge.Bottom);
this.inputMessage = '';
}) The list stream is a layout form that arranges content in units of rows. Each row of list items efficiently displays structured information through combinations of text, images, and other forms. When the content of list items exceeds the screen size, provide the scrolling functionality. For details about the scenarios, see Common List Operations.