0

I have migrated to Flutter 2.0 which is just the new release now. In my project I have used Flat Buttons but it got deprecated now in Flutter 2.0 and the suggestion pop up to use Text Button instead of Flat Buttons.

Now the problem is in Flat Buttons there are option directly to set the properties of button such as color, padding etc. but when I replaced it with Text Button there is error in using this properties. I have checked the documentation and found that there is the property of style: ButtonStyle(backgroundcolor: ____________). But when I have put Colors.blue in the backgroundcolor property it gives me error.

So I want to know that how is the behaviour of Buttons in Flutter 2.0 and how we can style the Buttons?

My snippet of code is here in which I want to style the button.

Container(
                  width: 200.0,
                  child: TextButton(
                    style: ButtonStyle(), // I want to style this.
                    onPressed: () => Navigator.pushNamed(context, SignupPage.id),
                    /*color: Colors.blue,
                    padding: const EdgeInsets.all(10.0),*/ //Commented code is deprecated in Flutter 2.0
                    child: Text(
                      'Create Account',
                      style: TextStyle(color: Colors.white, fontSize: 16.0),
                    ),
Harry
  • 154
  • 4
  • 15

3 Answers3

0

The style argument with a backgroundcolor is the way to do it, but does not take a Color object, its type is MaterialStateProperty<Color?>? so you should provide an object of that type.

documentation is here https://api.flutter.dev/flutter/material/TextButton-class.html
and here https://api.flutter.dev/flutter/material/ButtonStyle-class.html

Stephen
  • 4,041
  • 22
  • 39
0

Buttons now have a state, so you have to define the colors for each state:

  • you can define one color for all the states.

    ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.green),

  • you can define a different color for each state.

    ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith( (Set states) { if (states.contains(MaterialState.pressed)) return Theme.of(context).colorScheme.primary.withOpacity(0.5); return null; // Use the component's default. }, ), ),

0

ButtonStyle does not accept simple properties like color, padding etc. It accepts something called as MaterialStateProperty which, if confusing, there is a convenient alternative method called styleForm, which accepts above mentioned simple parameters and converts them internally into MaterialStateProperty. You can use the method as shown below:

TextButton(
    style: TextButton.styleFrom(
      backgroundColor: const Color(0xff777777)
    ),
    onPressed: () {},
    child: Text("Change The World")
)

Refer to this for more properties accepted by the styleForm method: https://api.flutter.dev/flutter/material/TextButton/styleFrom.html