gpt4 book ai didi

button - Flutter - 按下时更改 RaisedButton 的颜色

转载 作者:IT王子 更新时间:2023-10-29 07:17:34 25 4
gpt4 key购买 nike

我读到的所有内容都表明您可以使用 SetState 完成这项工作。这是我一直在使用的,它不会重绘。

class ServerSelectionState extends State<ServerSelection> {

bool server1Selected, server2Selected, server3Selected = false;

@override
void initState() {
setState(() {
server1Selected= false;
server2Selected= false;
server3Selected= false;
});
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
//Basically have an onTap method from a ListTile that opens a dialog, like this:
onTap: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
backgroundColor: greyTheme,
content: Form(
child: Container(
children: <Widget>[
ButtonTheme(
child: RaisedButton(
onPressed: (){
if (!mounted) return;
setState(() {
server1Selected = true;
server2Selected = false;
server3Selected = false;
});
},
color: server1Selected == true ? Colors.pink : Colors.blue,
child: Text(
'Server 1',
style: TextStyle(
color: Colors.red,
),
),
),
),
],
),
),
),
}
);
}

这将在热重载时很好地更新按钮颜色,但在那之前它似乎并不喜欢重绘。 if (!mounted) 部分防止了我看到的关于在重绘之前调用 dispose 或类似的错误,打印输出这是有效的,它正确地改变了 bool 值的状态,它实际上并没有更新颜色直到您强制重绘小部件。

最佳答案

showDialog 不能直接更改值,但要这样做,您的对话框必须是有状态的小部件。

从您的代码中可以看出,您必须创建另一个有状态的小部件,它返回整个警报对话框,如下面的代码所示。

您必须传递新有状态小部件所需的所有变量。

import 'package:flutter/material.dart';

class Homestack extends StatefulWidget {
@override
_HomestackState createState() => _HomestackState();
}

class _HomestackState extends State<Homestack> {


String dropdownValue ;

@override
Widget build(BuildContext context) {

return new Container(
color: Colors.blue,
padding: const EdgeInsets.all(20),
child: GestureDetector(
child: new Text("Tap ME!"),
onTap: (){
return showDialog(
context: context,
builder: (context){
return xyz(
server3Selected: false,
greyTheme: Colors.blueAccent,
server1Selected: false,
server2Selected: false,
);
}
);
},
)
);

}
}



class xyz extends StatefulWidget {

Color greyTheme ;
bool server1Selected;
bool server2Selected;
bool server3Selected;

xyz({Key key, this.greyTheme,this.server1Selected,this.server2Selected,this.server3Selected}): super(key: key);

@override
_xyzState createState() => _xyzState();
}

class _xyzState extends State<xyz> {
@override
Widget build(BuildContext context) {
return AlertDialog(
backgroundColor: widget.greyTheme,
content: Form(
child: Column(
children: <Widget>[
ButtonTheme(
child: RaisedButton(
onPressed: (){
if (!mounted) return;
setState(() {
widget.server1Selected = true;
widget.server2Selected = false;
widget.server3Selected = false;
});
},
color: widget.server1Selected == true ? Colors.pink : Colors.blue,
child: Text(
'Server 1',
style: TextStyle(
color: Colors.red,
),
),
),
),
],
),
),
);
}
}

关于button - Flutter - 按下时更改 RaisedButton 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56863411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com