This commit is contained in:
vipg
2025-11-19 16:57:18 +08:00
parent 8a8dd48726
commit b2e89bf5bd

View File

@@ -64,7 +64,8 @@ class CountryData {
});
factory CountryData.fromJson(Map<String, dynamic> json) {
var itemsList = json['items'] as List;
// 关键修复处理items为null的情况转为空列表
var itemsList = json['items'] as List? ?? [];
List<Country> items = itemsList.map((i) => Country.fromJson(i)).toList();
return CountryData(
@@ -90,23 +91,22 @@ class _CountryPageState extends State<CountryPage> {
int _currentPage = 1;
final int _pageSize = 20;
bool _hasMoreData = true;
late ScrollController _scrollController; // 优化滚动控制器
late ScrollController _scrollController;
@override
void initState() {
super.initState();
_scrollController = ScrollController();
_scrollController.addListener(_onScroll); // 注册滚动监听
_scrollController.addListener(_onScroll);
_fetchCountries();
}
@override
void dispose() {
_scrollController.dispose(); // 释放资源
_scrollController.dispose();
super.dispose();
}
// 滚动监听处理加载更多
void _onScroll() {
if (_isLoading) return;
if (_hasMoreData &&
@@ -116,7 +116,6 @@ class _CountryPageState extends State<CountryPage> {
}
}
// 加载国家列表数据使用POST请求
Future<void> _fetchCountries({bool isRefresh = false}) async {
if (isRefresh) {
setState(() {
@@ -140,7 +139,6 @@ class _CountryPageState extends State<CountryPage> {
debugPrint('请求参数: page=$_currentPage, page_size=$_pageSize');
final dio = Dio();
// 使用POST请求通过data传递表单数据适配后端form接收方式
final response = await dio.post(
url,
data: {
@@ -149,7 +147,7 @@ class _CountryPageState extends State<CountryPage> {
'name': '',
'code': '',
'country_id': '',
'flag': '', // 新增国旗查询参数
'flag': '',
},
options: Options(
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
@@ -172,7 +170,6 @@ class _CountryPageState extends State<CountryPage> {
_countries.addAll(countryResponse.data.items);
}
// 检查是否还有更多数据
_hasMoreData = _countries.length < countryResponse.data.total;
_currentPage++;
_errorMessage = null;
@@ -223,13 +220,11 @@ class _CountryPageState extends State<CountryPage> {
}
}
// 下拉刷新
Future<void> _refresh() async {
debugPrint('触发下拉刷新');
await _fetchCountries(isRefresh: true);
}
// 加载更多
void _loadMore() {
if (!_isLoading && _hasMoreData) {
debugPrint('触发加载更多,当前页: $_currentPage');
@@ -309,7 +304,6 @@ class _CountryPageState extends State<CountryPage> {
final country = _countries[index];
return _buildCountryItem(theme, country);
} else {
// 加载更多指示器
return Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Center(
@@ -320,12 +314,11 @@ class _CountryPageState extends State<CountryPage> {
);
}
},
controller: _scrollController, // 使用优化后的滚动控制器
controller: _scrollController,
),
);
}
// 构建国家列表项(新增国旗显示)
Widget _buildCountryItem(ThemeData theme, Country country) {
return Column(
mainAxisSize: MainAxisSize.min,
@@ -344,7 +337,6 @@ class _CountryPageState extends State<CountryPage> {
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
children: [
// 国旗显示区域
Container(
width: 40,
height: 40,