问题
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("..."),
),
body: Container(
color: Colors.green,
child: OutlineButton(
onPressed: () { },
color: Colors.orange,
highlightColor: Colors.pink,
child: Container(
color: Colors.yellow,
child: Text("A"),
),
shape: CircleBorder(),
),
),
);
}
}
The above code gives a transparent button. How can I get an orange OutlineButton?
回答1:
To modify the backgroundColor of a OutlineButton you can use a DecoratedBox and a Theme widget. At the end of this answer you'll find a quick example.
Anyway I'd still recommend simply using the FlatButton with its color
attribute instead.
Wrap your OutlinedButton
inside a DecoratedBox
. Set the shape
of your DecoratedBox
to the same shape your OutlinedButton
. Now you can use the color
attribute of your DecoratedBox
to change the color. The result will still have a small padding around the OutlinedButton
. To remove this you can wrap the DecoratedBox
inside a Theme
in which you adjust the ButtonTheme
. Inside the ButtonTheme
you want to set materialTapTargetSize: MaterialTapTargetSize.shrinkWrap
.
The padding is added inside Flutter, to increase the tap area around the button to a minimum size of 48x48 (source). Setting materialTapTargetSize
to MaterialTapTargetSize.shrinkWrap
removes this minimum size.
FlatButton
example:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: FlatButton(
color: Colors.pinkAccent,
shape: CircleBorder(),
onPressed: () => {},
child: Text('A'),
),
),
),
);
}
}
OutlinedButton
example:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: MyButton(),
),
),
);
}
}
class MyButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DecoratedBox(
decoration:
ShapeDecoration(shape: CircleBorder(), color: Colors.pinkAccent),
child: Theme(
data: Theme.of(context).copyWith(
buttonTheme: ButtonTheme.of(context).copyWith(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap)),
child: OutlineButton(
shape: CircleBorder(),
child: Text('A'),
onPressed: () => {},
),
),
);
}
}
回答2:
Here's way that you can check the background color of the button. Remove hightlightColor, and try give some value to highlightElevation property of OutlineButton, then press it, you could see initially it loads orange color.
回答3:
You could use FlatButton, and just set color there.
来源:https://stackoverflow.com/questions/55370952/how-to-set-the-background-color-of-a-flutter-outlinebutton