Flutter实现FloatingActionButton按PIN设置状态显示/隐藏
解决方案
核心思路是利用PinValidationProvider中的isPinSet状态来控制FloatingActionButton的显示:
- 当
isPinSet = false(PIN设置阶段):隐藏FAB - 当
isPinSet = true(PIN确认阶段):显示FAB
具体修改步骤如下:
1. 修改SetPinScreen的build方法
将固定的isFloatingButtonVisible: true改为根据Provider的isPinSet状态动态控制,同时通过外层Consumer监听状态变化,确保UI能实时更新。
修改后的代码:
@override Widget build(BuildContext context) { return Consumer<PinValidationProvider>( builder: (context, pinProvider, child) { return MainTemplate( // 仅在确认PIN阶段(isPinSet=true)显示按钮 isFloatingButtonVisible: pinProvider.isPinSet, floatingButtonAction: () { // 可添加PIN确认通过后的逻辑 if (pinProvider.isPinMatched) { // 比如跳转主页、完成PIN设置流程等操作 } }, child: Padding( padding: const EdgeInsets.all(15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Align( alignment: Alignment.centerLeft, child: Text( pinProvider.isPinSet ? 'Re-enter your PIN code to Confirm' : 'Set PIN to Activate your Finance House Card Ending With XXXX', style: TextStyle(fontWeight: FontWeight.w700, fontSize: 30), ), ), SizedBox(height: 20), Center( child: PinFieldAutoFill( decoration: UnderlineDecoration( textStyle: Theme.of(context).textTheme.subtitle1.copyWith( fontWeight: FontWeight.bold, fontSize: 15, ), gapSpace: 8, lineHeight: 1.2, colorBuilder: PinListenColorBuilder(Colors.black, Colors.grey.shade400), ), onCodeChanged: _validatePin, codeLength: 4, cursor: Cursor(color: Colors.black, enabled: true), controller: setPinController, keyboardType: TextInputType.number, ), ), SizedBox(height: 20), Consumer<PinValidationProvider>( builder: (context, provider, child) { final textColor = provider.isPinSet == false ? provider.isInvalidPin || (!provider.isPinMatched && provider.isPinSet) ? Colors.red : Colors.black : provider.isInvalidPin && !provider.isPinMatched ? Colors.red : Colors.black; if (!provider.isPinMatched && provider.isPinSet && setPinController.text.isNotEmpty && setPinController.text.length == 4) { return Center( child: Text( 'PIN does not match.', style: TextStyle( color: Colors.red, ), ), ); } else { return Text( 'Pin must be at least 4 digits. It must not be single digits like' ' 1111 or digits in numerical order such as 1234', style: TextStyle( color: textColor, ), ); } }, ), ], ), ), ); }, ); }
2. 逻辑说明
- 外层
Consumer<PinValidationProvider>会监听isPinSet状态变化,用户完成PIN设置后(isPinSet变为true),FAB自动显示;设置阶段则保持隐藏。 - 可在
floatingButtonAction中补充逻辑,比如判断isPinMatched为true时,执行PIN设置完成后的后续操作。
可选优化
如果需要仅在PIN输入匹配时启用FAB,可以给MainTemplate增加isFloatingButtonEnabled参数(若模板支持),设置为pinProvider.isPinMatched,确保只有PIN正确时按钮可点击。
内容的提问来源于stack exchange,提问作者Mansoor Malik
相关产品推荐
相关产品推荐

