【发布时间】:2023-01-20 02:06:56
【问题描述】:
我在一个有状态的小部件中设置了一个倒数计时器。 (我跟随了一个 youtube 教程。我是 flutter 的新手)。我想在我的应用程序的其他页面上显示。 所以我在考虑使用 provider 包,因为我将它用于所有其他变量。唯一的问题是我不知道如何将所需的部件转移到提供程序包中,以便我可以从其他页面调用它们。 这是我的代码:
import 'dart:async';
import 'package:provider/provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'constants.dart';
class ChessClock extends StatefulWidget {
const ChessClock({Key? key}) : super(key: key);
@override
State<ChessClock> createState() => _ChessClockState();
}
class _ChessClockState extends State<ChessClock> {
static const countdownDuration = Duration(minutes: 10);
Duration duration = Duration();
Timer? timer;
bool isCountdown = true;
@override
void initState() {
super.initState();
Reset();
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
]);
}
void Reset() {
if (isCountdown) {
setState(() => duration = countdownDuration);
} else {
setState(
() => duration = Duration(),
);
}
}
void addTime() {
final addSeconds = isCountdown ? -1 : 1;
setState(() {
final seconds = duration.inSeconds + addSeconds;
if (seconds < 0) {
timer?.cancel();
} else {
duration = Duration(seconds: seconds);
}
});
}
void startTimer() {
timer = Timer.periodic(
Duration(seconds: 1),
(_) => addTime(),
);
}
void stopTimer() {
setState(
() => timer?.cancel(),
);
}
@override
void dispose() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
super.dispose();
}
bool isRunningLeft = false;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Row(
children: [
Expanded(
flex: 3,
child: Container(
padding: EdgeInsets.all(20),
child: InkWell(
onTap: () {
setState(() {
isRunningLeft = !isRunningLeft;
});
isRunningLeft ? startTimer() : stopTimer();
},
child: Container(
width: double.infinity,
height: double.infinity,
decoration: BoxDecoration(
color: isRunningLeft ? kOrange : kBlueGrey900,
borderRadius: BorderRadius.circular(30),
),
child: Center(
child: BuildTimeLeft(),
),
),
),
),
),
RowSpacers(
lineColor: kOrange,
leftSizedBox: 2,
rightSizedBox: 2,
containerWidth: 3),
Expanded(
flex: 2,
child: Container(),
),
RowSpacers(
lineColor: kOrange,
leftSizedBox: 2,
rightSizedBox: 2,
containerWidth: 3),
Expanded(
flex: 3,
child: Container(),
),
],
),
),
);
}
Widget BuildTimeLeft() {
String twoDigits(int n) => n.toString().padLeft(2, '0');
final hours = twoDigits(
duration.inHours.remainder(60),
);
final minutes = twoDigits(
duration.inMinutes.remainder(60),
);
final seconds = twoDigits(
duration.inSeconds.remainder(60),
);
return RotatedBox(
quarterTurns: 1,
child: Text(
'$hours:$minutes:$seconds',
style: TextStyle(fontSize: 50),
),
);
}
}
class StopWatchTimers with ChangeNotifier {}
因为时间不是整数之类的基本变量,所以我不确定该怎么做。
非常感谢
【问题讨论】:
标签: flutter dart flutter-provider