How to handle Spamming Button Click in a Flutter app? - Stack Overflow

PHOTO EMBED

Mon Jun 27 2022 08:33:18 GMT+0000 (Coordinated Universal Time)

Saved by @X17 #dart

import 'package:async/async.dart';
import 'package:flutter/material.dart';

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  RestartableTimer timer;
  bool liked = false;

  onPressed() {
    // switch state instantly so the user doesn't have to wait,
    // (even tho the action is still not executed on the backend/database side)
    setState(() {
      liked = !liked;
    });

    if (timer?.isActive ?? false) {
      timer.reset();
    } else {
      timer = RestartableTimer(Duration(milliseconds: 3000), likeAction);
    }
  }

  likeAction() {
    // execute the action on your database and finally setState accordingly
    print('currentState: $liked' );
    // ..
    // ..
    // ..
    // setState({liked = ..});
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.white,
      child: Center(
        child: IconButton(
          icon: Icon(
            liked ? Icons.favorite : Icons.favorite_border,
            size: 36,
          ),
          color: Colors.redAccent,
          onPressed: onPressed,
        ),
      ),
    );
  }
}
content_copyCOPY

https://stackoverflow.com/questions/60697579/how-to-handle-spamming-button-click-in-a-flutter-app