Flutter布尔校验后跳转用户页面的报错问题求助
问题解决:Dart条件表达式类型不匹配错误
错误原因
你代码里的onPressed参数写法存在两个核心问题:
- 误用双重三元运算符(
? ?),导致条件判断的类型不符合Dart的静态类型要求,触发Conditions must have a static type of 'bool'错误。 _handleButtonPress是返回Future<void>的异步函数,而onPressed要求的是VoidCallback(无参数、无返回值的函数类型),直接赋值会导致类型不匹配。
修正方案
调整onPressed的逻辑:当_isButtonActive为true时,返回一个匿名函数,在该函数内调用_handleButtonPress并添加页面跳转逻辑;为false时返回null(禁用按钮)。同时在_handleButtonPress完成Firestore操作后,补充页面跳转代码。
修正后的完整代码
ElevatedButton( child: Text("Button2"), onPressed: _isButtonActive ? () async { await _handleButtonPress(); // 此处添加页面跳转逻辑,示例为跳转到HomePage Navigator.push( context, MaterialPageRoute(builder: (context) => HomePage()), ); } : null, ) Future<void> _handleButtonPress() async { try { await _firestore.collection('WithdrawalsAuthentications').doc(_uid).set({ 'date': Timestamp.now(), "amountRequested": _flexAmount, }); setState(() { _isButtonActive = false; }); } catch (e) { print("Error handling button press: $e"); } }
关键修改点
- 替换错误的双重三元运算符为匿名函数,确保
onPressed接收的是符合要求的VoidCallback类型。 - 在匿名函数内异步调用
_handleButtonPress,等待Firestore操作完成后再执行页面跳转。 - 注意页面跳转代码需要的
context需处于可用状态(若当前组件无直接context,可通过Navigator.of(context)等方式获取)。
内容的提问来源于stack exchange,提问作者Happiness Jen
相关产品推荐
相关产品推荐

