3

谢谢你帮助我。

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

 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'),
4

2 回答 2

2

只需将子属性添加到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 的答案基本相同,有一个自己的小部件类和更多的可重用性,因为它接受各种孩子。

于 2019-12-02T16:15:43.867 回答
1

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

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')

于 2019-12-02T15:26:42.930 回答