Как изменить цвет фона приподнятой кнопки во флаттере из функции?
Я новичок во Flutter, я начал флаттер на прошлой неделе, и теперь я хотел сделать простое приложение для ксилофона. Я успешно создал пользовательский интерфейс, но когда я создал функцию для воспроизведения звука, передав аргументы, она выдает мне эту ошибку.
**The following _TypeError was thrown building Body(dirty, state: _BodyState#051c2):
type '_MaterialStatePropertyAll<dynamic>' is not a subtype of type 'MaterialStateProperty<Color?>?'**
функция, которую я использую, такова.
void playSound(int soundNumber) {
final player = AudioCache();
player.play('note$soundNumber.wav');}
Expanded buildPlayButton({MaterialStateProperty color, int soundNumber}){
return Expanded(
child: ElevatedButton(
onPressed: () {
playSound(soundNumber);
},
style: ButtonStyle(
backgroundColor: color,
),
),
);}
Вот где я вызываю эту функцию.
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
buildPlayButton(color: MaterialStateProperty.all(Colors.red), soundNumber: 1),
buildPlayButton(color: MaterialStateProperty.all(Colors.orangeAccent), soundNumber: 2),
buildPlayButton(color: MaterialStateProperty.all(Colors.yellow), soundNumber: 3),
buildPlayButton(color: MaterialStateProperty.all(Colors.indigo), soundNumber: 4),
buildPlayButton(color: MaterialStateProperty.all(Colors.blue), soundNumber: 5),
buildPlayButton(color: MaterialStateProperty.all(Colors.lightGreenAccent), soundNumber: 6),
buildPlayButton(color: MaterialStateProperty.all(Colors.green), soundNumber: 7),
],
);
}
Пожалуйста, расскажите мне о вызове этой функции, потому что, когда я вызываю эту функцию, она дает мне вышеупомянутую ошибку ...
19 ответов
Вы можете стилизовать ElevatedButton с помощью статического метода styleFrom или класса ButtonStyle. Первый удобнее, чем второй.
Использование styleFrom для стилизации ElevatedButton:
ElevatedButton(
child: Text('Button'),
onPressed: () {},
style: ElevatedButton.styleFrom({
Color primary, // set the background color
Color onPrimary,
Color onSurface,
Color shadowColor,
double elevation,
TextStyle textStyle,
EdgeInsetsGeometry padding,
Size minimumSize,
BorderSide side,
OutlinedBorder shape,
MouseCursor enabledMouseCursor,
MouseCursor disabledMouseCursor,
VisualDensity visualDensity,
MaterialTapTargetSize tapTargetSize,
Duration animationDuration,
bool enableFeedback
}),
),
Пример:
ElevatedButton(
child: Text('Button'),
onPressed: () {},
style: ElevatedButton.styleFrom(
primary: Colors.purple,
padding: EdgeInsets.symmetric(horizontal: 50, vertical: 20),
textStyle: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold)),
),
Использование ButtonStyle для стилизации ElevatedButton:
style: ButtonStyle({
MaterialStateProperty<TextStyle> textStyle,
MaterialStateProperty<Color> backgroundColor,
MaterialStateProperty<Color> foregroundColor,
MaterialStateProperty<Color> overlayColor,
MaterialStateProperty<Color> shadowColor,
MaterialStateProperty<double> elevation,
MaterialStateProperty<EdgeInsetsGeometry> padding,
MaterialStateProperty<Size> minimumSize,
MaterialStateProperty<BorderSide> side,
MaterialStateProperty<OutlinedBorder> shape,
MaterialStateProperty<MouseCursor> mouseCursor,
VisualDensity visualDensity,
MaterialTapTargetSize tapTargetSize,
Duration animationDuration,
bool enableFeedback
})
Пример
ElevatedButton(
child: Text('Button'),
onPressed: () {},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.red),
padding: MaterialStateProperty.all(EdgeInsets.all(50)),
textStyle: MaterialStateProperty.all(TextStyle(fontSize: 30))),
),
Передайте цвет в качестве параметра и используйте MaterialStateProperty.all<Color>(color), чтобы указать цвет.
buildPlayButton(color: Colors.red, soundNumber: 1)
Expanded buildPlayButton({Color color, int soundNumber}){
return Expanded(
child: ElevatedButton(
onPressed: () {
playSound(soundNumber);
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(color),
),
),
);}
Кнопка образца
Вы можете установить цвет фона следующим образом:
ElevatedButton(
onPressed: resetHandler,
child: Text("button"),
style: ElevatedButton.styleFrom(primary: Colors.amber),
),
Просто используйте
MaterialStateProperty.all(**YOUR COLOR**)
:
ElevatedButton(
child: Text('Button'),
onPressed: () {},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.red),)
),
У вас есть 3 варианта изменения цвета фона:
ElevatedButton.styleFrom : если вы просто хотите изменить цвет фона и цвет переднего плана независимо от состояний, вы можете сделать, как указано ниже.
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red, // background
onPrimary: Colors.white, // foreground
),
onPressed: () { },
child: Text('custom foreground/background'),
)
MaterialStateProperty.all : переопределить цвет фона ElevatedButtons по умолчанию (текст/значок) для всех состояний.
ElevatedButton(style:
ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.red),
onPressed: () { },
child: Text('custom foreground/background'),
));
MaterialStateProperty.resolveWith : по умолчанию кнопка с повышенными правами наследует синий цвет. Мы можем настроить стиль по умолчанию, используя параметр стиля и класс ButtonStyle. Кнопка имеет разные состояния, такие как нажатая, отключенная, наведенная и т. д. Вы можете изменить стиль для каждого состояния. В приведенном ниже фрагменте цвет кнопки по умолчанию меняется на зеленый при нажатии.
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed))
return Colors.green;
return null; // Use the component's default.
},
),
),
)
Предположим, нам нужно изменить цвет фона кнопки с повышенными правами? Кнопка с повышенными правами имеет свойство стиля, а свойство стиля требует ButtonStyle(). ButtonStyle имеет свойство backgroundColor, для которого требуется свойство MaterialStateProperty. Вы можете просто назначить цвет фона с помощью MaterialStateProperty.all(Colors.green). Давайте рассмотрим примеры цвета фона кнопки Elevated во Flutter.
ElevatedButton(
onPressed: () {
print('Button Pressed');
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(Colors.green),
),
child: Text('Send'),
),
Текущий лучший ответ на примереElevatedButton.styleFrom
устарел. Начиная с Flutter v3.1.0, основной параметр устарел.
Color? primary // Use foregroundColor instead. This feature was deprecated after v3.1.0.
Вместо этого используйтеbackgroundColor
параметр:
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: const Colors.red,
),
onPressed: () {},
child: const Text('Test'),
)
Скриншот:
Код:
class _MyState extends State<MyPage> {
bool _flag = true;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () => setState(() => _flag = !_flag),
child: Text(_flag ? 'Red' : 'Green'),
style: ElevatedButton.styleFrom(
primary: _flag ? Colors.red : Colors.teal, // This is what you need!
),
),
),
);
}
}
Вы можете просто использовать этот код внутриElevatedButton
style: ElevatedButton.styleFrom(
backgroundColor:Theme.of(context).primaryColor
),
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
body:Center(
child: ElevatedButton(
onPressed: () {},
child: Text("click me"),
style:ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green))
),
),
} }
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
primary: HexColor(HexColor.primarycolor),
textStyle: TextStyle(fontWeight: FontWeight.bold)),
ElevatedButton(
onPressed: (){},
child: Text('comprar'),
style: ElevatedButton.styleFrom(
primary: Theme.of(context).primaryColor
)
)
Вам необходимо установитьprimary
свойство (внутри стиля) и назначьте ему цвет, но будьте осторожны, если вы не установили свойonPressed()
событие, то цвет не меняется..
Вот пример:
Widget renderMyButton() {
return ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.lightBlue, // Change the color here..
elevation: 0,
// ...
),
onPressed: () {}, // This line is important to change the ElevatedButton color..
child: Container()
);
}
Использовать стиль из ElevatedButton
ElevatedButton(
onPressed: (){},
child: Text('click me'),
style: ElevatedButton.styleFrom(backgroundColor: Colors.green),
),
style: ButtonStyle({
MaterialStateProperty.all(backgroundColor),
),
Точно так же вы можете добавить
MaterialStateProperty.all(<Value here>)
к большинству свойств кнопки с повышенным уровнем (высота, отступ, граница и т. д.).
Обязательно добавьте onPressed: () {},
иначе цвет будет серый
Если вы хотите изменить цвет фона приподнятой кнопки и цвет контура, а также форму круга, проверьте этот код:
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white,
side: BorderSide(
width: 1,
color: primaryBlue),
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(
20,
))),
onPressed: () {},
child: Text(
'Use camera',
style: t3b,
),
),
Этот код будет выглядеть так:
ElevatedButton(стиль: ButtonStyle(backgroundColor: MaterialStatePropertyAll(Colors.orange)),onPressed: null,);