简体   繁体   English

使用动态 onPressed 颤振创建新按钮小部件

[英]Creating a new button widget with dynamic onPressed flutter

I have a button widget with an onPressed function.我有一个带有 onPressed 功能的按钮小部件。 Now I want to use this widget to create multiple buttons, but of course with another function to run with.现在我想使用这个小部件来创建多个按钮,但当然要使用另一个功能来运行。

New buttonwidget:新按钮小部件:

class RunderKreis extends StatelessWidget {
  final DecorationImage? image;
  final double size;
  Color? color;
  IconData? icon;
  Color? onPrimaryColors;
  Future<dynamic>? directTo;
  RunderKreis({
    Key? key,
    this.color = const Color.fromARGB(255, 95, 81, 136),
    this.size = 90,
    this.icon,
    this.onPrimaryColors,
    this.image,
    this.directTo,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: size,
      width: size,
      child: ElevatedButton(
        onPressed: () {
              directTo;
        },
        child: Icon(icon),
      ),
    );
  }
}

Using it :使用它 :

RunderKreis(
                        icon: FeatherIcons.pieChart,
                        onPrimaryColors: AppColors.backColor,
                         directTo:  Future.delayed(Duration(seconds: 1),(){
                       Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => const Steckbrief()),
                      );}),
                      ),
RunderKreis(...),
RunderKreis(...),

Right now I use 3 buttons, but I get immediately redirected to the page I navigate to with the first onPressed function, without pressing the a button :( Am I implementing something the wrong way?现在我使用 3 个按钮,但我立即被重定向到我使用第一个 onPressed 函数导航到的页面,而没有按下 a 按钮:(我是否以错误的方式实现了某些东西?

Thanks in advance!提前致谢!

I prefer this style.我比较喜欢这种风格。

 child: ElevatedButton(
        onPressed:directTo,
        child: Icon(icon),
      ),

And use case will be用例将是

 directTo: () async {
await Future.delayed(Duration(seconds: 1), () {
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => const Steckbrief()),
  );
});

You can useVoidCallback for tap event.您可以将VoidCallback用于点击事件。

class RunderKreis extends StatelessWidget {
  final DecorationImage? image;
  final double size;
  Color? color;
  IconData? icon;
  Color? onPrimaryColors;
  VoidCallback? onTap;
    RunderKreis({
    Key? key,
    this.color = const Color.fromARGB(255, 95, 81, 136),
    this.size = 90,
    this.icon,
    this.onPrimaryColors,
    this.image,
    this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: size,
      width: size,
      child: ElevatedButton(
        onPressed: onTap,
        child: Icon(icon),
      ),
    );
  }
}

And use并使用

RunderKreis(
  onTap: () async {},
),
RunderKreis(
  onTap: () {},
),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM