如何将 onPressed 值发送到另一个小部件 Flutter
Posted
技术标签:
【中文标题】如何将 onPressed 值发送到另一个小部件 Flutter【英文标题】:How to send onPressed value to another widget Flutter 【发布时间】:2021-12-12 07:42:41 【问题描述】:我想将数据从小部件发送到另一个小部件,在我的示例中,我想将 onPressed 值作为变量发送。
appBar: CancelAppBar(onPressed: ),
在 onPressed 之后(在上面的代码中)我应该写什么来发送值:
Navigator.of(context).push(MaterialPageRoute(builder: (context) => UnderBuild()));
到单独的 dart 文件中的小部件?
下面是另一个文件:
class CancelAppBar extends StatefulWidget implements PreferredSizeWidget
CancelAppBar(Key? key, required this.onPressed) : super(key: key);
final ValueGetter<String> onPressed;
static final _appBar = AppBar();
@override
Size get preferredSize => _appBar.preferredSize;
@override
_CancelAppBarState createState() => _CancelAppBarState();
class _CancelAppBarState extends State<CancelAppBar>
get onPressed => null;
@override
Widget build(BuildContext context)
return AppBar(
titleSpacing: 0.0,
title: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(padding: EdgeInsets.only(left: 8.w)),
IconButton(
onPressed: ,
icon: Icon(Icons.close),
)
],
),
backgroundColor: AppColors.dark,
);
【问题讨论】:
How to access Stateful widget variable inside State class outside the build method?的可能重复CancelAppBar(onPressed: yourOnPressedFunction)
【参考方案1】:
您可以使用widget
getter 访问State
类中的任何StatefulWidget
变量,例如:
另外,你可以注意到:
您的onPressed
变量具有ValueGetter<String>
类型which is only a typedef to String Function()
IconButton
小部件的onPressed
具有void Function()
类型
然后你可以像这样使用你的变量:
class CancelAppBar extends StatefulWidget implements PreferredSizeWidget
CancelAppBar(Key? key, required this.onPressed) : super(key: key);
final ValueGetter<String> onPressed;
static final _appBar = AppBar();
@override
Size get preferredSize => _appBar.preferredSize;
@override
_CancelAppBarState createState() => _CancelAppBarState();
class _CancelAppBarState extends State<CancelAppBar>
@override
Widget build(BuildContext context)
return AppBar(
titleSpacing: 0.0,
title: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(padding: EdgeInsets.only(left: 8.w)),
IconButton(
onPressed: ()
/// Access your variable by [widget.onPressed]
widget.onPressed(); /// Call it inside this function because your variable doesn't match directly the [onPressed] of [IconButton] widget
,
icon: Icon(Icons.close),
)
],
),
backgroundColor: AppColors.dark,
);
【讨论】:
还有,调用CancelAppBar()时应该写什么参数以上是关于如何将 onPressed 值发送到另一个小部件 Flutter的主要内容,如果未能解决你的问题,请参考以下文章