EN VI

flutter center text inside button?

2024-03-15 11:00:05
How to flutter center text inside button

I cannot work out why this text is not centering inside the button:

                  SizedBox(
                    width: 30,
                    height: 30,
                    child: ElevatedButton(
                      onPressed: () {
                        FavourDown();
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.black, // background color
                        elevation: 5,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(20), // button's shape
                        ),
                      ),
                      child: const Text(
                        '-',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),

Result:

button

EDIT:

FULL ANSWER:

                  Material(
                    elevation: 20,
                    child: InkWell(
                      onTap: () {
                        FavourUp();
                      },
                      child: Container(
                        width: 30,
                        height: 30,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(12),
                          color: Colors.black,
                        ),
                        child: Center(
                          child: Text(
                            '+',
                            style:TextStyle(
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),

Solution:

Elevated button is a fixed component, you can't customise it to your own sizes. (You could just set padding to EdgeInsets.zero in style of elevated button)

Better to use a Container and decoration to make your own button and Use the Centre() widget to centre the text in the container of your preference.

Here is an example :

      InkWell(
          onTap: () {
            // Logic
          },
          child: Container(
            height: 20, // any size you want
            width: 100,// any size you want
            decoration: BoxDecoration(color: Colors.blue),
            child: Center(
              child: Text('Hello, World!'),
            ),
          ),
        ),

Hope this helped

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login