What am I doing: I want to show button text and one more button one under the other.
Problem: When I click the button, the text and the other button at the bottom change places.
How can I fix this problem?
return Scaffold(
body: Consumer2<ThemeNotifier, RecorderNotifier>(
builder: (context, theme, recorder, child) => Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: 32.0),
Center(
child: Stack(
alignment: Alignment.center,
children: [
Visibility(
visible: recorder.isRecording,
child: Lottie.asset('assets/recording_animation.json'),
),
Container(
decoration: BoxDecoration(
color: mRed,
border: recorder.isRecording ? null : Border.all(),
shape: BoxShape.circle,
),
child: IconButton(
color: mWhiteColor,
iconSize: MediaQuery.of(context).size.width * 0.3,
icon: Icon(
recorder.isRecording
? Icons.stop_rounded
: Icons.keyboard_voice_outlined,
),
onPressed: () => recorder.isRecording
? RecorderService().stopRecord(recorder)
: RecorderService().startRecord(recorder),
),
),
],
),
),
const SizedBox(height: 32.0),
const Text(
'Example',
style: TextStyle(fontSize: 32.0),
),
const SizedBox(height: 32.0),
],
),
),
);
2
Answers
In the
Visibility
widget, add themaintainState
property and set it to true. This ensures that when the visible property is set to false, the state of the widget is still maintained. This prevents the text and the other button at the bottom from changing places when you click the button.Adding this property helps maintain the widget’s state and layout even if it’s not visible. This prevents the layout from shifting when the visibility changes.
When you use a Stack, the widgets are placed on top of each other in the order they’re created. In your case, there’s a Container with an IconButton on top of a Lottie animation.
When you hide the Lottie animation, it changes the order of the widgets in the Stack, which can move the IconButton to a different spot. To fix this, you can use the Positioned tool to place the Container and Lottie animation based on the top and bottom of the screen.