I want to conditionally display something in a Column in flutter.
Here's what I currently have:
Container(
height: blockSizeVertical * 99,
width: double.infinity,
padding: EdgeInsets.symmetric(vertical: 28, horizontal: 26),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
_buildCloseButton(context),
_buildTopCopy(context),
_buildEmailField(context),
_buildPasswordField(context),
_buildLoginButton(context),
_buildForgotPasswordLink(),
],
)));
Within this column, I want to conditionally display something while leaving _buildCloseButton
alone: something like this:
child: Container(
height: blockSizeVertical * 99,
width: double.infinity,
padding: EdgeInsets.symmetric(vertical: 28, horizontal: 26),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
_buildCloseButton(context),
_buildTopCopy(context), --------------
_buildEmailField(context), |
_buildPasswordField(context), | -> // I want to conditionally swap these out
_buildLoginButton(context), |
_buildForgotPasswordLink(),-----------
],
)))
What I've tried was something like this (but doesn't work)
List<Widget> _buildLoginScreen() {
return [
_buildTopCopy(context),
_buildEmailField(context),
_buildPasswordField(context),
_buildLoginButton(context),
_buildForgotPasswordLink(),
];
}
// ....
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
_buildCloseButton(context),
_forgetPasswordScreen
? ForgotPassword()
: _buildLoginScreen(),
],
)
However this doesn't work. Is there a way to achieve something like this?
Edit: I am on Dart 2.13.4
CodePudding user response:
You can use the spread operator with your condition:
children: <Widget>[
_buildCloseButton(context),
_forgetPasswordScreen
? ForgotPassword() :
...[
_buildTopCopy(context),
_buildEmailField(context),
_buildPasswordField(context),
_buildLoginButton(context),
_buildForgotPasswordLink(),]
],
Edit:
Try a different approach since you can't use the spread operator:
children: <Widget>[
_buildCloseButton(context),
if(_forgottenPasswordScreen)
ForgotPassword(),
if (!_forgetPasswordScreen)
for (var widget in [
_buildTopCopy(context),
_buildEmailField(context),
_buildPasswordField(context),
_buildLoginButton(context),
_buildForgotPasswordLink(),
])
widget ],
CodePudding user response:
Can you try the below code?
Widget _buildConditionTrue() {
return Column(
children: <Widget>[
_buildTopCopy(context),
_buildEmailField(context),
_buildPasswordField(context),
_buildLoginButton(context),
_buildForgotPasswordLink(),
]);
}
Widget _buildConditionFalse() {
return Column(
children: <Widget>[
_buildForgotPasswordLink(),
_buildEmailField(context),
_buildPasswordField(context),
_buildLoginButton(context),
_buildTopCopy(context),
]);
}
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
_buildCloseButton(context),
condition? _buildConditionTrue() : _buildConditionFalse(),
])