Home > Mobile >  Flutter - How to reuse component: make a stateless or just a widget?
Flutter - How to reuse component: make a stateless or just a widget?

Time:02-24

I'm trying to know what is the best practice to reuse a component: Is it better to create a file with just a "widget method" or with a complete class with stateless/full widget?

For example, I would like to reuse the appbar, what is the best practice?

mainAppbar.dart

import 'package:flutter/material.dart';
import 'package:myapp/ressources/customColors.dart';

AppBar mainAppbar() {
  return AppBar(
    backgroundColor: Colors.white,
    title: Text(
      "Test",
      style: TextStyle(color: CustomColors.mainColor),
    ), 
    actions: [
      IconButton(
        icon: Icon(Icons.search, color: CustomColors.mainColor),
        onPressed: () {},
        splashRadius: 20,
      ),
      IconButton(
        icon: Icon(Icons.tune, color: CustomColors.mainColor),
        onPressed: () {},
        splashRadius: 20,
      ),
    ],
  );
}

OR

import 'package:flutter/material.dart';
import 'package:myapp/ressources/customColors.dart';

class MainAppBar extends StatelessWidget implements PreferredSizeWidget {
  final AppBar appBar;

  const MainAppBar({Key? key, required this.appBar}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      backgroundColor: Colors.white,
      title: Text(
        "Test",
        style: TextStyle(color: CustomColors.mainColor),
      ),
      actions: [
        IconButton(
          icon: Icon(Icons.search, color: CustomColors.mainColor),
          onPressed: () {},
          splashRadius: 20,
        ),
        IconButton(
          icon: Icon(Icons.tune, color: CustomColors.mainColor),
          onPressed: () {},
          splashRadius: 20,
        ),
      ],
    );
  }

  @override
  Size get preferredSize => Size.fromHeight(appBar.preferredSize.height);
}

In this example, I used the appbar, but it's the same question for all others components I would like to reuse :)

One more thing: i'm using GetX package!

Thank you!

CodePudding user response:

There is a very good resource on this question on Flutter's youtube channel.

Widgets vs helper methods | Decoding Flutter

You can also check out other videos in the playlist from here

CodePudding user response:

I don't really know about getX package but i think the first approach is better since nothing will change in the appBar making it a const so better to use the first approach so that whenever you call the build method, your appBar does not get re-rendered on the screen.

CodePudding user response:

i thing create a class is the better way because then you can use the class as a widget.

PS: i don't know anything about the getX package

  • Related