Home > Net >  Flutter Simultaneously Update Multiple Cards Periodically
Flutter Simultaneously Update Multiple Cards Periodically

Time:08-28

I have a ListView containing multiple cards, each with a "remaining time" on it. The time is calculated based on "aSetFutureTime - currentTime". The future times are stored in Google FireStore. I have the "remaining times" displaying just fine upon each page refresh. I would also like to make them tick every 1 second. I am uncertain how. If possible, I would prefer to not create multiple timers, one per card, as there would wind up being a lot. Is it possible to have one timer update each card's remaining duration based on the live data from FireStore, without disrupting the live update feature?

import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

void main() async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App Title',
      home: Scaffold(
        appBar: AppBar(title: const Text('Personnel')),
        body: const Center(child: Personnel()),
      ),
    );
  }
}

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

  @override
  State<Personnel> createState() => _PersonnelState();
}

class _PersonnelState extends State<Personnel> {
  final Stream<QuerySnapshot> _personnelStream = FirebaseFirestore.instance
      .collection('personnel')
      .snapshots(); // need where before snapshots

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _personnelStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return const Text('Data stream error');
        }
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Text('Loading');
        }

        return ListView(
          children: snapshot.data!.docs
              .map((DocumentSnapshot document) {
                Map<String, dynamic> data =
                    document.data()! as Map<String, dynamic>;
                return getPersonnelCard(data, context);
              })
              .toList()
              .cast(),
        );
      },
    );
  }
}

Card getPersonnelCard(dynamic data, BuildContext context) {
  return Card(
      elevation: 3.5,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Text(data['name'],
                  style: DefaultTextStyle.of(context)
                      .style
                      .apply(fontSizeFactor: 2.0, fontWeightDelta: 2)),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Text(getTimeUntil(data['expiration'].toDate()),
                  style: DefaultTextStyle.of(context)
                      .style
                      .apply(fontSizeFactor: 1.5)),
            ],
          )
        ],
      ));
}

format(Duration d) => d.toString().split('.').first.padLeft(8, '0');

String getTimeUntil(DateTime expires) {
  final now = DateTime.now();
  final difference = expires.difference(now);
  if (!difference.isNegative) {
    return format(difference);
  } else {
    return 'Expired';
  }
}

CodePudding user response:

You can use Timer.periodic and resign the stream with setState. and dispose the timer on end.

Timer? timer;
@override
void initState() {
  super.initState();
  timer = Timer.periodic(Duration(seconds: 1), (timer) {
    _personnelStream =
        FirebaseFirestore.instance.collection('personnel').snapshots();

    setState(() {});
  });
}
  • Related