根据给定的布尔条件用父窗口小部件包裹窗口小部件

问题描述 投票:0回答:1

如果给定条件为真,我想用Column小部件包装FutureBuilder小部件。

除了重复两次Column小部件之外,还有其他更好的方法吗?

代码如下所示:

class HomeScreen extends StatelessWidget {
  // member variables
  final bool isEligible;

  // constructor
  HomeScreen({this.isEligible});

  @override
  Widget build(BuildContext context) {
    // wrap with Future Builder based on given condition 
    return isEligible
        ? FutureBuilder(
            future: API.getInfo(),
            builder: (context, snapshot) {
              return Column(
                children: <Widget>[
                  Text(
                    'This is a text',
                  ),
                  Text(
                    'This is another text',
                  ),
                ],
              );
            })
        : Column(
            children: <Widget>[
              Text(
                'This is a text',
              ),
              Text(
                'This is another text',
              ),
            ],
          );
  }
}
flutter dart
1个回答
0
投票

您可以创建一个类型为“ Widget”的函数来返回该列。

Widget _createColumn (){
   return Column(
            children: <Widget>[
              Text(
                'This is a text',
              ),
              Text(
                'This is another text',
              ),
            ],
          );
}

然后您可以调用该函数:

class HomeScreen extends StatelessWidget {


// member variables
  final bool isEligible;

  // constructor
  HomeScreen({this.isEligible});

  @override
  Widget build(BuildContext context) {
    // wrap with Future Builder based on given condition 
    return isEligible
        ? FutureBuilder(
            future: API.getInfo(),
            builder: (context, snapshot) {
              return _createColumn();
            })
        : _createColumn();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.