Flutter项目报错:'RaisedButton'未在'_SignUpState'中定义求解决
问题原因
RaisedButton是Flutter旧版本中的组件,在Flutter 2.0及以后版本中已被废弃移除,官方推荐使用ElevatedButton替代,因此会出现"未定义"的报错。
解决方案
将所有页面中的RaisedButton替换为ElevatedButton,并调整对应参数(两者部分参数结构不同):
- 替换组件名称:把代码里的
RaisedButton全部改成ElevatedButton - 调整参数结构:
- 原
color参数需放到style: ElevatedButton.styleFrom()的backgroundColor中 - 原
elevation参数移到styleFrom()方法内 - 原
highlightColor、splashColor通过overlayColor设置(用MaterialStateProperty处理不同交互状态的颜色) - 原
animationDuration直接放到styleFrom()中
- 原
修改后的按钮代码示例
针对你提供的SignUp页面中的按钮,修改后如下:
ElevatedButton( style: ElevatedButton.styleFrom( animationDuration: const Duration(milliseconds: 300), elevation: 2.0, backgroundColor: Colors.black87, overlayColor: MaterialStateProperty.resolveWith<Color?>((states) { if (states.contains(MaterialState.pressed)) { return Colors.white; // 对应原splashColor } if (states.contains(MaterialState.hovered)) { return Colors.white; // 对应原highlightColor } return null; }), ), onPressed: () { // 原点击逻辑保持不变 if (_signInKey.currentState.validate()) { FirebaseAuth.instance .createUserWithEmailAndPassword( email: _email, password: _password) .then((AuthResult signUpUser) { _userCred = { 'email': signUpUser.user.email, 'uid': signUpUser.user.uid, }; try { DocumentReference infoDoc = _userInfo.document(_userCred['uid']); infoDoc.setData({ 'friends': [], }).then((_) { _userCred['userInfo'] = infoDoc; _userCredDb .document(_userCred['uid']) .setData(_userCred) .then((_) { print('done here'); }); }); } catch (e) {} }).catchError((e) => print(e)); } }, child: const Text( 'Signup', style: TextStyle( color: Colors.white, ), ), )
其他页面处理
另外两个使用RaisedButton的页面,按照同样的方式替换组件并调整参数即可解决相同错误。
额外提示:你的代码中使用的
Firestore.instance是旧版Firebase写法,若后续遇到Firestore相关错误,需替换为FirebaseFirestore.instance,并确保firebase_core和cloud_firestore依赖为最新版本。
内容的提问来源于stack exchange,提问作者Divya
相关产品推荐
相关产品推荐

