我试图在按下时更改凸起按钮的颜色,一段时间以来我一直遇到问题,我现在整个按钮小部件的代码是
children: <Widget>[
Expanded(
child: Container(
child: new SizedBox(
width: 15,
height: 60,
child: new RaisedButton(
color: pressed ? Color(0xFF1D1E33) : Colors.blue,
hoverColor: Colors.blueAccent,
focusColor: Colors.blueAccent,
child: Text(
'Male',
style: TextStyle(
fontSize: 26,
fontWeight: FontWeight.bold,
color: Colors.white),
textAlign: TextAlign.center,
),
onPressed: () => setState((){pressed = !pressed;})),
),
我也有一个如下所示的布尔值,但是运行代码“断言失败:布尔表达式不能为空”时收到错误消息
bool get pressed => null;
set pressed(bool pressed) {}
答案 0 :(得分:0)
您可以在下面复制粘贴运行完整代码
代码段
bool _pressed = false;
bool get pressed {
return _pressed;
}
set pressed(bool pressed) {
_pressed = pressed;
}
工作演示
完整代码
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
bool _pressed = false;
bool get pressed {
return _pressed;
}
set pressed(bool pressed) {
_pressed = pressed;
}
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
child: new SizedBox(
width: 100,
height: 60,
child: new RaisedButton(
color: pressed ? Color(0xFF1D1E33) : Colors.blue,
hoverColor: Colors.blueAccent,
focusColor: Colors.blueAccent,
child: Text(
'Male',
style: TextStyle(
fontSize: 26,
fontWeight: FontWeight.bold,
color: Colors.white),
textAlign: TextAlign.center,
),
onPressed: () => setState(() {
pressed = !pressed;
})))),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}