最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Widget simple declaration flutter - Stack Overflow

programmeradmin0浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 2

Yes, 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"),
    ),
  ),
);
发布评论

评论列表(0)

  1. 暂无评论