我使用 bloc 进行状态管理以从 api 获取数据
FutureOr<void> fetchAllDrinksList(
GetAllDrinksList event, Emitter<HomeState> emit) async {
await apiRepository.getAllDrinks().then((value) {
emit(state.copyWith(
status: HomeStatus.success,
drinksList: value,
message: 'success',
));
}).onError((error, stackTrace) {
emit(state.copyWith(
status: HomeStatus.failure, message: error.toString()));
});
}
并显示到首页,像这样
BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) {
switch (state.status) {
case HomeStatus.initial:
return Center(
child: CircularProgressIndicator(),
);
case HomeStatus.failure:
return GestureDetector(
onTap: () {
context.read<HomeBloc>().add(GetAllDrinksList());
},
child: Center(child: Text(state.message.toString())),
);
case HomeStatus.success:
return Column(
children: [
GridView.builder(
physics: NeverScrollableScrollPhysics(),
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 40,
mainAxisSpacing: 20,
childAspectRatio: 0.7,
),
shrinkWrap: true,
padding: EdgeInsets.symmetric(
vertical: 30, horizontal: 25),
itemCount: state.drinksList.length,
itemBuilder: (context, index) {
DrinksModel drink = state.drinksList[index];
我有 ui 卡的其余代码用于显示饮料列表中的数据,但我收到 Flutter API 获取代码抛出“索引超出范围”的错误,我认为问题是 state.drinksList 的长度,但我使用 print 语句来调试项目列表,但我通过使用 state.drinksList[index].name
获取数据谢谢!
尝试将您的
column
封装在 Expanded
小部件或 flexible
中