How to animate a container on click in flutter - flutter

I am new to flutter animation, I have a stopwatch screen with a container that contains the stopwatch, a container with a list of laps, and 3 floating action buttons that do three things, reset, play-pause and lap. I want the stopwatch container to animate up when clicking on the lap button and then animate down when clicking on the reset button.
class _StopWatchScreenState extends State<StopWatchScreen>
with SingleTickerProviderStateMixin {
final StopWatchTimer _stopWatchTimer = StopWatchTimer();
final _isHours = true;
late AnimationController controller;
bool isPlaying = false;
bool lapClicked = false;
double value = 150.0;
final ScrollController scrollController = ScrollController();
#override
void initState() {
super.initState();
controller =
AnimationController(vsync: this, duration: Duration(milliseconds: 200));
}
void dispose() {
super.dispose();
_stopWatchTimer.dispose();
scrollController.dispose();
controller.dispose();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Column(
children: [
Center(
child: Padding(
padding: EdgeInsets.only(top: value), // Issue here
child: AnimatedContainer(
child: Center(
child: StreamBuilder<int>(
stream: _stopWatchTimer.rawTime,
initialData: _stopWatchTimer.rawTime.value,
builder: (context, snapshot) {
final value = snapshot.data;
final displayTime = StopWatchTimer.getDisplayTime(
value!,
hours: _isHours);
return Text(
displayTime,
style: GoogleFonts.lato(
fontSize: 40.0, color: Colors.white),
);
})),
width: 350.0,
height: 450.0,
decoration: BoxDecoration(
border: Border.all(color: Colors.white, width: 5.0),
shape: BoxShape.circle),
duration: const Duration(milliseconds: 100),
curve: Curves.fastLinearToSlowEaseIn,
),
),
),
Visibility(
visible: lapClicked,
child: Container(
height: 280.0,
child: StreamBuilder<List<StopWatchRecord>>(
stream: _stopWatchTimer.records,
initialData: _stopWatchTimer.records.value,
builder: (context, snapshot) {
final value = snapshot.data;
if (value!.isEmpty) {
return Container();
}
Future.delayed(const Duration(milliseconds: 100), () {
scrollController.animateTo(
scrollController.position.maxScrollExtent,
duration: Duration(milliseconds: 200),
curve: Curves.easeOut);
});
return ListView.builder(
physics: BouncingScrollPhysics(),
itemCount: value.length,
itemBuilder: (context, index) {
final data = value[index];
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text(
'Lap ${index + 1}',
style: GoogleFonts.lato(
fontSize: 30.0, color: Colors.white70),
),
),
Padding(
padding: const EdgeInsets.only(right: 20.0),
child: Text('${data.displayTime}',
style: GoogleFonts.lato(
fontSize: 30.0,
color: Colors.white70)),
)
],
),
const Padding(
padding: EdgeInsets.only(top: 5.0),
child: Opacity(
opacity: 0.1,
child: Divider(
thickness: 1.5,
color: Colors.white70,
),
),
)
],
);
},
controller: scrollController,
);
},
),
),
),
],
),
floatingActionButton: Padding(
padding: const EdgeInsets.only(left: 30.0, bottom: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FloatingActionButton(
onPressed: () {
setState(() {
lapClicked = false;
value = 190.0;
});
controller.reverse();
_stopWatchTimer.onExecute.add(StopWatchExecute.reset);
},
child: const Icon(
Icons.refresh,
size: 30.0,
),
),
FloatingActionButton(
onPressed: () {
toggleIcon();
if (isPlaying == true) {
_stopWatchTimer.onExecute.add(StopWatchExecute.start);
} else {
_stopWatchTimer.onExecute.add(StopWatchExecute.stop);
}
},
child: AnimatedIcon(
icon: AnimatedIcons.play_pause,
size: 35.0,
progress: controller,
),
),
FloatingActionButton(
onPressed: () {
setState(() {
lapClicked = true;
value = 10.0;
});
_stopWatchTimer.onExecute.add(StopWatchExecute.lap);
},
child: const Icon(
Icons.timer,
size: 30.0,
),
),
],
),
),
),
);
}
void toggleIcon() {
setState(() {
isPlaying = !isPlaying;
isPlaying ? controller.forward() : controller.reverse();
});
}
}

