简体   繁体   中英

Flutter, how to reduce repeated widget

Thank you for aiding me.

What I'm trying to do is cut down on repeat of the code below;

 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
     ),
    )
  }
}

Is there a way I could make above a function or method and insert the code below?

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

You can just use a function to return your code as a Widget

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),
            ],
          )
      ),
    );
  }

then just use myWidget('asset/images/HelloWorld.png', 'Hello World, form Dart')

Just add a child property to the 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,
      ),
    );
  }
}

And then give it what ever child you desire.

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

This is basically the same as @dkap's answer with an own widget class and a little bit more reusability since it accepts all kinds of children.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM