gpt4 book ai didi

flutter - 如何使用 GlobalKey 保持小部件的状态

转载 作者:行者123 更新时间:2023-12-04 14:51:59 26 4
gpt4 key购买 nike

我想使用 GlobalKey 保持子部件状态父状态改变后。有一种解决方法是使用 Opacity为了解决问题,不知道为什么GlobalKey在这种情况下不能按预期工作。

import 'dart:async';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Retrieve Text Input',
home: MainScreen(),
);
}
}

class MainScreen extends StatefulWidget {
@override
_MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
final _key = GlobalKey();
bool _showTimer = true;

@override
void initState() {
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Title'),
centerTitle: false,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextButton(
onPressed: () => setState(() {
_showTimer = !_showTimer;
}),
child: Text('show/hide')),
_showTimer ? TimerWidget(key: _key) : Container()
],
),
));
}
}

class TimerWidget extends StatefulWidget {
const TimerWidget({Key key}) : super(key: key);

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

const int TIME_REMINDING_SECONDS = 480;

class _TimerWidgetState extends State<TimerWidget> {
Timer _timer;
int _start = TIME_REMINDING_SECONDS;

@override
Widget build(BuildContext context) {
return Text(
'${(_start ~/ 60).toString().padLeft(2, '0')}:${(_start % 60).toString().padLeft(2, '0')}',
style: TextStyle(
color: _start > 10 ? Colors.amber : Colors.red, fontSize: 20));
}

@override
initState() {
super.initState();
_startTimer();
}

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

_startTimer() {
const oneSec = const Duration(seconds: 1);
_timer = new Timer.periodic(
oneSec,
(Timer timer) => setState(
() {
if (_start < 1) {
timer.cancel();
} else {
_start = _start - 1;
}
},
),
);
}
}
每次父状态更改时,您都会看到计时器重新启动到初始值。我尝试了解决方案 here但没有用。

最佳答案

作为选项,您可以跳过 GlobalKey且使用简单 Offstage小部件

Offstage(offstage: !_showTimer, child: TimerWidget()),
提到的另一个答案 VisibilitymaintainState范围。
这是毫无意义的,因为它使用 Offstage在引擎盖下。

关于flutter - 如何使用 GlobalKey 保持小部件的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68920196/

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