Use Animated Container with visibility
see this for animated container
Visibility(
visible:true,//controll to click on your lap button
child: AnimatedContainer(),
)
Animated Container

I used AnimatedContainer to animate the stopwatch and fixed the animation issue by removing the padding property from the container and replacing it with a margin property

Related

Error: Expected an identifier, but got ')'

I got this error in debug console:
Launching lib\main.dart on Chrome in debug mode...
lib\main.dart:1
Error: Expected an identifier, but got ')'.
lib/apilar_codigo/stacked_all.dart:20
Try inserting an identifier before ')'.
StartPomodoro(end: ),
Failed to compile application.
Exited (sigterm)
How can I solved it?
This is my code:
startPomodoro.dart
class StartPomodoro extends StatefulWidget {
StartPomodoro({super.key, required this.end});
final DateTime end;
#override
State<StartPomodoro> createState() => _StartPomodoroState();
}
class _StartPomodoroState extends State<StartPomodoro>
with TickerProviderStateMixin {
final now = DateTime.now();
List<bool> isSelected = [true, false];
late Timer timer;
late AnimationController controller;
String get countText {
Duration count = controller.duration! * controller.value;
return controller.isDismissed
? '${controller.duration!.inHours.toString().padLeft(2, '0')}:${(controller.duration!.inMinutes % 60).toString().padLeft(2, '0')}:${(controller.duration!.inSeconds % 60).toString().padLeft(2, '0')}'
: '${count.inHours.toString().padLeft(2, '0')}:${(count.inMinutes % 60).toString().padLeft(2, '0')}:${(count.inSeconds % 60).toString().padLeft(2, '0')}';
}
double progress = 1.0;
bool LongBreak = true;
void notify() {
if (countText == '00:00:00') {}
}
#override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 0),
);
controller.addListener(() {
notify();
if (controller.isAnimating) {
setState(() {
progress = controller.value;
});
} else {
setState(() {
progress = 1.0;
LongBreak = true;
});
}
});
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor:
LongBreak ? const Color(0xffD94530) : const Color(0xff6351c5),
body: SizedBox(
height: 460,
child: Stack(
children: [
Positioned(
top: 220,
left: 16,
child: GestureDetector(
onTap: () {
if (controller.isDismissed) {
showModalBottomSheet(
context: context,
builder: (context) => Container(
height: 300,
child: CupertinoTimerPicker(
initialTimerDuration: controller.duration!,
onTimerDurationChanged: (time) {
setState(() {
controller.duration = time;
});
},
),
),
);
}
},
child: AnimatedBuilder(
animation: controller,
builder: (context, child) {
return Stack(
children: <Widget>[
Align(
alignment: Alignment.bottomCenter,
child: Container(
color: const Color(0xffD94530),
height: controller.value *
MediaQuery.of(context).size.height,
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment:
MainAxisAlignment.spaceAround,
children: <Widget>[
Expanded(
child: Align(
alignment: Alignment.center,
child: Align(
alignment: FractionalOffset.center,
child: Container(
width: MediaQuery.of(context)
.size
.width -
64,
height: 210,
decoration: const BoxDecoration(
color: Color.fromARGB(
255, 245, 245, 245),
boxShadow: [
BoxShadow(
color: Color(0x22000000),
blurRadius: 64,
blurStyle: BlurStyle.outer,
offset: Offset(0, 16),
),
],
),
child: Container(
padding: const EdgeInsets.all(24.0),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
const Text(
"Hyper focused on...",
style: TextStyle(
fontSize: 22.0,
fontWeight:
FontWeight.w600,
),
),
const SizedBox(height: 16),
Center(
child: Column(
mainAxisAlignment:
MainAxisAlignment
.center,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment
.center,
children: [
Text(
countText,
style:
const TextStyle(
letterSpacing:
4,
fontSize: 65.0,
color: Color(
0xff3B3B3B),
),
),
],
),
Row(
mainAxisAlignment:
MainAxisAlignment
.center,
children: const [
Text(
' Hours Minutes Seconds ',
style: TextStyle(
letterSpacing:
2,
fontSize: 20.0,
color: Color(
0xff3B3B3B),
),
),
],
),
],
),
),
],
),
),
),
),
),
),
),
],
),
),
],
);
}),
),
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
AnimatedBuilder(
animation: controller,
builder: (context, child) {
return const Padding(
padding: EdgeInsets.symmetric(
vertical: 2.0, horizontal: 15.0),
);
}),
AnimatedBuilder(
animation: controller,
builder: (context, child) {
return Padding(
padding: const EdgeInsets.symmetric(
vertical: 2.0, horizontal: 15.0),
child: FloatingActionButton.extended(
backgroundColor: const Color(0xffFAFAFA),
onPressed: () {
if (controller.isAnimating) {
controller.stop();
setState(() {
LongBreak = false;
});
} else {
controller.reverse(
from: controller.value == 0
? 1.0
: controller.value);
setState(() {
LongBreak = false;
});
}
},
icon: Icon(
controller.isAnimating
? Icons.pause
: Icons.play_arrow,
color: const Color(0xff3B3B3B),
),
label: Text(
controller.isAnimating ? "Pause" : "Start",
style:
const TextStyle(color: Color(0xff3B3B3B)),
)),
);
}),
],
),
),
],
),
),
),
);
}
AnimationController _buildClockAnimation(TickerProvider tickerProvider) {
return AnimationController(
vsync: tickerProvider,
duration: const Duration(milliseconds: 750),
);
}
void _animateLeftDigit(
int prev,
int current,
AnimationController controller,
) {
final prevFirstDigit = (prev / 10).floor();
final currentFirstDigit = (current / 10).floor();
if (prevFirstDigit != currentFirstDigit) {
controller.forward();
}
}
}
StackPages.dart
class StackPages extends StatelessWidget {
const StackPages({super.key});
#override
Widget build(BuildContext context) {
return Stack(
// ignore: prefer_const_literals_to_create_immutables
children: [
// ChartBar()
// PieChartSample1(),
// ToDoPage(),
StartPomodoro(end: ),
// HomePageTimerUI(),
],
);
}
}
How to get rid of this problem? I tried this but no luck:
StartPomodoro(end: end),
Thank you for any help you can offer
Parameter end is of type DateTime.
To get over this error provide value of type DateTime in end parameter.
Try following code:
StartPomodoro(end: DateTime.now().add(const Duration(days: 1)))
: Error: Expected an identifier, but got ':'.
../…/painting/_network_image_io.dart:147
Try inserting an identifier before ':'.
:rethrow;
^
: Error: Expected ';' after this.
../…/painting/_network_image_io.dart:146
});
^
: Error: Unexpected token ':'.
../…/painting/_network_image_io.dart:147
:rethrow;
getting this error in my code i haven't created anything yet but still showing this error it has to show the basic hello world counter interface,but its not showing that also ,what's the problem I am getting I don't know previously I creating a project but while I was in the middle of that project the same issue had occure after that project everytime if I creating a new project also it showing the same error.

