如何将函数注入到其他类中

问题描述 投票:0回答:1

单击“我的按钮”时我想打印“测试”

我在课堂上做了一个带有函数的构造,但是没用

请帮助我这是我的代码

Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'bla bla bla',
            ),
            MyButton((){print('test');}, 'my button')
          ],
        ),

我创建了一个StatefulWidget类,我称之为MyButton

import 'package:flutter/material.dart';

class MyButton extends StatefulWidget {
  Function buttonFunction;
  String buttonName;
  MyButton(this.buttonFunction,this.buttonName);

  @override
  _MyButtonState createState() => _MyButtonState();
}

class _MyButtonState extends State<MyButton> {
  @override
  Widget build(BuildContext context) {
    String name=widget.buttonName;
    return Container(
      width: 200,
      child: RaisedButton(
        color: Colors.red,
        onPressed: () {
          widget.buttonFunction;
          print('clicked $name');
        },

        textColor: Colors.white,
        child: Text("$name",
          style: TextStyle(fontSize: 18,),
        ),
      ),
    );
  }
}
function flutter methods dart inject
1个回答
0
投票

您缺少括号“()”来调用该函数,而只是引用了它。

您还在build方法内设置了一个变量,在声明变量的地方是错误的,因为它将重新运行很多次,并且不必要地重新声明并且变得昂贵。如果要访问字符串中的值的属性,只需使用“字符串$ {widget.myStringVariable}”。

我已修改您的代码以反映这些更改:

class _MyButtonState extends State<MyButton> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 200,
      child: RaisedButton(
        color: Colors.red,
        onPressed: () {
          widget.buttonFunction();
          print('clicked $name');
        },
        textColor: Colors.white,
        child: Text("${widget.buttonName}",
          style: TextStyle(fontSize: 18,),
        ),
      ),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.