dart 我正在传递匿名函数,函数体中包含Navigator.pushNamed,但它显示了错误-在构建期间调用了setState()或markNeedsBuild(

5ktev3wc  于 2023-01-18  发布在  其他
关注(0)|答案(3)|浏览(125)

这是导致错误的代码块,如果我从函数中删除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版本

8yparm6h

8yparm6h1#

您正在调用onPress方法,而不是对其进行赋值。按如下方式赋值(RoundedButton的代码):

MaterialButton(
  onPressed: onPress, // instead of onPress()
  minWidth: 200.0,
  height: 42.0,
  child: Text(
    buttonText,
    style: TextStyle(color: Colors.white,),
  ),
)
inb24sb2

inb24sb22#

使用VoidCallback代替类型函数final Function onPress;-〉final VoidCallback onPress;

3b6akqbq

3b6akqbq3#

嗨,问题是您正在传递onPressed: onPress()这样的函数,它会在构建期间触发onPress()函数。将其替换为onPressed: onPress

相关问题