我正在使用库flutter_colorpicker库。我的Widget有一个名为isEditing的变量,用于知道屏幕处于编辑模式。编辑模式从sqlite数据库中获取一些数据,将其放在屏幕上,并稍微更改保存按钮的逻辑。
当isEditing为false时,ColorPicker工作正常。但它在编辑模式下不起作用。当我在颜色选择器上点击就绪时,容器不会改变颜色,数据库中的颜色保持不变。
有人知道发生了什么吗?谢谢大家。
class ManageCategory extends StatefulWidget {
const ManageCategory({Key? key, required this.isEditing, this.category})
: super(key: key);
final bool isEditing;
final Map<String, dynamic>? category; // <- Loaded trough sqflite in parent class.
@override
State<ManageCategory> createState() => _ManageCategoryState();
}
class _ManageCategoryState extends State<ManageCategory> {
String title = '';
final _nameController = TextEditingController();
final _descController = TextEditingController();
Color _color = Colors.blue;
final _dbInstance = TimeManagerDB.instance;
@override
Widget build(BuildContext context) {
if (widget.isEditing) {
title = 'Edit category';
_nameController.text = widget.category!['name'];
_descController.text = widget.category!['desc'];
_color = Color(widget.category!['color']);
} else {
title = 'Create category';
}
return Scaffold(
appBar: AppBar(
title: Text(title),
actions: widget.isEditing
? [
IconButton(onPressed: onDelete, icon: const Icon(Icons.delete)),
]
: null,
),
body: ListView(
padding: const EdgeInsets.all(16.0),
children: [
Text(
'Nome',
style: Theme.of(context).textTheme.displayMedium,
),
TextField(
controller: _nameController,
decoration: const InputDecoration(border: OutlineInputBorder()),
),
const SizedBox(height: 24.0),
Text(
'Descrição',
style: Theme.of(context).textTheme.displayMedium,
),
TextField(
controller: _descController,
decoration: const InputDecoration(border: OutlineInputBorder()),
maxLines: 4,
),
const SizedBox(height: 24.0),
Row(
children: [
Container(
height: 60.0,
width: 18.0,
color: _color,
),
const SizedBox(width: 16.0),
Text(
'Cor',
style: Theme.of(context).textTheme.displayMedium,
),
const Spacer(),
ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Choose a color!'),
content: SingleChildScrollView(
child: ColorPicker(
pickerColor: _color,
enableAlpha: false,
onColorChanged: (color) {
_color = color;
},
),
),
actions: <Widget>[
ElevatedButton(
child: const Text('Ready'),
onPressed: () {
setState(() {
Navigator.of(context).pop();
});
},
),
],
);
});
},
child: const Text("Choose"),
),
],
),
const SizedBox(height: 64.0),
Center(
child: ElevatedButton(
onPressed: onSave,
child: const Text('Save'),
),
),
],
),
);
}
}
2条答案
按热度按时间lsmd5eda1#
嘿,应该用setState重建UI:
xkrw2x1b2#
我解决了将变量初始化移动到initState()的问题。
}