我有一个自定义小部件类:
class FancyButton extends StatefulWidget
{
final Function() onTap;
final String text;
final IconData icon;
bool enabled;
FancyButton({this.onTap, this.text, this.icon, this.enabled = true})
@override
_FancyButtonState createState()
{
return _FancyButtonState(onTap, text, icon, enabled);
}
}
class _FancyButtonState extends State<FancyButton> with SingleTickerProviderStateMixin
{
Function() onTap;
String text;
IconData icon;
bool enabled;
_FancyButtonState(this.onTap, this.text, this.icon, this.enabled);
@override
Widget build(BuildContext context) {
if(!enabled)
{
print("build disabled");
}
return GestureDetector(
onTap: onTap,
child: Container(
color: enabled ? Colors.red : Colors.green,
height: 20
),
);
}
}
我这样使用它:
Widget continueButton = new StreamBuilder(
stream: viewModel.canFinishProfile.asBroadcastStream(),
initialData: viewModel.canFinishProfile.value,
builder: (builder, snapshot)
{
print("can finish profile " + viewModel.canFinishProfile.value.toString());
return FancyButton(
text: multilang.get("auth_continue"),
enabled: viewModel.canFinishProfile.value,
onTap: ()
{
viewModel.onClickedContinue.add(null);
},
);
},
)
所以我希望小部件在 canFinishProfile 值更改后更新。问题是一旦 canFinishProfile 值更改,FancyButton 的状态就不会更新,因此总是会绘制旧的小部件视图。请注意,如果我将 FancyButton 更改为 StatelessWidget 并将其构建代码放在 StatelessWidget 中,那么它会重新绘制一次,然后 canFinishProfile 值更改。但是,我需要它成为一个更复杂的功能的 StatefulWidget。