如何从父级的子级小部件显示CircularProgressIndicator()?

时间:2020-07-03 14:20:57

标签: flutter dart

我收到来自有状态儿童小部件的网络通话。为此,我需要在包含脚手架的父窗口小部件中显示CircularProgressIndicator。有什么办法显示吗?

父窗口小部件:

class OrderDetailPage extends StatefulWidget {
   @override
  _OrderDetailPageState createState() => _OrderDetailPageState();

}

class _OrderDetailPageState extends State<OrderDetailPage> {
    bool isloading = false;

    Widget build(BuildContext context){
       return Scaffold(body: isLoading ? Center(child: CircularProgressIndicator() : Container(
          child: ChildWidget()
      ));
    }
}

孩子:

class ChildWidget extends StatefulWidget {
  @override
  ChildWidgetState createState() => ChildWidgetState();
}

class ChildWidgetState extends State<OrderDetailPage> {
  return Center(child: RaisedButton(onPressed: () { // need to make isloading in parent widget to true and false})
}

1 个答案:

答案 0 :(得分:1)

有两种方法将State传递到小部件树中。

将回调函数从父级传递到子级:

class OrderDetailPage extends StatefulWidget {
   @override
  _OrderDetailPageState createState() => _OrderDetailPageState();

}

class _OrderDetailPageState extends State<OrderDetailPage> {
    bool isloading = false;
    Widget build(BuildContext context){
       return Scaffold(body: isLoading ? Center(child: CircularProgressIndicator() : Container(
          child: ChildWidget(callback: () => setState(() => isLoading = !isLoading))
      ));
    }
}

孩子:

class ChildWidget extends StatefulWidget {
  ChildWidget({this.callback});
  @override
  ChildWidgetState createState() => ChildWidgetState();
}

class ChildWidgetState extends State<OrderDetailPage> {
  return Center(child: RaisedButton(onPressed: () { 
   widget.callback();
}

较晚的替代方法是使用状态管理解决方案,例如InheritedWidgetProvider软件包或其他许多软件包之一。