如何将对象和回调传递给Flutter中的Stateless Widget?

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

How to pass an object AND a callback to a Stateless Widget in Flutter?

问题

我需要将一个对象和回调一起传递给一个无状态小部件,但无法成功,有人可以帮忙吗?

child: NewPage(rec, onSelectParam: (int param) {
    print('value: ' + param.toString());
})
class NewPage extends StatelessWidget {
   NewPage(this.rec, this.onSelectParam);
   
   var rec;
   Function(int) onSelectParam;
}

它会出现编译错误:

位置参数不足:需要2个,但只提供了1个。

英文:

I need to pass an object together with a Call Back to a stateless widget but fail to do so, can anyone help?

child: NnewPage(rec, onSelectParam: (int param) {
            print('value: ' + param.toString());
        })

class NewPage extends StatelessWidget {
   NewPage(this.rec, this.onSelectParam);
   
   var rec;
   Function(int) onSelectParam;

It gives compile error:

> Too few positional arguments: 2 required, 1 given.

答案1

得分: 0

有2种方法:

child: NnewPage(rec, (param) {
        print('value: ' + param.toString());
    })
class NewPage extends StatelessWidget {
   NewPage(this.rec, this.onSelectParam);
   
   var rec;
   Function(int) onSelectParam;
}

或者:

child: NnewPage(rec: rec, onSelectParam: (param) {
            print('value: ' + param.toString());
    })
class NewPage extends StatelessWidget {
   NewPage({this.rec, this.onSelectParam});
   
   var rec;
   Function(int) onSelectParam;
}

更多详细信息,请参阅这篇文章:https://stackoverflow.com/questions/61947930/understanding-brackets-in-dart

英文:

There are 2 ways:

child: NnewPage(rec, (param) {
        print('value: ' + param.toString());
    })

class NewPage extends StatelessWidget {
   NewPage(this.rec, this.onSelectParam);
   
   var rec;
   Function(int) onSelectParam;

or:

child: NnewPage(rec: rec, onSelectParam: (param) {
            print('value: ' + param.toString());
    })

class NewPage extends StatelessWidget {
   NewPage({this.rec, this.onSelectParam});
   
   var rec;
   Function(int) onSelectParam;

For more detail, you can read this article: https://stackoverflow.com/questions/61947930/understanding-brackets-in-dart

huangapple
  • 本文由 发表于 2023年7月17日 17:23:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76703063.html
匿名

发表评论

匿名网友

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

确定