这是导致错误的代码块,如果我从函数中删除Navigator.pushNamed,则不会发生错误
RoundedButton(buttonColor: Colors.lightBlueAccent,buttonText: 'Log In',
onPress: (){Navigator.pushNamed(context, LoginScreen.id);}, <-- This line is causing error
),
这是RoundedButton的代码
class RoundedButton extends StatelessWidget {
RoundedButton({required this.buttonColor, required this.buttonText, required this.onPress});
final Color buttonColor;
final String buttonText;
final Function onPress;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: Material(
elevation: 5.0,
color: buttonColor,
borderRadius: BorderRadius.circular(30.0),
child: MaterialButton(
onPressed: onPress(),
minWidth: 200.0,
height: 42.0,
child: Text(
buttonText,
style: TextStyle(color: Colors.white,),
),
),
),
);
}
}
这是我得到The following assertion was thrown building RoundedButton(dirty): setState() or markNeedsBuild() called during build.
和The widget which was currently being built when the offending call was made was: RoundedButton dirty The relevant error-causing widget was: RoundedButton RoundedButton:file:///D:/Flutter%20Projects/flashchat/lib/screens/welcome_screen.dart:86:13
的错误
我需要在按下按钮时导航到loginscreeen,但导航器在函数内部导致错误。我尝试将其放入另一个函数,但也引发相同的错误。不知道如何导航到其他屏幕。
我正在遵循Angela Yu的课程,它运行得非常好。我正在Windows 10上运行Flutter 3.3.10版本
3条答案
按热度按时间8yparm6h1#
您正在调用
onPress
方法,而不是对其进行赋值。按如下方式赋值(RoundedButton
的代码):inb24sb22#
使用
VoidCallback
代替类型函数final Function onPress;
-〉final VoidCallback onPress;
3b6akqbq3#
嗨,问题是您正在传递
onPressed: onPress()
这样的函数,它会在构建期间触发onPress()
函数。将其替换为onPressed: onPress
。