How can I center a container?

This is my design for now:
I want to achive this design:
As you can see, the container starts at the top and want I want to do is center it like the second screenshot.
This is my code:
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pomodoro/5.hourglass_animation/countdown_timer/responsive.dart';
class StartPomodoro extends StatefulWidget {
const StartPomodoro({super.key, });
//final DateTime end;
#override
State<StartPomodoro> createState() => _StartPomodoroState();
}
class _StartPomodoroState extends State<StartPomodoro>
with TickerProviderStateMixin {
final now = DateTime.now();
List<bool> isSelected = [true, false];
late Timer timer;
late AnimationController controller;
String get countText {
Duration count = controller.duration! * controller.value;
return controller.isDismissed
? '${controller.duration!.inHours.toString().padLeft(2, '0')}:${(controller.duration!.inMinutes % 60).toString().padLeft(2, '0')}:${(controller.duration!.inSeconds % 60).toString().padLeft(2, '0')}'
: '${count.inHours.toString().padLeft(2, '0')}:${(count.inMinutes % 60).toString().padLeft(2, '0')}:${(count.inSeconds % 60).toString().padLeft(2, '0')}';
}
double progress = 1.0;
bool LongBreak = true;
void notify() {
if (countText == '00:00:00') {}
}
#override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 0),
);
controller.addListener(() {
notify();
if (controller.isAnimating) {
setState(() {
progress = controller.value;
});
} else {
setState(() {
progress = 1.0;
LongBreak = true;
});
}
});
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
ThemeData themeData = Theme.of(context);
return SafeArea(
child: Scaffold(
backgroundColor:
LongBreak ? const Color(0xffD94530) : const Color(0xff6351c5),
body: GestureDetector(
onTap: () {
if (controller.isDismissed) {
showModalBottomSheet(
context: context,
builder: (context) => Container(
height: 300,
child: CupertinoTimerPicker(
initialTimerDuration: controller.duration!,
onTimerDurationChanged: (time) {
setState(() {
controller.duration = time;
});
},
),
),
);
}
},
child: AnimatedBuilder(
animation: controller,
builder: (context, child) {
return Stack(
children: <Widget>[
Align(
alignment: Alignment.bottomCenter,
child: Container(
color: const Color(0xffD94530),
height: controller.value *
MediaQuery.of(context).size.height *
0.722,
),
),
Spacer(),
Padding(
padding: const EdgeInsets.all(8.0),
child: Responsive(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Align(
alignment: Alignment.bottomCenter,
child: Align(
alignment: FractionalOffset.bottomCenter,
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 2.0, horizontal: 15.0),
child: Container(
width: MediaQuery.of(context).size.width,
height: 210,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color:
const Color(0xffFAFAFA)
),
child: Container(
padding: const EdgeInsets.all(20.0),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
const Text(
"Hyper-focused on... (+add task)",
style: TextStyle(
fontSize: 22.0,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 16),
Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment
.center,
children: [
Text(
countText,
style: const TextStyle(
fontWeight:
FontWeight.w600,
letterSpacing: 4,
fontSize: 65.0,
color:
Color(0xff3B3B3B),
),
),
],
),
Row(
mainAxisAlignment:
MainAxisAlignment
.center,
children: const [
Text(
' Hours Minutes Seconds ',
style: TextStyle(
fontWeight:
FontWeight.w500,
letterSpacing: 2,
fontSize: 20.0,
color:
Color(0xff3B3B3B),
),
),
],
),
],
),
),
),
],
),
),
),
),
),
),
),
Spacer(),
Responsive(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment:
CrossAxisAlignment.stretch,
children: [
AnimatedBuilder(
animation: controller,
builder: (context, child) {
return Padding(
padding:
const EdgeInsets.symmetric(
vertical: 2.0,
horizontal: 15.0),
child:
FloatingActionButton.extended(
backgroundColor:
const Color(
0xffFAFAFA),
onPressed: () {
if (controller
.isAnimating) {
controller.stop();
setState(() {
LongBreak = false;
});
} else {
controller.reverse(
from: controller
.value ==
0
? 1.0
: controller
.value);
setState(() {
LongBreak = false;
});
}
},
icon: Icon(
controller.isAnimating
? Icons.pause
: Icons.play_arrow,
color: const Color(
0xff3B3B3B),
),
label: Text(
controller.isAnimating
? "Pause"
: "Start",
style: const TextStyle(
color: Color(
0xff3B3B3B)),
)),
);
}),
],
),
),
SizedBox(height: 10,),
],
),
),
),
],
);
}),
),
),
);
}
AnimationController _buildClockAnimation(TickerProvider tickerProvider) {
return AnimationController(
vsync: tickerProvider,
duration: const Duration(milliseconds: 750),
);
}
void _animateLeftDigit(
int prev,
int current,
AnimationController controller,
) {
final prevFirstDigit = (prev / 10).floor();
final currentFirstDigit = (current / 10).floor();
if (prevFirstDigit != currentFirstDigit) {
controller.forward();
}
}
}
For some reason, I'm unable to center the container, wrapped with the widget
center
and no luck, how can I center the timer container?
Thank you for any help you can offer
Its difficult to figure out the complete code because of lots of code and incorrect indentation. But as far as I can see, you are facing this problem because of using Spacer,
Spacer is pushing your floating button and the timer Container to its ends.
Try removing the Spacer and wrap the timer Container with Center and wrap it with Flexible this should solve your problem.
Your present code is roughly:
Column
|_ Timer Container
|_ Spacer
|_ Floating Button
Change it to:
Column
|_ Flexible
|_ Center
|_ Timer Container
|_ Floating Button
If you like to use Stack widget, use positional widget like Aling, Positioned on Stack. Based on your UI, using stack widget structure will be
return Stack(
children: <Widget>[
background(context),
Align(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: buildCounter(context),
),
),
Align(
alignment: Alignment.bottomCenter,
child: startPauseButtonBuild(),
),
],
);
Here is the full snippet, I've removed some part for minimal and padding widget to handle some space
void main() => runApp(MaterialApp(home: const StartPomodoro()));
class StartPomodoro extends StatefulWidget {
const StartPomodoro({
super.key,
});
#override
State<StartPomodoro> createState() => _StartPomodoroState();
}
class _StartPomodoroState extends State<StartPomodoro>
with TickerProviderStateMixin {
final now = DateTime.now();
List<bool> isSelected = [true, false];
late Timer timer;
late AnimationController controller;
String get countText {
Duration count = controller.duration! * controller.value;
return controller.isDismissed
? '${controller.duration!.inHours.toString().padLeft(2, '0')}:${(controller.duration!.inMinutes % 60).toString().padLeft(2, '0')}:${(controller.duration!.inSeconds % 60).toString().padLeft(2, '0')}'
: '${count.inHours.toString().padLeft(2, '0')}:${(count.inMinutes % 60).toString().padLeft(2, '0')}:${(count.inSeconds % 60).toString().padLeft(2, '0')}';
}
double progress = 1.0;
bool LongBreak = true;
void notify() {
if (countText == '00:00:00') {}
}
#override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 0),
);
controller.addListener(() {
notify();
if (controller.isAnimating) {
setState(() {
progress = controller.value;
});
} else {
setState(() {
progress = 1.0;
LongBreak = true;
});
}
});
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
ThemeData themeData = Theme.of(context);
return SafeArea(
child: Scaffold(
backgroundColor:
LongBreak ? const Color(0xffD94530) : const Color(0xff6351c5),
body: GestureDetector(
onTap: () {},
child: AnimatedBuilder(
animation: controller,
builder: (context, child) {
return Stack(
children: <Widget>[
background(context),
Align(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: buildCounter(context),
),
),
Align(
alignment: Alignment.bottomCenter,
child: startPauseButtonBuild(),
),
],
);
}),
),
),
);
}
Widget startPauseButtonBuild() {
return LayoutBuilder(
builder: (_, constraints) => Padding(
padding: const EdgeInsets.all(8.0),
child: AnimatedBuilder(
animation: controller,
builder: (context, child) {
return Padding(
padding:
const EdgeInsets.symmetric(vertical: 2.0, horizontal: 15.0),
child: SizedBox(
width: constraints.maxWidth,
child: FloatingActionButton.extended(
backgroundColor: const Color(0xffFAFAFA),
onPressed: () {},
icon: Icon(
controller.isAnimating ? Icons.pause : Icons.play_arrow,
color: const Color(0xff3B3B3B),
),
label: Text(
controller.isAnimating ? "Pause" : "Start",
style: const TextStyle(color: Color(0xff3B3B3B)),
),
),
),
);
}),
),
);
}
Column buildCounter(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Align(
alignment: Alignment.bottomCenter,
child: Container(
width: MediaQuery.of(context).size.width,
height: 210,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color(0xffFAFAFA)),
child: Container(
padding: const EdgeInsets.all(20.0),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
"Hyper-focused on... (+add task)",
style: TextStyle(
fontSize: 22.0,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 16),
Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
countText,
style: const TextStyle(
fontWeight: FontWeight.w600,
letterSpacing: 4,
fontSize: 65.0,
color: Color(0xff3B3B3B),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text(
' Hours Minutes Seconds ',
style: TextStyle(
fontWeight: FontWeight.w500,
letterSpacing: 2,
fontSize: 20.0,
color: Color(0xff3B3B3B),
),
),
],
),
],
),
),
),
],
),
),
),
),
),
],
);
}
Align background(BuildContext context) {
return Align(
alignment: Alignment.bottomCenter,
child: Container(
color: const Color(0xffD94530),
height: controller.value * MediaQuery.of(context).size.height * 0.722,
),
);
}
AnimationController _buildClockAnimation(TickerProvider tickerProvider) {
return AnimationController(
vsync: tickerProvider,
duration: const Duration(milliseconds: 750),
);
}
void _animateLeftDigit(
int prev,
int current,
AnimationController controller,
) {
final prevFirstDigit = (prev / 10).floor();
final currentFirstDigit = (current / 10).floor();
if (prevFirstDigit != currentFirstDigit) {
controller.forward();
}
}
}

