Several screens with similar widgets - how to code (Flutter, Dart)

1,037

I had a similar problem last week. The log in screen and the sign up screen are very similar, or at least the top banner portion of them.

screen shots of login and sign up screens

What I did was to create my own widget for both screens to use.

The code for this customize widget:

class AuthBanner extends StatelessWidget {
  const AuthBanner({
    Key key,
    @required this.text,
  }) : super(key: key);

  final String text;

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
            image: DecorationImage(
          image: AssetImage(backdrop),
          fit: BoxFit.cover,
        )),
        height: 220,
        width: double.infinity,
        child: Stack(
          children: [
            Align(
              alignment: Alignment.bottomLeft,
              child: Padding(
                padding: const EdgeInsets.only(left: 30.0, bottom: 20.0),
                child: Text(text.toUpperCase(),
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 32,
                      fontWeight: FontWeight.w600,
                    )),
              ),
            ),
          ],
        ));
  }
}

This can be used similar to other widgets, such as Text widget. For example, if I'm on the log in screen, I use:

AuthBanner(text: "login")

Share:
1,037
LoveCoding
Author by

LoveCoding

Updated on December 10, 2022

Comments

  • LoveCoding
    LoveCoding over 1 year

    I have a project with several screens that always contain a class with a body and a parent widget (which is a Card in my case). The parent widget has similar attributes all the time but different children like button, text, or container, etc..

    My question is: Should I just copy the code of the parent widget (the Card) every time for every single screen? Or is it best practice to put the Card into another class or function or widget which only contains the Card (so that I would have the entire code of the Card only one single time)?

    I would really appreciate if someone could write a code example.

    • Rubens Melo
      Rubens Melo about 5 years
      Extract the code from Card to another class and reuse it wherever you need.