Is there a way to define a widget that does not inherit from statefull or statelles widget ,and when should to use it? For example: This is listView that displays objectCard(custom card):
ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return objectCard(list[index], onTap);
},
),
I ask if the objectCard can be simple without inherit from statefull or statelles widget
Is there a way to define a widget that does not inherit from statefull or statelles widget ,and when should to use it? For example: This is listView that displays objectCard(custom card):
ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return objectCard(list[index], onTap);
},
),
I ask if the objectCard can be simple without inherit from statefull or statelles widget
Share edited Mar 4 at 14:29 mini mouse asked Mar 4 at 12:16 mini mousemini mouse 595 bronze badges 1- Could you please provide any code for the widget you want or add any details about it – Mahmoud Al-shehyby Commented Mar 4 at 13:54
1 Answer
Reset to default 2Yes, you can define a method
return a Widget
then pass the parameters you want from this method:
Example:
Widget objectCard({required String title, required void Function() onTap}) {
return Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
child: Container(
padding: const EdgeInsets.all(10),
margin: const EdgeInsets.all(10.0),
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.lime,
),
child: Text(title),
),
),
);
}
then You can use it wherever you want in your project:
ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return objectCard(title: list[index], onTap: onTap);
},
),
If your widget is simple and doesn't need to manage state or lifecycle methods like initState()
or dispose()
use this way
You can also create a class
field(variable) of type Widget
if the Widget
does not required any parameters
Widget objectCard = Material(
color: Colors.transparent,
child: InkWell(
onTap: () {},
child: Container(
padding: const EdgeInsets.all(10),
margin: const EdgeInsets.all(10.0),
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.lime,
),
child: const Text("Title"),
),
),
);