[英]Access const child widget variable from parent widget in Flutter
I want to access child widget variable value in parent widget whereas child widget is a const widget which does not allow me to use GlobalKey for const child widget.我想访问父窗口小部件中的子窗口小部件变量值,而子窗口小部件是一个 const 窗口小部件,它不允许我将 GlobalKey 用于 const 子窗口小部件。
My question is how can I access child widget without GlobalKey.我的问题是如何在没有 GlobalKey 的情况下访问子窗口小部件。 Here is my code snippet:这是我的代码片段:
class ParentWidget extends StatefulWidget { @override State<StatefulWidget> createState() { // TODO: implement createState return ParentWidgetState(); } } class ParentWidgetState extends State<ParentWidget> { @override Widget build(BuildContext context) { return Container( child: const LeftSidePanel(),); } } class LeftSidePanel extends StatefulWidget { @override State<StatefulWidget> createState() { // TODO: implement createState return LeftPanelWidgetState(); } const LeftSidePanel( ); } class LeftSidePanelState extends State<LeftSidePanel> { }
Anyone there to answer my query please.请有人回答我的问题。 Thanks谢谢
In this example none of widgets have to be Statefull ( try to use as few statefull widgets as you can)在这个例子中,没有一个小部件必须是有状态的(尽量使用尽可能少的有状态小部件)
import 'package:flutter/material.dart';
class ParentWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: ChildWidget(
getWidgetTextCallback: (someParameter) {
print(someParameter);
// here you can have the value from the Child widget use it wisely
},
),
);
}
}
class ChildWidget extends StatelessWidget {
final widgetText = 'widgetText';
final Function(String) getWidgetTextCallback;
const ChildWidget({required this.getWidgetTextCallback});
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(widgetText),
ElevatedButton(
onPressed:
getWidgetTextCallback(widgetText),
child: Text(widgetText),
)
],
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.