当我使用函数回调时我遇到问题
我有来自不同文件的自定义按钮小部件,然后我创建回调函数它可能会显示来自主函数的指针,当我运行时我遇到以下问题: 问题
和这段代码,主布局:
import 'package:flutter/material.dart';
import './increment.dart';
void main() => runApp(MaterialApp(
home: HomePage(),
));
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _counter = 0;
void increment() {
setState(() {
_counter = _counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
Text('Result = ${_counter}'),
SizedBox(
height: 100,
),
Inc(increment)
// ElevatedButton(onPressed: increment, child: Text('-'))
],
),
),
);
}
}
和这个小部件自定义:
import 'package:flutter/material.dart';
class Inc extends StatelessWidget {
final Function selectInc;
Inc(this.selectInc);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
height: 100,
child: ElevatedButton(onPressed: selectInc(), child: Text('+')),
);
}
}
我如何解决这个问题?
i have custom button widget from different file, then i create callback function it might will showing pointer from main function, when i'm running i have issues this:
Issues
and this code, main layout:
import 'package:flutter/material.dart';
import './increment.dart';
void main() => runApp(MaterialApp(
home: HomePage(),
));
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _counter = 0;
void increment() {
setState(() {
_counter = _counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
Text('Result = ${_counter}'),
SizedBox(
height: 100,
),
Inc(increment)
// ElevatedButton(onPressed: increment, child: Text('-'))
],
),
),
);
}
}
and this widget custom:
import 'package:flutter/material.dart';
class Inc extends StatelessWidget {
final Function selectInc;
Inc(this.selectInc);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
height: 100,
child: ElevatedButton(onPressed: selectInc(), child: Text('+')),
);
}
}
how i can solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是调用函数并使用结果。您只需将该函数用作参数:
由于您的
selectInc
方法是一个 void 函数,即回调所需的确切类型,您也可以省略匿名函数包装器并直接传递您的回调:但是,看来你需要更多的类型安全才能让编译器不抱怨。使
看起来像这样:
This is calling the function and using the result. You need to use the function only as a parameter:
Since your
selectInc
method is a void function, the exact type the callback requires, you could also omit the anonymous function wrapper and pass your callback directly:However, it seems you need some more type safety for the compiler to not complain. Make
look like this: