Flutter, how to reduce repeated widget
1,300
Solution 1
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.
Solution 2
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')
Author by
Fool Baby
Updated on December 15, 2022Comments
-
Fool Baby over 1 year
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'),