Flutter Web/Dart使用survey_kit时如何获取CurrentStep值
Flutter survey_kit 获取currentStep实现动态关联图片
直接通过BuildContext查找PresentingSurveyState即可拿到当前步骤,不需要修改第三方库源码,以下是可直接复用的实现:
基础实现代码
import 'package:flutter/material.dart'; import 'package:survey_kit/survey_kit.dart'; class DynamicImageSurveyPage extends StatefulWidget { const DynamicImageSurveyPage({super.key}); @override State<DynamicImageSurveyPage> createState() => _DynamicImageSurveyPageState(); } class _DynamicImageSurveyPageState extends State<DynamicImageSurveyPage> { Step? currentSurveyStep; // 提前配置步骤和对应图片的映射关系 final Map<String, String> stepImageMap = { 'welcome_step': 'assets/images/welcome_banner.png', 'basic_info_step': 'assets/images/info_tip.png', 'satisfaction_step': 'assets/images/satisfaction_tip.png', 'submit_step': 'assets/images/submit_tip.png', }; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('调研问卷')), body: Column( children: [ // 动态图片展示区 if (currentSurveyStep != null && stepImageMap.containsKey(currentSurveyStep!.id)) SizedBox( height: 180, width: double.infinity, child: Image.asset( stepImageMap[currentSurveyStep!.id]!, fit: BoxFit.cover, ), ), // 问卷主体区 Expanded( child: Builder( builder: (surveyContext) { // 查找Survey对应的State final surveyState = surveyContext.findAncestorStateOfType<PresentingSurveyState>(); // 监听步骤变化触发UI更新 surveyState?.addListener(() { if (mounted && surveyState.currentStep != currentSurveyStep) { setState(() { currentSurveyStep = surveyState.currentStep; }); } }); // 初始化首屏加载时的当前步骤 WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted && currentSurveyStep == null) { setState(() { currentSurveyStep = surveyState?.currentStep; }); } }); return SurveyWidget( survey: yourSurveyConfig, // 替换为你自己的问卷配置实例 onResult: (SurveyResult result) { // 替换为你的问卷提交逻辑 debugPrint('问卷提交完成'); }, ); }, ), ), ], ), ); } }
简化无状态写法
如果不想手动维护状态,可以直接用AnimatedBuilder绑定surveyState,步骤变化时自动刷新,代码更简洁:
Expanded( child: Builder( builder: (context) { final surveyState = context.findAncestorStateOfType<PresentingSurveyState>(); return Column( children: [ if (surveyState != null) AnimatedBuilder( animation: surveyState, builder: (_, __) { final currentStep = surveyState.currentStep; if (stepImageMap.containsKey(currentStep?.id)) { return Image.asset(stepImageMap[currentStep!.id]!, height: 180, fit: BoxFit.cover); } return const SizedBox.shrink(); }, ), Expanded( child: SurveyWidget( survey: yourSurveyConfig, onResult: (result) => debugPrint('提交成功'), ), ), ], ); }, ), )
注意事项
- 别直接在Scaffold的根context里找
PresentingSurveyState,必须用Builder包裹SurveyWidget拿到子树的context,不然会找不到对应State返回null - 给surveyState加监听/用AnimatedBuilder绑定,就能在步骤切换(点上一步/下一步)的时候自动刷新图片,不用自己重写导航逻辑
- 建议给每个Step配置唯一id,直接用id做图片映射的key就行,不用额外存其他步骤标识
- Flutter Web环境下这套写法完全兼容,只要提前在pubspec.yaml里配置好图片资源路径就行
如果你使用的是0.2.0以下的旧版本survey_kit,
currentStep是私有属性无法直接访问,升级到0.2.0及以上版本即可正常使用,不需要fork源码修改。
内容的提问来源于stack exchange,提问作者PK Przemek
相关产品推荐
相关产品推荐

