import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
home: const RootPage(),
);
}
}
class RootPage extends StatefulWidget {
const RootPage({super.key});
#override
State<RootPage> createState() => _RootPageState();
}
class _RootPageState extends State<RootPage> {
int value = 75;
Timer? _timer;
#override
void dispose() {
_timer?.cancel();
super.dispose();
}
void valuerandomer() {
_timer = Timer.periodic(
Duration(milliseconds: 500),
(t) {
int count = 0;
int max = 1000;
int min = 1;
Random rnd = new Random();
while (count != -1) {
count++;
value += rnd.nextInt(6) + (-5);
}
if (value > (max - 1)) {
value = 999;
} else if (value < 0) {
value = 0;
}
print(value);
setState(() {});
},
);
}
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromARGB(255, 12, 12, 12),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Stack(
alignment: Alignment.center,
children: [
Image.asset('images/SQUARE.png'),
Center(
child: Text(
'$valuerandomer()',
textAlign: TextAlign.center,
style: TextStyle(
color: Color.fromARGB(255, 255, 106, 0),
fontSize: 90,
fontFamily: "MyFont"),
),
),
],
),
],
),
);
}
}
The output of the code:
I want the function to print every 500 miliseconds in the text widget so the value parameter starts with the value of 75 and changes every 500 milliseconds with this function. How do I do that? How do I declare this function in the text widget like Text('$valuerandomer')? cuz its just dont work. I tried just to type there $value but still doesnt work.
You wrote that your value has to change but it's not really clear how it should change and what your valuerandomer tries to do.
My guess is that your are trying to randomize a number between min and max. And this should happen count times.
EDIT: This code now runs forever and changes the number.
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
home: const RootPage(),
);
}
}
class RootPage extends StatefulWidget {
const RootPage({super.key});
#override
State<RootPage> createState() => _RootPageState();
}
class _RootPageState extends State<RootPage> {
ValueNotifier<int> valueNotifier = ValueNotifier(75);
late final Timer? _timer;
final Random rnd = Random();
final Duration duration = const Duration(milliseconds: 500);
final int max = 1000;
final int min = 1;
#override
void dispose() {
_timer?.cancel();
super.dispose();
}
#override
void initState() {
super.initState();
valuerandomer();
}
void valuerandomer() {
_timer = Timer.periodic(
duration,
(Timer t) {
int value = rnd.nextInt(max-min) + min;
valueNotifier.value = value;
},
);
}
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromARGB(255, 12, 12, 12),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Stack(
alignment: Alignment.center,
children: [
Center(
child: ValueListenableBuilder<int>(
valueListenable: valueNotifier,
builder: (context, value, child) {
return Text(
'$value',
textAlign: TextAlign.center,
style: const TextStyle(
color: Color.fromARGB(255, 255, 106, 0),
fontSize: 90,
fontFamily: "MyFont"),
);
}
),
),
],
),
],
),
);
}
}
First of all we call valueRandomer to start the timer. The method itself does nothing else. The timer calls the callback function every 0.5 seconds. Inside the callback function we generate a random number between min and max.
The rnd.nextInt(num) actually just generates number between 0 and num. That's why we need interval shifting. Substract by min to get the range between 0 and (max-min). After that we add min back to number to get our real random number in our range.
Finally we set the value of the ValueNotifier to the newly generated number. ValueNotifier and ValueListenableBuilder are pretty handy in this case. The ValueListenableBuilder rebuilds itself whenever the ValueNotifier changes its value. We dont need to call setState here anymore because ValueListenableBuilder handles that for us.
It says void function because your function returns void type void valuerandomer() . Try changing it to String valuerandomer and return your value at the end of the function.
Related
I have a word: money. I want to show every letter from that word after 2 seconds delay: First show letter m, after 2 seconds on screen should be visible: m-o, after next two seconds: m-o-n etc. I am thinking about save every letter to array: [m-, o-,n-,e-,y] and after that using Timer add Text.
Things which I don't know how achieve: how can I split this word to this array? And How add/show Text using Timer.
Let's follow your approach and make it happen.
To make an array from word, use split("") and it will return a list of string.
Like this
List<String> _totalChar = "money".split("");
Result
Full Widget
If you want to play it on start, put _textAnimationSetUp() inside initState(). BTW, I'm not focusing on button state. Let me know if you face any trouble with this widget.
import 'dart:async';
import 'package:flutter/material.dart';
class AnimatedText extends StatefulWidget {
AnimatedText({Key? key}) : super(key: key);
#override
_AnimatedTextState createState() => _AnimatedTextState();
}
class _AnimatedTextState extends State<AnimatedText> {
Timer? timer;
String buttonText = "play";
///* let's make list from word
List<String> _totalChar = "money".split("");
List<String> _visibleChar = [];
int currentIndex = 0;
_textAnimationSetUp() async {
timer = Timer.periodic(Duration(seconds: 2), (timer) {
setState(() {
if (currentIndex < _totalChar.length)
_visibleChar.add(
"${currentIndex > 0 ? "-" : ""}${_totalChar[currentIndex++]}");
else
timer.cancel();
});
});
}
get _textStyle => TextStyle(
fontSize: 40,
);
#override
void dispose() {
if (timer != null && timer!.isActive) timer!.cancel();
super.dispose();
}
_play() async {
setState(() {
currentIndex = 0;
_visibleChar.clear();
buttonText = "restart";
});
if (timer != null && timer!.isActive) timer!.cancel();
_textAnimationSetUp();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
//* removing everything except letter and -
_visibleChar
.toString()
.replaceAll(" ", "")
.replaceAll(",", '')
.replaceAll("[", '')
.replaceAll("]", ""),
style: _textStyle,
),
ElevatedButton(
onPressed: () {
_play();
setState(() {});
},
child: Text(buttonText),
),
],
),
),
);
}
}
Install :
dependencies:
animated_text: ^1.0.2
Then :
import 'package:animated_text/animated_text.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool play = true;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Animated Text'),
),
body: Container(
color: Colors.white,
child: Column(
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width,
height: 300,
child: AnimatedText(
alignment: Alignment.center,
speed: Duration(milliseconds: 1000),
controller: AnimatedTextController.loop,
displayTime: Duration(milliseconds: 1000),
wordList: ['animations.', 'are.', 'easier.', 'now.'],
textStyle: TextStyle(
color: Colors.black,
fontSize: 55,
fontWeight: FontWeight.w700),
),
),
],
),
),
);
}
}
You can use Future delay for every letter. Something like this:
timer() async {
await Future.delayed(Duration(milliseconds: 200));
setState(() {
letterVisible = true;
});
}
Objective : I want to have different timing duration for each color
Blue = 2 seconds
Red = 5 seconds
Green = 1 seconds
Yellow = 8 seconds
I got the code from here How to render child without parent when using setState?,
import 'dart:async';
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(MaterialApp(debugShowCheckedModeBanner: false, home: Sample()));
}
class Sample extends StatelessWidget {
#override
Widget build(BuildContext context) {
print("Parent Widget rebuild");
return SafeArea(
child: Column(
children: [
Container(
height: 50,
width: 50,
color: Colors.red,
),
SizedBox(height: 20),
ChangingColor(),
],
),
);
}
}
class ChangingColor extends StatefulWidget {
#override
_ChangingColorState createState() => _ChangingColorState();
}
class _ChangingColorState extends State<ChangingColor> {
Timer _timer;
Color _color;
List<Color> arrColors = [Colors.blue, Colors.red, Colors.green, Colors.yellow] ;
int _pos =0;
List<int> arrSeconds = [2,5,1,8]; //here I set array for seconds
#override
void initState() {
for (var e in arrSeconds) {
_timer = Timer.periodic(Duration(seconds: e), (Timer t) { //I want the array looping using different seconds
print("seconds: $e");
setState(() {
_pos = (_pos + 1) % arrColors.length;
});
});}
super.initState();
}
#override
Widget build(BuildContext context) {
print("Child Widget rebuild");
return Container(
height: 50,
width: 50,
color: arrColors[_pos],
);
}
#override
void dispose() {
_timer.cancel();
_timer = null;
super.dispose();
}
}
The problem is seems like the timer did not finish yet but the color keep changing. Should I use async?
Please try this:
import 'dart:async';
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(MaterialApp(debugShowCheckedModeBanner: false, home: Sample()));
}
class Sample extends StatelessWidget {
#override
Widget build(BuildContext context) {
print("Parent Widget rebuild");
return SafeArea(
child: Column(
children: [
Container(
height: 50,
width: 50,
color: Colors.red,
),
SizedBox(height: 20),
ChangingColor(),
],
),
);
}
}
class ChangingColor extends StatefulWidget {
#override
_ChangingColorState createState() => _ChangingColorState();
}
class _ChangingColorState extends State<ChangingColor> {
Timer _timer;
Color _color;
List<Color> arrColors = [Colors.blue, Colors.red, Colors.green, Colors.yellow] ;
int _pos =0;
List<int> arrSeconds = [2,5,1,8]; //here I set array for seconds
#override
void initState() {
super.initState();
doSomething();
}
#override
Widget build(BuildContext context) {
print("Child Widget rebuild");
return Container(
height: 50,
width: 50,
color: arrColors[_pos],
);
}
#override
void dispose() {
_timer.cancel();
_timer = null;
super.dispose();
}
Future<void> doSomething() async {
var second=0;
var colorCount=1;
var count=0;
var totalList=[];
for(var e in arrSeconds){
count=count+e;
totalList.add(count);
}
print(totalList);
_timer = Timer.periodic(Duration(seconds: 1), (Timer t) {
if(totalList[totalList.length-1]==second){
_timer.cancel();
setState(() {
_pos=0;
});
doSomething();
}else{
if(totalList.contains(second)){
setState(() {
_pos =colorCount;
colorCount++;
print(second);
});
}
}
second++;
});
}
}
In my code below, I am struggling with LifeCyrles in Flutter where I can update my State in Provider, APPARENTLY, only in didChangeDependencies hook or in a template widget (via events hung up on buttons or so).
Alright, I don't mind that only didChangeDependencies hook works for me BUT when my logic in earlier mentioned hook depends on some class properties I am having problems with the accuracy of the class data.
I get data one step behind (since it's called before build hook I guess).
I cannot run this logic in the build hook because it includes a request to change the state in Provider. If I try to change the state there I've got either this error:
setState() or markNeedsBuild() called during build.
or this one
The setter 'lastPage=' was called on null.
Receiver: null
Tried calling: lastPage=true
What I want to do: I've got a wrapper widget which holds three other widgets: footer, header and pageViewer.
When I reach the last page I need to notify my wrapper widget about that so it reacts accordingly and hides header and footer.
I would appreciate any help here!
The focused code:
Here is the problem and must be solution
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:ui_flutter/screens/welcome/welcome_bloc.dart';
import 'package:flutter/scheduler.dart';
class _FooterState extends State<Footer> {
#override
void initState() {
super.initState();
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
final WelcomeBloc _welcome = Provider.of<WelcomeBloc>(context);
_welcomeBloc = _welcome;
// this._detectLastPage();
}
#override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.bottomCenter,
padding: EdgeInsets.symmetric(vertical: 30.0, horizontal: 30.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
this.stepper,
this.nextArrow,
],
),
);
}
_detectLastPage() {
// Here I've got inaccurate data
print(this.widget.currentStep);
}
}
I have already tried some other hooks like Scheduler but maybe I did something wrong there.
SchedulerBinding.instance
.addPostFrameCallback((_) => this._detectLastPage());
It's called only once at the first build-up round and that's it.
I lack an Angular hook here AfterViewInit. It would be handy here.
or Mounted in VueJS
That's the rest of my code if you'd like to see the whole picture.
If you have any suggestions on the architecture, structure or something else you are welcome. It's highly appreciated since I'm new to Flutter.
main.dart
import 'package:flutter/material.dart';
import 'package:ui_flutter/routing.dart';
import 'package:provider/provider.dart';
import 'screens/welcome/welcome_bloc.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => WelcomeBloc()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
initialRoute: '/welcome',
onGenerateRoute: RouteGenerator.generateRoute,
),
);
}
}
welcome.dart (my wrapper)
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:provider/provider.dart';
import 'package:ui_flutter/screens/welcome/welcome_bloc.dart';
import './footer.dart';
import './viewWrapper.dart';
import './header.dart';
// import 'package:ui_flutter/routing.dart';
class Welcome extends StatefulWidget {
#override
_WelcomeState createState() => _WelcomeState();
}
class _WelcomeState extends State<Welcome> {
WelcomeBloc _welcomeBloc;
#override
Widget build(BuildContext context) {
final WelcomeBloc _welcome = Provider.of<WelcomeBloc>(context);
this._welcomeBloc = _welcome;
print('Welcome: _welcome.currentPage - ${this._welcomeBloc.lastPage}');
return Scaffold(
body: SafeArea(
child: Stack(
children: <Widget>[
ViewerWrapper(),
Footer(
currentStep: _welcomeBloc.currentPage,
totalSteps: 3,
activeColor: Colors.grey[800],
inactiveColor: Colors.grey[100],
),
WelcomeHeader,
],
),
),
);
}
}
welcomeBloc.dart (my state via Provider)
import 'package:flutter/material.dart';
class WelcomeBloc extends ChangeNotifier {
PageController _controller = PageController();
int _currentPage;
bool _lastPage = false;
bool get lastPage => _lastPage;
set lastPage(bool value) {
_lastPage = value;
notifyListeners();
}
int get currentPage => _currentPage;
set currentPage(int value) {
_currentPage = value;
notifyListeners();
}
get controller => _controller;
nextPage(Duration duration, Curves curve) {
controller.nextPage(duration: duration, curve: curve);
}
}
footer.dart (that's where I've problems with data at the very bottom of the code - _detectLastPage method)
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:ui_flutter/screens/welcome/welcome_bloc.dart';
import 'package:flutter/scheduler.dart';
class Footer extends StatefulWidget {
final int currentStep;
final int totalSteps;
final Color activeColor;
final Color inactiveColor;
final Duration duration;
final Function onFinal;
final Function onStart;
Footer({
this.activeColor,
this.inactiveColor,
this.currentStep,
this.totalSteps,
this.duration,
this.onFinal,
this.onStart,
}) {}
#override
_FooterState createState() => _FooterState();
}
class _FooterState extends State<Footer> {
final double radius = 10.0;
final double distance = 4.0;
Container stepper;
Container nextArrow;
bool lastPage;
WelcomeBloc _welcomeBloc;
#override
void didChangeDependencies() {
super.didChangeDependencies();
final WelcomeBloc _welcome = Provider.of<WelcomeBloc>(context);
_welcomeBloc = _welcome;
this._detectLastPage();
}
#override
Widget build(BuildContext context) {
this._makeStepper();
this._makeNextArrow();
return Container(
alignment: Alignment.bottomCenter,
padding: EdgeInsets.symmetric(vertical: 30.0, horizontal: 30.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
this.stepper,
this.nextArrow,
],
),
);
}
_makeCirle(activeColor, inactiveColor, position, currentStep) {
currentStep = currentStep == null ? 0 : currentStep - 1;
Color color = (position == currentStep) ? activeColor : inactiveColor;
return Container(
height: this.radius,
width: this.radius,
margin: EdgeInsets.only(left: this.distance, right: this.distance),
decoration: BoxDecoration(
color: color,
border: Border.all(color: activeColor, width: 2.0),
borderRadius: BorderRadius.circular(50.0)),
);
}
_makeStepper() {
List<Container> circles = List();
for (var i = 0; i < widget.totalSteps; i++) {
circles.add(
_makeCirle(this.widget.activeColor, this.widget.inactiveColor, i,
this.widget.currentStep),
);
}
this.stepper = Container(
child: Row(
children: circles,
),
);
}
_makeNextArrow() {
this.nextArrow = Container(
child: Padding(
padding: const EdgeInsets.only(right: 8.0),
child: GestureDetector(
onTap: () {
_welcomeBloc.controller.nextPage(
duration: this.widget.duration ?? Duration(milliseconds: 500),
curve: Curves.easeInOut,
);
},
child: Icon(
Icons.arrow_forward,
)),
),
);
}
_onLastPage() {
if (this.widget.onFinal != null) {
this.widget.onFinal();
}
}
_onFirstPage() {
if (this.widget.onStart != null) {
this.widget.onStart();
}
}
_detectLastPage() {
// Here I've got inaccurate data
int currentPage =
this.widget.currentStep == null ? 1 : this.widget.currentStep;
if (currentPage == 1 && this.widget.currentStep == null) {
this._onFirstPage();
} else if (currentPage == this.widget.totalSteps) {
print('lastPage detected');
setState(() {
this.lastPage = true;
});
_welcomeBloc.lastPage = true;
this._onLastPage();
} else {
setState(() {
this.lastPage = false;
});
_welcomeBloc.lastPage = false;
}
}
}
Thanks in advance!
I am new to flutter as well, But I have learned about a few architecture patterns that have helped me build some apps.
Here is how I do it:
Create a Provider which holds the data for you in runtime. (It can be a Bloc in your case). Stick to one architecture, don't try to put providers and blocs in the same project. Both are used for state management and only using one would be a great practice.
Second, Register the providers using ChangeNotificationProvider or any other widgets which does a similar job of rebuilding the child widget when a data gets changed.
Third, Get the provider in the build method of the widget that is supposed to change when the value of the variable provider changes. This way only the concerned widget is redrawn.
For your case,
If you want to hide the header and footer once you reach the last page, you can declare a variable, let's say isLastPage set to false by default in your provider.
Next, wrap the widget, i.e. header and footer with ChangeNotificationListner
Now, let that widget decide what it has to do based on the value of isLastPage, either hide itself or show.
I hope this helps!
At the long run, I seem to have found Mounted lifecycle hook in Flutter which is implemented with the help of Future.microtask. Unlike .addPostFrameCallback:
SchedulerBinding.instance
.addPostFrameCallback((_) => this._detectLastPage());
Which is triggered only once like InitState (but only at the end of the build execution), Future.microtask can be placed inside build block and be invoked after every change and state update.
It doesn't solve the problem with the inaccurate state in didChangeDependencies hook but provides another way to perform post-build executions.
Credits for the current solution to #Abion47
example
Future.microtask(() => this._detectLastPage());
I'm Building An Flutter Application which requires image changes after a period of time. I thought using while loop with a sleep method inside may solve the problem. But It didn't, Image is only getting change after the loop ends. Application UI also gets froze.
Desired Output: Image should be changed after every 10 seconds.
Image and Button text is not Updating When Loop is running, please help me to get the desired output.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Test(
),
),
)
);
}}
class Test extends StatefulWidget {
#override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
int imgnumber=1;
int varToCheckButtonPress = 0;
String BtnTxt = "START";
void inc(){
while(imgnumber<10)
{
print(imgnumber);
setState(() {
sleep(Duration(seconds:5));
imgnumber++;
});
}
}
#override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(flex: 1,
child: Container(
child: Image.asset('images/'+imgnumber.toString()+'.png'),
height: 500,
width:500,
color: Colors.green,
),
),
FlatButton(
child: Text(BtnTxt),
onPressed: (){
if (varToCheckButtonPress == 0) {
setState(() {
BtnTxt = 'PAUSE';
varToCheckButtonPress = 1;
});
} else if (varToCheckButtonPress == 1) {
setState(() {
BtnTxt = 'RESUME';
varToCheckButtonPress = 0;
});
}
inc();
},
)
],
);
}
}
you shouldn't use sleep in the setState try replacing the inc function with this:
void inc() async {
while(imgnumber<10)
{
print(imgnumber);
await Future.delayed(const Duration(seconds: 10));
setState(() {
imgnumber++;
});
}
}
Anyone Help to trace the position of audio (that is)
if(durationtoOne(position==5)){
FlutterToast.Showtoast(msg:"I am At 5 sec");
}
I am Stuck on where to add this code if added in initstate got error,
I want to listen the position throught the audio plats
Code Starts Here
import 'dart:async';
import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class SmartMantra extends StatefulWidget {
#override
_SmartMantraState createState() => _SmartMantraState();
}
class _SmartMantraState extends State<SmartMantra> {
StreamSubscription _positionSubscription;
Duration position;
AssetsAudioPlayer _assetsAudioPlayer;
stream() {
_positionSubscription = _assetsAudioPlayer.currentPosition
.listen((p) => setState(() => position = p),);
}
#override
void initState() {
_assetsAudioPlayer.open("assets/shivamantra.mp3");
stream();
_assetsAudioPlayer.finished.listen((finished) {
print(finished);
// print(count);
});
super.initState();
}
#override
void dispose() {
_positionSubscription.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
SizedBox(
height: 70,
),
Center(
child: Text(
durationToone(position).toString(),
style: TextStyle(color: Colors.black, fontSize: 12),
),
),
//getTextContainer()
],
));
}
int durationToone(Duration duration) {
int twoDigits(int n) {
if (n >= 10) return n;
return n;
}
int twoDigitSeconds =
twoDigits(duration.inSeconds.remainder(Duration.secondsPerMinute));
return twoDigitSeconds;
}
}
Code Ends Here
Summary:At the specific Position needs to Trigger some Function While the Position Changes(I.e)
if(durationtoOne(position==5)){
FlutterToast.Showtoast(msg:"I am At 5 sec");
}
throught the audio plays or app is in foreground
If a stream is not a broadcast stream, you can listen to it only once.
Refer to this Medium post to know more about Streams.
You need to add your code in the stream function when listening to _assetsAudioPlayer.currentPosition.
import 'dart:async';
import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class SmartMantra extends StatefulWidget {
#override
_SmartMantraState createState() => _SmartMantraState();
}
class _SmartMantraState extends State<SmartMantra> {
StreamSubscription _positionSubscription;
Duration position;
AssetsAudioPlayer _assetsAudioPlayer;
stream() {
_positionSubscription = _assetsAudioPlayer.currentPosition
.listen((p) {
setState(() => position = p));
// You should add your code here
if(durationtoOne(position==5)){
FlutterToast.Showtoast(msg:"I am At 5 sec");
}
}
}
#override
void initState() {
_assetsAudioPlayer.open("assets/shivamantra.mp3");
stream();
_assetsAudioPlayer.finished.listen((finished) {
print(finished);
// print(count);
});
super.initState();
}
#override
void dispose() {
_positionSubscription.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
SizedBox(
height: 70,
),
Center(
child: Text(
durationToone(position).toString(),
style: TextStyle(color: Colors.black, fontSize: 12),
),
),
//getTextContainer()
],
));
}
int durationToone(Duration duration) {
int twoDigits(int n) {
if (n >= 10) return n;
return n;
}
int twoDigitSeconds =
twoDigits(duration.inSeconds.remainder(Duration.secondsPerMinute));
return twoDigitSeconds;
}
}