0

Hey guys I have a (hopefully for you simple) problem. How can I start a function from another Widget? I have a statelessWidget from where I want to start a timer function, which is in a statefulWidget. How can I start the timer (which "is" in the statefulWidget) from the statelessWidget? I hope you understand my problem, if not tell me pls which parts from the code you need. Thanks in advance!

[...]

void main() => runApp(
      MaterialApp(
        home: Workout1(),
        routes: { "/home": (context) => Homescreen(),}
      ),
    );

class Workout1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Title"),
        ),
        body: BodyConstruction());
  } 
}

class BodyConstruction extends StatefulWidget {
  @override
  _BodyConstructionState createState() =>
      _BodyConstructionState(); //the belongs to a "StatefulWidget"
}

class _BodyConstructionState extends State<BodyConstruction> {
  int _time = 10;

[...]

  void countdown() {
    Timer.periodic(
      Duration(seconds: 1),
      (timer) {
        setState(() {
          _time--; //every second -1
        });



 @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: <Widget>[
          [...]




            RaisedButton(
              child: Text("Button"),
              onPressed: () {
                countdown(); //when tis button is pressed "countdown" is called
              }),
          Text(_time.toString()),
        ],
      ),
    );
  }
}

Here is some code. I hope I havent delet anythig important for you, but otherwise the code would be to long. I want that the timer starts when this screen opens and not when the button is pressed

simi
  • 323
  • 4
  • 12

1 Answers1

0

If in your stateful widget, you have a function like this:

void myFunction() {
    // Do something!
}

and where you have included the stateless widget, pass function reference to it's constructor.

MyStatelessWidget(myFunction)

In the Stateless Widget:

class MyStatelessWidget extends StatelessWidget {
    Function timerFunction;

    MyStatelessWidget(this.timerFunction);
}

Now you can simpy call that function whenever you want, for example like on a button click.

FlatButton(
    child: Text('Start'),
    onPressed: timerFunction,
)
gegobyte
  • 4,945
  • 10
  • 46
  • 76