How to integrate data retrieved from an API via Timer.periodic into Flutter Cubit project

820

you can use Timer inside cubit for updating the UI with the latest values small example to update the UI with timer

    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);
    }
Share:
820
MBU
Author by

MBU

Updated on November 28, 2022

Comments

  • MBU
    MBU over 1 year

    I am working on a Flutter Bloc/Cubit based application in which I will need to have a Timer.periodic running that will retrieve data from an API at a certain repeating duration and then update the UI if new data is retrieved.

    I'm confused as to the workflow of where the Timer.periodic should be running and how to integrate with a Cubit such that the UI gets updated when State changes based on data being retrieved within the Timer.periodic's callback that gets called each time the periodic fires. Right now, that callback is running fine when the Timer.periodic is started manually. But, of course, it will need to somehow be integrated into the Cubit flow and this is what I don't really understand how to do.

    Does anyone have any pointers or experience with such a project?

    • pedro pimont
      pedro pimont over 2 years
      do you have some code already? if so, please paste what you've got so far
  • MBU
    MBU over 2 years
    Thank you. Your answer and code showed me exactly what I needed. Was trying to put the Timer.periodic outside of a cubit. Putting it inside the Cubit was the key.