导航到另一个屏幕并在颤动中返回时,块状态会丢失

问题描述 投票:0回答:1

我使用 bloc 和 flutter 来处理业务逻辑等,代码工作正常,除了当我从主屏幕导航到另一个屏幕时,返回主屏幕后,来自 api 的所有数据都会丢失,它显示没有产品文本,除非我刷新 UI,任何帮助将不胜感激,谢谢


class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {


  @override
  void initState() {
    super.initState();
    BlocProvider.of<AppBloc>(context).add(UserInfoEvent());
    BlocProvider.of<ProductBloc>(context).add(GetProductsEvent("electronics"));
  }

  @override
  Widget build(BuildContext context) {
    return  SafeArea(
      child: Scaffold(
        body: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              BlocBuilder<AppBloc,AppState>(
                builder: (context,state){
                  if(state is UserInfoState){
                    UserModel? userModel = state.userModel;
                    return  Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(userModel!.fullName,style: Utils.getMedium().copyWith(fontSize: 20),),
                        const Spacer(),
                        CircleAvatar(
                          radius: 17,
                          backgroundColor: Colors.grey.shade200,
                          child: IconButton(onPressed: (){

                            Get.toNamed(AppRouting.cartPage);

                          }, icon: const Icon(Icons.add_shopping_cart_outlined,size: 15,)),
                        ),
                        const SizedBox(width: 10,),
                        CircleAvatar(
                          radius: 15,
                          child: Image.network(userModel.profileUrl,fit: BoxFit.cover,filterQuality: FilterQuality.high,),
                        )
                      ],
                    );
                  }
                  return Container();
                },
              ),
              const Divider(),
              const SizedBox(height: 25,),
              CarouselSlider(
                  items: Utils.banners.map((e){
                    return ClipRRect(
                      borderRadius: BorderRadius.circular(12),
                      child: Image.asset(e,fit: BoxFit.cover,),
                    );
                  }).toList(),
                  options: CarouselOptions(
                      viewportFraction: 1.0,
                      autoPlay: true,
                      autoPlayInterval: const Duration(seconds: 3)
                  )),
              const SizedBox(height: 20,),
              Text("Categories",style: Utils.getBold().copyWith(fontSize: 20),),
              const SizedBox(height: 20,),
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children: List.generate(Utils.categories.length, (index) {
                    return GestureDetector(
                      onTap: () {
                        BlocProvider.of<ProductBloc>(context).add(GetProductsEvent(Utils.categoriesNames[index].toLowerCase()));
                      },
                      child: Card(
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12),
                            side: const BorderSide(color: Colors.black87)),
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              SizedBox(
                                width: 20,
                                height: 20,
                                child: Center(
                                  child: Image.asset(Utils.categories[index], width: 40, height: 40),
                                ),
                              ),
                              const SizedBox(width: 10),
                              Text(Utils.categoriesNames[index].capitalize!),
                            ],
                          ),
                        ),
                      ),
                    );
                  }),
                ),
              ),
              const SizedBox(height: 20,),
              Expanded(
                  child: BlocBuilder<ProductBloc,AppState>(
                    builder: (context,state){
                      if(state is LOADING){
                        return  const Center(child: SpinKitFadingCube(color: Colors.blue,size: 20,),);
                      }
                      else if (state is ERROR){
                        return Center(child: Text('No Products',style: Utils.getBold().copyWith(fontSize: 25),),);
                      }
                      else if(state is GetProductsState){
                        List<Product>? data = state.list;
                        return GridView.builder(
                            restorationId: 'store_data',
                            shrinkWrap: true,
                            itemCount: data?.length,
                            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 2,
                              childAspectRatio: 0.85,
                            ),
                            itemBuilder: (context,index){
                              return GestureDetector(
                                onTap: (){
                                  Get.toNamed(AppRouting.detailsPage,arguments: { "productID" : data[index].id});
                                },
                                child: Card(
                                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12),
                                      side: const BorderSide(color: Colors.black26)),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      const SizedBox(height: 20,),
                                      Center(
                                        child: Stack(
                                          children: [
                                            CachedNetworkImage(
                                              imageUrl: data![index].image,
                                              height: 150,
                                              width: 150,
                                              imageBuilder: (context, imageProvider) {
                                                return Container(
                                                  decoration: BoxDecoration(
                                                    image: DecorationImage(image: imageProvider, fit: BoxFit.fill),
                                                  ),
                                                );
                                              },
                                              placeholder: (context, url) => const SizedBox(
                                                height: 140,
                                                width: 140,
                                                child: Center(
                                                  child: SpinKitFadingCube(
                                                    color: Colors.blue,
                                                    size: 20,
                                                  ),
                                                ),
                                              ),
                                              errorWidget: (context, url, error) => const Icon(Icons.error),
                                            ),
                                            Positioned(
                                              right: 0,
                                              top: 10,
                                              child: Container(
                                                width: 80,
                                                height: 30,
                                                decoration: BoxDecoration(
                                                    borderRadius: BorderRadius.circular(18),
                                                    color: Colors.red
                                                ),
                                                child: Center(
                                                  child: Text("50% OFF",style: Utils.getBold().copyWith(color: Colors.white),),
                                                ),
                                              ),
                                            )
                                          ],
                                        ),
                                      ),
                                      Padding(
                                        padding: const EdgeInsets.only(left: 8,right: 8,top: 4),
                                        child: Text(data[index].title,maxLines: 1,overflow: TextOverflow.ellipsis,
                                          style: Utils.getMedium().copyWith(fontSize: 18),),
                                      ),
                                      Padding(
                                        padding: const EdgeInsets.only(left: 8,right: 8),
                                        child: Text("\$${data[index].price}",style: Utils.getBold()
                                            .copyWith(color: Colors.blue,fontSize: 17),),
                                      )
                                    ],
                                  ),
                                ),
                              );
                            });
                      }
                      return Center(child: Text('No Products',style: Utils.getBold().copyWith(fontSize: 25),),);
                    },
                  ))
            ],
          ),
        ),
      ),
    );
  }
}
flutter bloc flutter-bloc
1个回答
-2
投票

问 Hitarth Chhuncha @hitarth 来自 优秀的网络世界

© www.soinside.com 2019 - 2024. All rights reserved.