我正在開發基于 Flutter Bloc/Cubit 的應用程式,在該應用程式中,我需要運行 Timer.periodic 以在特定的重復持續時間內從 API 檢索資料,然后在檢索到新資料時更新 UI。
我對 Timer.periodic 應該在哪里運行以及如何與 Cubit 集成的作業流程感到困惑,這樣 UI 在狀態更改時會根據 Timer.periodic 回呼中檢索的資料進行更新,該回呼每次呼叫周期性火災。現在,當手動啟動 Timer.periodic 時,該回呼運行良好。但是,當然,它需要以某種方式集成到 Cubit 流程中,而這正是我不真正了解如何做的。
有沒有人對這樣的專案有任何指示或經驗?
uj5u.com熱心網友回復:
您可以使用 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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340066.html
上一篇:嘗試使用image_picker實作相機功能,但不斷收到LateInitializationError[FLUTTER]
