我对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.
这是一个特定条目为空的示例吗?或者我应该添加更多的条件渲染?
1条答案
按热度按时间suzh9iv81#
此处不应调用
setState
,因此请替换与