将自定义按钮作为小部件发送给无状态小部件

huangapple go评论48阅读模式
英文:

Send custom button as widget to a stateless widget

问题

我有一个无状态小部件,它在构建器方法内部返回一个按钮小部件。我想要在应用程序的不同部分调用这个无状态小部件,但我希望小部件返回一个我传入的函数来调用的按钮。我应该如何做?

我将传入的按钮可以是:

  • ElevatedButton
  • OutlineButton
  • IconButton

这是我的无状态小部件,它返回一个 ElevatedButton。

class FileUploadMutation extends StatelessWidget {
  const FileUploadMutation(this.user, this.switchScreenFn, {Key? key})
      : super(key: key);

  final User user;
  final Function switchScreenFn;

  @override
  Widget build(BuildContext context) {
    return Mutation(
      options: MutationOptions(
        document: gql(fileUploadMutation),
      ),
      builder: (runMutation, result) {
        return ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.red,
            elevation: 0,
          ),
          onPressed: () async {
            List<MultipartFile> files = user.files;
            runMutation(
              {
                'containerName': containerName,
                'files': files,
              },
            );
          },
          child: const Text("Continue"),
        );
      },
    );
  }
}

希望这有所帮助。

英文:

I have a stateless widget that returns a button widget inside of the builder method. I want this stateless widget to be called from different parts of the application but I want the widget to return a button that I pass in with a function to be called. How can I do this?

The buttons that I will be passing in could be -

  • ElevatedButton
  • OutlineButton
  • IconButton

Here is my stateless widget that returns an ElevatedButton.

class FileUploadMutation extends StatelessWidget {
  const FileUploadMutation(this.user, this.switchScreenFn, {Key? key})
      : super(key: key);

  final User user;
  final Function switchScreenFn;
    
  @override
  Widget build(BuildContext context) {
    return Mutation(
      options: MutationOptions(
        document: gql(fileUploadMutation),
      ),
      builder: (runMutation, result) {
        return ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.red,
            elevation: 0,
          ),
          onPressed: () async {
            List&lt;MultipartFile&gt; files = user.files;
            runMutation(
              {
                &#39;containerName&#39;: containerName,
                &#39;files&#39;: files,
              },
            );
          },
          child: const Text(&quot;Continue&quot;),
        );
      },
    );
  }
}

答案1

得分: 2

我不理解你的代码,但我认为你需要创建一个可以在任何地方使用的按钮。如果是这样,你可以像这样创建你的按钮:

class CustomButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;
  final Color color;
  final Color textColor;
  const CustomButton({
    Key? key,
    required this.size,
    required this.text,
    required this.color,
    required this.textColor,
    required this.onPressed,
  });

  final Size size;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: size.width / 2.5,
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          elevation: 10,
          backgroundColor: color,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25),
          ),
        ),
        child: Text(
          text,
          style: TextStyle(color: textColor, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }
}

当你需要使用这个按钮时,只需像这样使用:

CustomButton(
  onPressed: () async {
    _saveForm(context);
  },
  size: size,
  text: "Sign In",
  color: Colors.white,
  textColor: Colors.black,
)

请注意,我修正了构造函数的参数,并添加了缺失的key参数。

英文:

I don't understand your code but I think you need to Crete a button that can use anywhere ? if so you can Crete your button like this

class CustomButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;
  final Color color;
  final Color textColor;
  const CustomButton({
    super.key,
    required this.size,
    required this.text,
    required this.color,
    required this.textColor,
    required this.onPressed,
  });

  final Size size;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: size.width / 2.5,
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          elevation: 10,
          backgroundColor: color,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25),
          ),
        ),
        child: Text(
          text,
          style: TextStyle(color: textColor, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }
}

when you need to use this button just use like this

 CustomButton(
                                onPressed: () async {
                                  _saveForm(context);
                                },
                                size: size,
                                text: &quot;Sign In&quot;,
                                color: Colors.white,
                                textColor: Colors.black,
                              ),

答案2

得分: 0

