我正在MyButton通過組合創建一個自定義按鈕小部件,ElevatedButton該Text小部件將包含一個小部件作為子部件。它有一個布爾isLoading屬性,用于配置要構建的 Button 型別。當isLoading = true它將回傳一個灰色加載按鈕,其寬度與此加載按鈕構建之前提供的文本寬度相同。我的問題是如何在 setState 呼叫或再次呼叫 build 方法之前獲取width子Text小部件的of ,以便我可以使用它width來創建相同大小的加載按鈕?
在使用子Text小部件構建默認按鈕后,將始終呼叫加載按鈕。(即isLoading只有當小部件不是最初重建時才為真)。
這是代碼:
class MyButton extends StatefulWidget {
final String text;
final bool isLoading;
final VoidCallback onPressed;
MyButton({Key key, @required this.text, @required this.isLoading, this.onPressed}) : super(key: key);
@override
State<StatefulWidget> createState() => _MyButtonState();
}
class _MyButtonState extends State<MyButton> {
double _width; // Width of the [Text] child widget that will be used to get the [Container] of same width for loading button
@override
void initState() {
super.initState();
_width = 150;
}
@override
void didUpdateWidget(covariant MyButton oldWidget) {
super.didUpdateWidget(oldWidget);
/*
Calculate the width....
*/
}
@override
Widget build(BuildContext context) {
// I want to get the width of this child
Widget child = Text(
widget.text,
style: TextStyle(color: Colors.black),
);
if (widget.isLoading) {
child = Container(
height: 60,
width: _width, // this should be same as [Text] width
color: Colors.grey,
);
}
return ElevatedButton(
child: child,
onPressed: !widget.isLoading ? widget.onPressed : null,
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(
!widget.isLoading ? Colors.red : Colors.grey,
),
),
);
}
}
這是我想要做的演示,但按鈕的大小isLoading = true現在是絕對的。
我檢查了其他帖子和問題,但找不到解決我的用例的有用方法。使用GlobalKey是一種解決方案,但不是推薦的方法,使用RenderObject我無法解決這個問題,因為在這種情況下我們只能獲得父級的固有高度和寬度。
我認為除了使用 GlobalKey 和 RenderObject 之外,可能還有其他方法可以做到這一點。
uj5u.com熱心網友回復:
而不是為此創建一個容器,我希望您只是隱藏文本,以便按鈕的大小與以前相同。試試下面的代碼:
Widget build(BuildContext context) {
return ElevatedButton(
child: Opacity(
opacity: !widget.isLoading ? 1 : 0,
child: Text(
widget.text,
style: TextStyle(color: Colors.black),
),
),
onPressed: !widget.isLoading ? widget.onPressed : null,
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(
!widget.isLoading ? Colors.red : Colors.grey,
),
),
);
}
uj5u.com熱心網友回復:
我們可以使用 add postFrameCallbackto WidgetBinding 實體從 內部的背景關系中獲取小部件的大小postFrameCallback。
注意:這可能不是有效的方法。
這是適用于我的案例的代碼。
@override
void initState() {
super.initState();
getWidth();
_width = _width ?? 150;
}
void getWidth() {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
if (context?.size is Size) {
_width = context.size.width;
print(context.size.toString());
}
});
}
@override
void didUpdateWidget(covariant MyButton oldWidget) {
getWidth();
super.didUpdateWidget(oldWidget);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/399242.html
上一篇:以xamarin形式將資料從listView傳遞到tabPage
下一篇:在模態底部作業表中禁用滑塊小部件
