我正在try 使用Provider
和Stateless
小部件页面来更新倒计时UI.
当我运行以下所有操作时,我会在秒表每1秒的滴答声中在控制台中收到两条打印消息:
例如
flutter: build()
flutter: _buildCountDown()
此外,remaining
值实际上不会在UI中更新.
But if I:
- 将页面设为
StatefulWidget
- replace the variable access with
Consumer<CountdownProvider>
syntax 例如
return Consumer<CountdownProvider>(
builder: (_, countdownProvider, __) {
return Text(countdownProvider.remaining.toString()),
});
...一切都按预期进行:UI正确更新,我没有得到build()
的打印输出,只有_buildCountDown()
,这正是我想要的.
Q) What am I doing wrong that means I can't make this a Stateless widget that updates as expected?
- 主要的dart我有这样的提供者:
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => CountdownProvider(),
),
],
)
- 我编写了一个简单的倒计时提供者-
CountdownProvider
:
class CountdownProvider extends ChangeNotifier {
int remaining = 0;
final Stopwatch _stopwatch = Stopwatch();
late Timer _timer;
void start(int val) {
remaining = val;
_timer = Timer.periodic(const Duration(seconds: 1), _onTick);
_stopwatch.start();
}
void _onTick(Timer timer) {
remaining--;
if (remaining < 0) {
return;
}
notifyListeners();
}
void stop(bool skipNotify) {
_timer.cancel();
_stopwatch.stop();
if (skipNotify) {
_stopwatch.reset();
remaining = 0;
return;
}
notifyListeners();
}
}
- 显示页面:
PageCountdown
:
class PageCountdown extends StatelessWidget {
const PageCountdown({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
// 10 seconds default countdown
Provider.of<CountdownProvider>(context, listen: false).start(10);
print("build()");
return Scaffold(
body: _buildContent(context),
);
}
Widget _buildContent(BuildContext context) {
return SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
_buildCountDown(context),
],
),
);
}
Widget _buildCountDown(BuildContext context) {
int remaining = Provider.of<CountdownProvider>(context).remaining;
print("_buildCountDown()");
return Text(
remaining.toString(),
);
}
}