setState() on showDialog() from initState() is not changing the state. Flutter

I have created a dialog with StatefulBuilder. Setstate works perfectly within the StatefulBuilder. But I want to change that state from initstate too. But the set state from initstate is not called.
My code:
#override
void initState() {
super.initState();
rest_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 15),
);
rest_controller.addListener(() {
if (rest_controller.isAnimating) {
setState(() {
print("rp"+rest_progress.toString());
rest_progress = rest_controller.value;
});
} else {
setState(() {
print("rp2"+rest_progress.toString());
rest_progress = 1.0;
rest_isPlaying = false;
});
}
});
}
Dialog open function:
showDataAlert() {
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(
20.0,
),
),
),
backgroundColor: kMainColor,
contentPadding: EdgeInsets.only(
top: 10.0,
),
title: Text(
"Take Rest",
style: TextStyle(fontSize: 24.0, color: kTextColor),
),
content:
Center(
child: Column(
children: [
SizedBox(
height: 10,
),
Expanded(
child: Stack(
alignment: Alignment.center,
children: [
SizedBox(
width: 260,
height: 260,
child: CircularProgressIndicator(
backgroundColor: Colors.grey.shade300,
value: rest_progress,
strokeWidth: 6,
),
),
AnimatedBuilder(
animation: rest_controller,
builder: (context, child) => Text(
restCountText,
style: TextStyle(
fontSize: 50,
fontWeight: FontWeight.bold,
color: kTextColor,
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
onTap: () {
if (rest_controller.isAnimating) {
rest_controller.stop();
setState(() {
rest_isPlaying = false;
});
} else {
rest_controller.reverse(from: rest_controller.value == 0 ? 1.0 : rest_controller.value);
setState(() {
rest_isPlaying = true;
});
}
},
child: RoundButton(
icon: rest_isPlaying == true ? Icons.pause : Icons.play_arrow,
),
),
GestureDetector(
onTap: () {
rest_controller.reset();
setState(() {
rest_isPlaying = false;
});
},
child: RoundButton(
icon: Icons.stop,
),
),
],
),
)
],
),
),
);
}
);
});
}
Basically, setstate from the initstate is not changing the state. I have tried to change the state from showDataAlert function also, but no luck. Only the state changes if I click the button inside the showdialog.