按照以下方式创建您自定义的小部件 并在代码的 任何位置定义onPresses 参数将执行您的方法调用。

 导入包 &#39;package:easyclean_business/utils/scaler_config.dart&#39; ;
 导入包 &#39;package:easyclean_business/utils/theme/color.dart&#39; ;
 导入包 &#39;package:flutter/material.dart&#39; ;
 导入包 &#39;package:get/get.dart&#39; ;
 导入包 &#39;package:hooks_riverpod/hooks_riverpod.dart&#39; ;

 导入 &#39;constant_widgets.dart&#39; 。

 类 Click 将如下所示:-

 class Click extends HookConsumerWidget {
   final String text;
   final void Function() onPressed;
   final bool loading;
   final bool disabled;
   final BorderSide borderSide;
   final double fontsize;
   final BorderRadiusGeometry radius;
   final double btnheight;
   final Color btncolor, textcolor, disabledColor;
   final ScalerConfig scaler = Get.find(tag: &#39;scaler&#39;);
   final Widget blurConatiner;
   Click(
       {Key key,
       this.text,
       this.onPressed,
       this.loading = false,
       this.disabled = false,
       this.borderSide,
       this.fontsize,
       this.radius,
       this.btncolor,
       this.btnheight,
       this.textcolor,
       this.blurConatiner,
       this.disabledColor})
       : super(key: key);

   @override
   Widget build(BuildContext context, WidgetRef ref) {
     return MaterialButton(
       elevation: 5,
       shape: RoundedRectangleBorder(
         side: BorderSide.none,
         borderRadius: BorderRadius.circular(
           scaler.scalerV(8.0),
         ),
       ),
       child: Row(
         mainAxisAlignment: MainAxisAlignment.center,
         children: [
           loading
               ? SizedBox(
                   child: CircularProgressIndicator(
                     color: LightColors.bottomtext,
                     strokeWidth: scaler.scalerH(2.0),
                   ),
                   height: scaler.scalerV(16.0),
                   width: scaler.scalerV(16.0),
                 )
               : Container(),
           loading
               ? SizedBox(
                   width: scaler.scalerH(16.0),
                 )
               : Container(),
           blurConatiner ??
               Text(
                 text,
                 style: textStyle(
                     fontWeight: FontWeight.w600,
                     fontSize: fontsize ?? scaler.scalerT(16.0),
                     color: textcolor ?? LightColors.bottomtext),
               ),
         ],
       ),
       color: btncolor ?? LightColors.primary,
       disabledColor: disabledColor ?? LightColors.primary,
       onPressed: disabled
           ? null
           : loading
               ? null
               : onPressed,
       minWidth: double.infinity,
       height: btnheight ?? scaler.scalerV(55.0),
     );
   }
 }
英文:

Create your custom Widget like this and call it and define anywhere in your code . onPresses parameter will execute your method call .

                     Click(
                        text: &#39;Send&#39;,
                        onPressed: _sendData,
                        loading: loginMutation.isLoading,
                      ),

And Custom widget will look like .You call :-

 import &#39;package:easyclean_business/utils/scaler_config.dart&#39;;
import &#39;package:easyclean_business/utils/theme/color.dart&#39;;
import &#39;package:flutter/material.dart&#39;;
import &#39;package:get/get.dart&#39;;
import &#39;package:hooks_riverpod/hooks_riverpod.dart&#39;;

import &#39;constant_widgets.dart&#39;;

class Click extends HookConsumerWidget {
  final String text;
  final void Function() onPressed;
  final bool loading;
  final bool disabled;
  final BorderSide borderSide;
  final double fontsize;
  final BorderRadiusGeometry radius;
  final double btnheight;
  final Color btncolor, textcolor, disabledColor;
  final ScalerConfig scaler = Get.find(tag: &#39;scaler&#39;);
  final Widget blurConatiner;
  Click(
      {Key key,
      this.text,
      this.onPressed,
      this.loading = false,
      this.disabled = false,
      this.borderSide,
      this.fontsize,
      this.radius,
      this.btncolor,
      this.btnheight,
      this.textcolor,
      this.blurConatiner,
      this.disabledColor})
      : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return MaterialButton(
      elevation: 5,
      shape: RoundedRectangleBorder(
        side: BorderSide.none,
        borderRadius: BorderRadius.circular(
          scaler.scalerV(8.0),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          loading
              ? SizedBox(
                  child: CircularProgressIndicator(
                    color: LightColors.bottomtext,
                    strokeWidth: scaler.scalerH(2.0),
                  ),
                  height: scaler.scalerV(16.0),
                  width: scaler.scalerV(16.0),
                )
              : Container(),
          loading
              ? SizedBox(
                  width: scaler.scalerH(16.0),
                )
              : Container(),
          blurConatiner ??
              Text(
                text,
                style: textStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: fontsize ?? scaler.scalerT(16.0),
                    color: textcolor ?? LightColors.bottomtext),
              ),
        ],
      ),
      color: btncolor ?? LightColors.primary,
      disabledColor: disabledColor ?? LightColors.primary,
      onPressed: disabled
          ? null
          : loading
              ? null
              : onPressed,
      minWidth: double.infinity,
      height: btnheight ?? scaler.scalerV(55.0),
    );
  }
}

huangapple
  • 本文由 发表于 2023年6月15日 11:21:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76478870.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定