无状态小部件内单个小部件的setState

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

我确实有一个 StatelessWidget 名称

MyImagesPage
,它包含各种 StatelessWidget,我确实有一个想要更新的特定小部件,并且我尝试使用
StatefulBuilder
,但它不起作用。 这是我的代码片段。

class MyImagesPage extends StatelessWidget {
  const MyImagesPage({super.key});

  @override
  Widget build(BuildContext context) {
    return StatefulBuilder(
      builder: (context, setState) {
        return CarouselSlider(
          carouselController: controller,
          options: CarouselOptions(
              height: MediaQuery.of(context).size.height,
              viewportFraction: 1.0,
              enlargeCenterPage: true,
              aspectRatio: 2.0,
              pageSnapping: true,
              enableInfiniteScroll: false,
              onPageChanged: (index, reason) {
                setState(() {
                  currentSlide = index;
                  print("currentSlide: $currentSlide");
                });
              }
              // autoPlay: false,
              ),
          items: validatedImageList
              .map((item) => Container(
                  decoration: const BoxDecoration(
                    borderRadius: BorderRadius.all(
                      Radius.circular(10),
                    ),
                  ),
                  child: ClipRRect(
                    borderRadius: const BorderRadius.all(
                      Radius.circular(10),
                    ),
                    child: Image.file(
                      File(item.path),
                      fit: BoxFit.cover,
                      height: MediaQuery.of(context).size.height,
                    ),
                  )))
              .toList(),
        );
      },
    );
  }
}

我确实有一个按钮可以触发图像拾取事件

ElevatedButton(
     child: const Text('Select Image'),
     onPressed: () {
        FunctionHelper.selectImagesFunction(
           context,
           imageFileList,
           validatedImageList,
           invalidFileSizeImageList,
           imagePicker,
           stateSet,
           );
           Navigator.of(context).pop();
   });
and here is the code of my ``FunctionHelper`` class.
class FunctionHelper {
  static selectImagesFunction(BuildContext context, List<XFile> imageFileList, List<XFile> validatedImageList, List<XFile> invalidFileSizeImageList,
      ImagePicker imagePicker) async {
    final List<XFile> selectedImages = await imagePicker.pickMultiImage(
      imageQuality: 60,
    );
    if (selectedImages.isNotEmpty) {
      imageFileList.addAll(selectedImages);
    }
    if (imageFileList.length >= 7) {
      // ignore: use_build_context_synchronously
      Utils.animatedSnackbar(
          context: context,
          mobileSnackBarPosition: MobileSnackBarPosition.top,
          snackBarTitle: "Ops! You selected more than 6",
          snackBarType: AnimatedSnackBarType.error);
    } else {
      for (var x in imageFileList) {
        const maxFileSizeInBytes = 3 * 1048576;
        var imagePath = await x.readAsBytes();
        var fileSize = imagePath.length; // filesize of every imaages looped in the list.
        if (x.path.endsWith(".jpg") || x.path.endsWith(".png") || x.path.endsWith(".jpeg") || x.path.endsWith(".gif")) {
          print("allowed: .jpg / .jpeg / .png / .gif ");
          if (fileSize <= maxFileSizeInBytes) {
            print("image name: ${x.name} and image size: ${filesize(fileSize)} and maxFileSize: ${filesize(maxFileSizeInBytes)}");
            validatedImageList.add(x);
          } else {
            print("INVALID! image name: ${x.name} and image size: ${filesize(fileSize)} and maxFileSize: ${filesize(maxFileSizeInBytes)}");
            invalidFileSizeImageList.add(x);
          }
        } else {
          print("not allowed with no: .jpg / .jpeg / .png / .gif ");
        }
      }
    }
    
  }

我正在考虑是否只提取 StatefulBuilder 下的代码,并为该单个小部件创建一个 StatefulWidget 以用于查看图像。

flutter dart setstate imagepicker
1个回答
0
投票

您的方法是构建整个屏幕。因此,只需将无状态小部件转换为有状态小部件即可。 但这对于状态管理来说不是一个好的做法

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

  @override
  State<MyImagesPage> createState() => _MyImagesPageState();
}

class _MyImagesPageState extends State<MyImagesPage> {
  @override
  Widget build(BuildContext context) {
    return CarouselSlider(
          carouselController: controller,
          options: CarouselOptions(
              height: MediaQuery.of(context).size.height,
              viewportFraction: 1.0,
              enlargeCenterPage: true,
              aspectRatio: 2.0,
              pageSnapping: true,
              enableInfiniteScroll: false,
              onPageChanged: (index, reason) {
                setState(() {
                  currentSlide = index;
                  print("currentSlide: $currentSlide");
                });
              }
              // autoPlay: false,
              ),
          items: validatedImageList
              .map((item) => Container(
                  decoration: const BoxDecoration(
                    borderRadius: BorderRadius.all(
                      Radius.circular(10),
                    ),
                  ),
                  child: ClipRRect(
                    borderRadius: const BorderRadius.all(
                      Radius.circular(10),
                    ),
                    child: Image.file(
                      File(item.path),
                      fit: BoxFit.cover,
                      height: MediaQuery.of(context).size.height,
                    ),
                  )))
              .toList(),
        );
   
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.