【问题标题】:Flutter, how to reduce repeated widgetFlutter,如何减少重复的小部件
【发布时间】:2020-03-27 05:23:08
【问题描述】:

谢谢你的帮助。

我想要做的是减少下面代码的重复;

 class PeddingRadius extends StatelessWidget {
  PeddingRadius(final column);

  @override
  Widget build(BuildContext context) {
    Container(
      padding: const EdgeInsets.all(8.0),
      child: Material(
          borderRadius: BorderRadius.circular(30),
          shadowColor: Colors.grey.shade100,
          elevation: 5,
          child: //my code
     ),
    )
  }
}

有没有一种方法可以在函数或方法之上创建并在下面插入代码?

                  Image.asset(
                  'asset/images/HelloWorld.png', height: 100.0, width: 100.0,
                  ),
                  Text('Hello World, form Dart'),

【问题讨论】:

    标签: function flutter widget dart-2


    【解决方案1】:

    只需将子属性添加到PeddingRadius

    class PeddingRadius extends StatelessWidget {
      final Widget child;
    
      PeddingRadius({@required Widget child});
    
      @override
      Widget build(BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(8.0),
          child: Material(
              borderRadius: BorderRadius.circular(30),
              shadowColor: Colors.grey.shade100,
              elevation: 5,
              child: child,
          ),
        );
      }
    }
    

    然后给它你想要的任何孩子。

    PeddingRadius(
      child: Column(
        children: [
           Image.asset(
             assetLocation, height: 100.0, width: 100.0,
           ),
           Text(text),
        ],
      ),
    )
    // or
    PeddingRadius(
      child: RaisedButton(child: Text("Hello World")),
    )
    
    

    这与@dkap 的答案基本相同,有一个自己的小部件类,并且由于它接受各种子类,因此具有更多的可重用性。

    【讨论】:

      【解决方案2】:

      您可以只使用一个函数将您的代码作为小部件返回

      Widget myWidget(String assetLocation, String text) {
          return Container(
            padding: const EdgeInsets.all(8.0),
            child: Material(
                borderRadius: BorderRadius.circular(30),
                shadowColor: Colors.grey.shade100,
                elevation: 5,
                child: Column(
                  children: [
                    Image.asset(
                      assetLocation, height: 100.0, width: 100.0,
                    ),
                    Text(text),
                  ],
                )
            ),
          );
        }
      

      那就用myWidget('asset/images/HelloWorld.png', 'Hello World, form Dart')

      【讨论】:

        猜你喜欢
        • 2020-10-11
        • 2023-02-23
        • 2011-08-03
        • 2021-10-29
        • 2020-01-23
        • 2021-10-25
        • 2020-04-23
        • 2014-12-07
        • 1970-01-01
        相关资源
        最近更新 更多