Change Text Widget Text Dynamically on Button Click

Here is my code. I am fetching the value TotalVotes from Firebase and showing its value in a Text-widget and I wanted to increase TotalVotes count when anyone hit button and update the Text widget. But I'm not able to update the Text-widget, and the value of the Text-widget updates only after refreshing the page.
Row(
children: <Widget>[
Text("Total Votes: $TotalVotes",
style: TextStyle(color: Colors.white, fontSize: 12)),
SizedBox(width: 30),
FadeAnimation(
2,
Container(
decoration: BoxDecoration(
color: Color(0xFFF1f94aa).withOpacity(.6),
borderRadius: BorderRadius.circular(8)),
child: Padding(
padding: const EdgeInsets.all(4.0),
child: FadeAnimation(
3,
InkWell(
child: ItemIcon(Icons.favorite_border, " Vote"),
onTap: () {
DatabaseReference database = FirebaseDatabase
.instance
.reference()
.child("Vote")
.child(Name);
database.once().then((DataSnapshot dataSnapshot) {
print(dataSnapshot.value['TotalVotes']);
String totalvote = (int.parse(
dataSnapshot.value['TotalVotes']) +
1)
.toString();
database.child("TotalVotes").set(totalvote);
setState(() {
TotalVotes = totalvote;
});
Fluttertoast.showToast(
msg: 'Voted Successfully');
});
},
)),
)),
),
],
),
Whole Widget Code
Widget VoteForTomorrowUi(String ImageUrl,String Name,String Price,String TotalVotes,)<------------------------------------
{
return
FadeAnimation(2,Container(
margin: EdgeInsets.only(right: 20),
height: 210,
width: 220,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Color(0xFFF082938)
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: Container(
width: 220,
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
image: DecorationImage(
image: NetworkImage(ImageUrl),
fit: BoxFit.fill
)
),
),
),
Container(
margin: EdgeInsets.all(10),
height: 51,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Price: "+Price, style: TextStyle(
color: Colors.white,
fontSize: 12
)),
SizedBox(height: 5),
Row(
children: <Widget>[
Text("Total Votes: $TotalVotes" ,style: TextStyle(
color: Colors.white,
fontSize: 12
)),
SizedBox(width: 30),
FadeAnimation(2, Container(
decoration: BoxDecoration(color:Color(0xFFF1f94aa).withOpacity(.6),borderRadius: BorderRadius.circular(8)
),
child: Padding(
padding: const EdgeInsets.all(4.0),
child: FadeAnimation(3,InkWell(
child: beacheItemIcon(Icons.favorite_border, " Vote"),
onTap: (){
DatabaseReference database = FirebaseDatabase.instance.reference()
.child("VoteForTomorrow").child(Name);
database.once().then((DataSnapshot dataSnapshot){
print(dataSnapshot.value['TotalVotes']);
String totalvote = (int.parse(dataSnapshot.value['TotalVotes'])+1).toString();
database.child("TotalVotes").set(totalvote);
setState(() {
TotalVotes = totalvote; <--------------------------
});
Fluttertoast.showToast(msg: 'Voted Successfully');
});
},
)
),
)),
),
],
)
])
)
],
),
) );
}
Fade Animation
class FadeAnimation extends StatelessWidget {
final double delay;
final Widget child;
FadeAnimation(this.delay, this.child);
#override
Widget build(BuildContext context) {
final tween = MultiTrackTween([
Track("opacity").add(Duration(milliseconds: 500), Tween(begin: 0.0, end: 1.0)),
Track("translateY").add(
Duration(milliseconds: 500), Tween(begin: -130.0, end: 0.0),
curve: Curves.easeOut)
]);
return ControlledAnimation(
delay: Duration(milliseconds: (500 * delay).round()),
duration: tween.duration,
tween: tween,
child: child,
builderWithChild: (context, child, animation) => Opacity(
opacity: animation["opacity"],
child: Transform.translate(
offset: Offset(0, animation["translateY"]),
child: child
),
),
);
}
}
Here is TotalVotes
void initState() {
super.initState();
DatabaseReference postRef = FirebaseDatabase.instance.reference().child("Category");
DatabaseReference postRef2 = FirebaseDatabase.instance.reference().child("VoteForTomorrow");
postRef2.once().then((DataSnapshot dataSnapshot2){
var Keys = dataSnapshot2.value.keys;
var Datas = dataSnapshot2.value;
voteForTomorrowList.clear();
for(var individualKey in Keys)
{
VoteForTomorrow voteForTomorrow = new VoteForTomorrow(
Datas[individualKey]['ImageUrl'],
Datas[individualKey]['Name'],
Datas[individualKey]['Price'],
Datas[individualKey]['TotalVotes'],
);
voteForTomorrowList.add(voteForTomorrow);
}
setState(() {
});
});
And this is how I'm calling the votefortommorow
VoteForTomorrowUi(voteForTomorrowList[index].ImageUrl, voteForTomorrowList[index].Name, voteForTomorrowList[index].Price, voteForTomorrowList[index].TotalVotes);
With out seeing your code as a whole I might be still a little confused but im using your widget and a FutureBuilder and this works
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<DataSnapshot>(
future: FirebaseDatabase.instance
.reference()
.child("VoteForTomorrow")
.child('Name')
.child('TotalVotes')
.once(),
builder:
(BuildContext context, AsyncSnapshot<DataSnapshot> snapshot) {
return Center(
child: VoteForTomorrowUi(
'https://static.photocdn.pt/images/articles/2017/11/29/articles/2017_8/iStock-641093712-min.jpg',
'Name',
'Price',
snapshot.data.value,
),
);
}),
);
}
}
I just put some dummy data in for the other values but the widget is the same the only thing I can think of is if you are reading and writing all your data properly you must be re-initializing TotalVotes every time the widget builds which is why you get the same value

