嘿伙计们,我有一个(希望对你来说很简单)问题。如何从另一个小部件启动功能?我有一个 statelessWidget,我想从那里启动一个计时器功能,它位于 statefulWidget 中。如何从 statelessWidget 启动计时器(statefulWidget 中的“是”)?我希望你能理解我的问题,如果没有,请告诉我你需要代码中的哪些部分。提前致谢!
[...]
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()),
],
),
);
}
}
这是一些代码。我希望我没有删除任何对你很重要的东西,否则代码会很长。我希望计时器在此屏幕打开时启动,而不是在按下按钮时启动