如何使用flutter_bloc对JSON获取的Forecast模型数据按温度排序
解决方案
要实现列表默认按温度升序排列,只需在获取天气预报数据后对列表元素按温度排序,再传递给状态即可,具体修改如下:
1. 修改Bloc数据处理逻辑
在ForecastRequest事件的处理代码中,获取到响应数据后对列表进行升序排序:
on<ForecastRequest>((event, emit) async { emit(WeatherLoadInProgress()); try { final forecastResponse = await _forecastRepository.getForecast(event.cityName); // 复制原列表并按温度升序排序 final sortedList = List<ListElement>.from(forecastResponse.list) ..sort((a, b) => a.main.temp.compareTo(b.main.temp)); // 创建排序后的Forecast实例 final sortedForecast = Forecast(list: sortedList); emit(ForecastLoadSuccess(forecast: sortedForecast)); } catch (e) { print(e); emit(WeatherLoadFailure(error: e.toString())); } } );
代码说明
- 用
List<ListElement>.from复制原列表,避免修改原始响应数据 - 通过
sort方法结合compareTo,实现按温度从低到高排序(若需降序,调换a和b的位置即可) - 将排序后的列表传入新的
Forecast对象,确保状态中存储的是已排序的数据
2. UI层保持不变
原列表展示代码无需修改,直接使用状态中已排序的forecast.list即可:
return ListView.separated( padding: const EdgeInsets.all(8), itemCount: state.forecast.list.length, separatorBuilder: (BuildContext context, int index) => Divider(), itemBuilder: (BuildContext context, int index) { return ListTile( title: Text("${state.forecast.list[index].main.temp}", style:TextStyle(fontSize: 22)), subtitle: Text("${state.forecast.list[index].dtTxt}") ); } );
完成修改后,用户打开页面就能直接看到按温度升序排列的天气预报列表。
内容的提问来源于stack exchange,提问作者Texter
相关产品推荐
相关产品推荐

