您可以在 cubit 内使用 Timer 以使用最新值更新 UI 小示例以使用计时器更新 UI
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
void main() async {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(),
darkTheme: ThemeData.dark(),
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: BlocBuilder<UpdatetimerCubit, UpdatetimerState>(
bloc: UpdatetimerCubit(),
builder: (context, state) {
if (state is UpdatetimerUIState) {
return Column(
children: [
TextButton(
onPressed: () {},
child: Text('Reset'),
),
Text('${state.currentTime}'),
],
);
}
return Text('${DateTime.now().millisecondsSinceEpoch}');
},
),
);
}
}
class UpdatetimerCubit extends Cubit<UpdatetimerState> {
Timer? timer;
UpdatetimerCubit() : super(UpdatetimerInitial()) {
timer = Timer.periodic(const Duration(seconds: 5), (timer) {
print('Timer');
emit(UpdatetimerUIState(DateTime.now().millisecondsSinceEpoch));
});
}
void closeTimer() {
timer?.cancel();
}
}
@immutable
abstract class UpdatetimerState {}
class UpdatetimerInitial extends UpdatetimerState {}
class UpdatetimerUIState extends UpdatetimerState {
final int currentTime;
UpdatetimerUIState(this.currentTime);
}