列表右边需要有一个a到z的英文状态栏,属于A的就在A的下面以此类推,像微信一样
时间: 2024-04-12 16:30:32 浏览: 13
要实现类似微信好友列表右侧的A-Z英文字母状态栏,可以使用`IndexedStack`和`ListView`来实现。这样可以让状态栏始终显示在好友列表的顶部。
以下是更新后的代码示例:
```dart
import 'package:flutter/material.dart';
class Friend {
final String name;
Friend(this.name);
}
class FriendListPage extends StatefulWidget {
@override
_FriendListPageState createState() => _FriendListPageState();
}
class _FriendListPageState extends State<FriendListPage> {
List<Friend> _friendList = [
Friend('Alice'),
Friend('张三'),
Friend('Bob'),
Friend('李四'),
];
List<String> _indexList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z'];
List<Friend> _filteredFriendList = [];
String _selectedLetter = '';
@override
void initState() {
super.initState();
_filterFriendList('');
}
void _filterFriendList(String letter) {
_selectedLetter = letter;
_filteredFriendList = _friendList
.where((friend) => friend.name.startsWith(letter))
.toList();
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('好友列表'),
),
body: Row(
children: [
Expanded(
child: ListView.builder(
itemCount: _indexList.length,
itemBuilder: (context, index) {
final letter = _indexList[index];
return InkWell(
onTap: () => _filterFriendList(letter),
child: Container(
alignment: Alignment.center,
height: 20,
color: _selectedLetter == letter ? Colors.blue : Colors.transparent,
child: Text(letter),
),
);
},
),
),
Expanded(
flex: 5,
child: IndexedStack(
index: 0,
children: [
ListView.builder(
itemCount: _filteredFriendList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_filteredFriendList[index].name),
);
},
),
],
),
),
],
),
);
}
}
void main() {
runApp(MaterialApp(
home: FriendListPage(),
));
}
```
在此更新后的代码中,我们使用了两个`Expanded`小部件,将屏幕分为两个部分。左侧是A-Z字母状态栏,右侧是好友列表。
- 我们在`_FriendListPageState`类中添加了一个`_indexList`列表,包含A到Z的字母。
- `_filterFriendList`函数被修改为过滤好友列表,并根据所选字母更新变量`_filteredFriendList`和`_selectedLetter`。
- 在构建方法中,我们在左侧使用`ListView.builder`显示字母状态栏,并通过点击事件调用`_filterFriendList`函数来过滤好友列表。
- 在右侧,我们使用`IndexedStack`小部件来显示过滤后的好友列表。`IndexedStack`只显示当前索引处的子小部件,我们在此处只显示一个`ListView.builder`,其中包含过滤后的好友。
这样,您就可以在好友列表右侧看到一个A-Z的字母状态栏,并且根据所选字母进行过滤。