flutter Futurebuilder内部的页面视图.Builder引发错误

mi7gmzs6  于 2022-12-30  发布在  Flutter
关注(0)|答案(1)|浏览(128)

我对Flutter比较陌生,所以我有下面的代码,我一直在阅读futurebuilder,它似乎是最适合我的情况的构建器。

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

  @override
  State<CardCarousel> createState() => _CardCarouselState();
}

class _CardCarouselState extends State<CardCarousel> {
  List<String> imagePaths = [];

  @override
  void initState() {
    super.initState();
    _initImages();
  }

  Future<List<String>> _initImages() async {
    final manifestContent = await rootBundle.loadString('AssetManifest.json');
    final Map<String, dynamic> manifestMap = json.decode(manifestContent);
    List<String> imagePaths = manifestMap.keys
        .where((String key) => key.contains('assets/images/png/'))
        .where((String key) => key.contains('.png'))
        .toList();

    return imagePaths;
  }

  @override
  Widget build(BuildContext context) {
    final PageController controller = PageController();
    return FutureBuilder(
        future: _initImages(),
        builder: (context, AsyncSnapshot<List<String>> snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.done:
              if (snapshot.data == null) {
                return Text('NO IMAGES');
              } else {
                setState(() {
                  imagePaths = snapshot.data!;
                });
              }
              break;
            case ConnectionState.none:
              print('NONE');
              break;
            case ConnectionState.waiting:
              print('WAITING');
              break;
            case ConnectionState.active:
              print('active');
              break;
          }

          return PageView.builder(
              controller: controller,
              itemCount: imagePaths.length,
              itemBuilder: (_, int index) {
                return CustomCard(imageURL: imagePaths[index]);
              });
        });
  }
}

它会抛出以下错误:

This CardCarousel widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.

这是一个特定条目为空的示例吗?或者我应该添加更多的条件渲染?

suzh9iv8

suzh9iv81#

此处不应调用setState,因此请替换

if (snapshot.data == null) {
            return Text('NO IMAGES');
          } else {
            setState(() {
              imagePaths = snapshot.data!;
            });
          }

if (snapshot.data == null) {
            return Text('NO IMAGES');
          } else {
            imagePaths = snapshot.data!;
          }

相关问题