how to add flexible height to showGeneralDialog on Flutter?

I added padding for transparent outside. But fixed height. How to change it?
padding: EdgeInsets.fromLTRB(20, 50, 20, 50),
Is it possible to remove above this line and flexible(center)?
I am expected like this flexible height alert. click here
onPressed: () {
showGeneralDialog(
context: context,
barrierColor: Palette.black.withOpacity(.3),
barrierDismissible: true,
transitionDuration: Duration(milliseconds: 400),
pageBuilder: (_, __, ___) {
return ChangePropertyPage(
propertyModel: propertyModel);
},
);
},
change Property Page
class ChangePropertyPage extends StatelessWidget {
final List<PropertyModel> propertyModel;
const ChangePropertyPage({Key key, this.propertyModel}) : super(key: key);
#override
Widget build(BuildContext context) {
final double width = CustomMediaQuery.width(context);
return Padding(
padding: EdgeInsets.fromLTRB(20, 50, 20, 50),
child: Material(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
PropertyListTileWidget(
mainTitle: 'USER\'S Name', subTitle: 'USER\'S Email'),
VerticalSpacing(height: 10),
CustomLine(
height: 1,
width: (width - 40) - 20,
color: Palette.black.withOpacity(.2),
),
Expanded(
child: ListView.builder(
itemCount: propertyModel.length,//now length is 1
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return InkWell(
onTap: ()async{
},
child: PropertyListTileWidget(
mainTitle: '${propertyModel[index].propertyName}',
subTitle: '${propertyModel[index].ownerUId}'),
);
}),
)
],
),
),
),
);
}
}
if you are expecting this:
then
full code:
import 'package:flutter/material.dart';
class CustomDialogBox extends StatefulWidget {
#override
_CustomDialogBoxState createState() => _CustomDialogBoxState();
}
class _CustomDialogBoxState extends State<CustomDialogBox> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Custom Dialog Box"),
centerTitle: true,
),
body:Center(
child:FlatButton(
color: Colors.blue,
onPressed: (){
showDialog(
context: (context),
child: ShowCustomDialogBox()
);
},
child: Text("Show Dialog")
)
) ,
);
}
}
class ShowCustomDialogBox extends StatefulWidget {
#override
State<StatefulWidget> createState() => ShowCustomDialogBoxState();
}
class ShowCustomDialogBoxState extends State<ShowCustomDialogBox>with SingleTickerProviderStateMixin {
AnimationController controller;
Animation<double> scaleAnimation;
#override
void initState() {
super.initState();
controller = AnimationController(vsync: this, duration: Duration(milliseconds: 450));
scaleAnimation =CurvedAnimation(parent: controller, curve: Curves.decelerate);
controller.addListener(() {
setState(() {});
});
controller.forward();
}
#override
Widget build(BuildContext context) {
return Center(
child: Material(
color: Colors.transparent,
child: ScaleTransition(
scale: scaleAnimation,
child: Container(
margin: EdgeInsets.all(20.0),
padding: EdgeInsets.all(8.0),
height: MediaQuery.of(context).size.height/2.5, //Change height of dialog box.
width: MediaQuery.of(context).size.width,
decoration: ShapeDecoration(
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0))),
child: Column(
children: <Widget>[
Expanded(
flex: 4,
child: ListView.builder(
itemCount: 10,
itemBuilder: (context, index){
return Column(
// mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text((index+1).toString(),style: TextStyle(color:Colors.blue,fontSize:40),),
Divider()
],
);
}
)
),
Padding(
padding: const EdgeInsets.only(
left: 20.0, right: 10.0, top: 0.0,),
child: ButtonTheme(
height: 35.0,
minWidth: MediaQuery.of(context).size.width/3.5,
child: RaisedButton(
color: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0)),
splashColor: Colors.white.withAlpha(40),
child: Text(
'Next',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 13.0),
),
onPressed: () {
setState(() {
Navigator.pop(context);
});
},
)
)
),
],
)
),
),
),
);
}
}