gpt4 book ai didi

flutter - 在 Flutter 中更新 SnackBar 内容

转载 作者:行者123 更新时间:2023-12-02 00:10:44 25 4
gpt4 key购买 nike

在移动到下一页之前,我有一个显示 SnackBar(或 toast)的按钮。我有一个倒计时,5 秒后我推送 Page2。

RaisedButton(
onPressed: () {
_startTimer();
final snackBar = SnackBar(
behavior: SnackBarBehavior.floating,
content: Text(
'Prepare yourself to start in ${widget._current.toString()}!'), // doesn't work here
duration: new Duration(seconds: widget._start),
action: SnackBarAction(
label: widget._current.toString(), // and neither does here
onPressed: () {
// Some code to undo the change.
},
),
);
Scaffold.of(context).showSnackBar(snackBar);
},
child: Text(
"I'm ready",
style: TextStyle(fontSize: 20),
),
),

倒计时没有什么可看的,但我会粘贴它以防万一:

void _startTimer() {
CountdownTimer countDownTimer = new CountdownTimer(
new Duration(seconds: widget._start),
new Duration(seconds: 1),
);

var sub = countDownTimer.listen(null);
sub.onData((duration) {
setState(() {
widget._current = widget._start - duration.elapsed.inSeconds;
});
});

sub.onDone(() {
print("Done");
sub.cancel();
});
}

因此,如果我在其他地方(例如 Text 内)显示倒计时,它会起作用,但似乎 SnackBar 不会更改其包含,它总是会倒计时的最大数量。

最佳答案

您需要为 snackbar 的内容字段实现一个带有倒计时逻辑的自定义小部件,如下所示:

class TextWithCountdown extends StatefulWidget {
final String text;
final int countValue;
final VoidCallback? onCountDown;

const TextWithCountdown({
Key? key,
required this.text,
required this.countValue,
this.onCountDown,
}) : super(key: key);

@override
_TextWithCountdownState createState() => _TextWithCountdownState();
}

class _TextWithCountdownState extends State<TextWithCountdown> {
late int count = widget.countValue;
late Timer timer;
@override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 1), _timerHandle);
}

@override
void dispose() {
timer.cancel();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Container(
child: Text("[$count] " + widget.text),
);
}

void _timerHandle(Timer timer) {
setState(() {
count -= 1;
});
if (count <= 0) {
timer.cancel();
widget.onCountDown?.call();
}
}
}

关于flutter - 在 Flutter 中更新 SnackBar 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59213871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com