将 Alertbox 创建为单独的小部件 Flutter

时间:2021-03-22 07:15:22

标签: flutter flutter-widget

我的目标是在用户单击注销时创建警报框。由于有许多页面显示注销按钮,为了避免代码重复,我将警报框作为一个单独的小部件。我有上下文问题。我知道小部件适用于 Context。当警报框被视为单独的小部件时,我该如何解决这个问题?

 final AuthService _auth = new AuthService();
    
    class Signout {
      changeRoute(String choice) {
        if (choice == "Ausloggen") {
          return showDialog(
            context: context, // Undefined name 'context'.
            barrierDismissible: true,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Container(
                    child: Icon(
                  Icons.warning_rounded,
                  size: Sizes.s40,
                  color: Colors.deepOrange,
                )),
                content: Container(
                  padding: EdgeInsets.only(left: 60),
                  child: Text(
                    'Sind Sie sicher?',
                    style: TextStyle(
                      fontSize: Sizes.s20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是从外部提供上下文。像这样:

class Signout {
  changeRoute(BuildContext context, String choice) {
    if (choice == "Ausloggen") {
      return showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Container(
                child: Icon(
              Icons.warning_rounded,
              size: Sizes.s40,
              color: Colors.deepOrange,
            )),
            content: Container(
              padding: EdgeInsets.only(left: 60),
              child: Text(
                'Sind Sie sicher?',
                style: TextStyle(
                  fontSize: Sizes.s20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),

然后,当您调用它时,您应该提供适当的上下文:

Signout.changeRoute(context, 'myChoice');