WEBサイト制作・アプリ開発・システム開発・ブランディングデザイン制作に関するご相談はお気軽にご連絡ください。
構想段階からじっくりとヒアリングし、お客様の課題にあわせたアプローチ手法でお客様の“欲しかった”をカタチにしてご提案いたします。
Blog スタッフブログ
Flutter
システム開発
ひとくちコードスニペット
[Flutter]UIの連打対策をするコードスニペット
![]()
こんにちは、株式会社MIXシステム開発担当のBloomです。
今回はFlutterで利用できるコードスニペットを紹介します。まずはこちらのクラスを記述しましょう。
import 'package:flutter/material.dart';
import 'dart:async';
class Throttler {
Throttler(this.duration);
final Duration duration;
bool _locked = false;
Timer? _t;
void run(void Function() action) {
if (_locked) return;
_locked = true;
action();
_t?.cancel();
_t = Timer(duration, () => _locked = false);
}
void dispose() => _t?.cancel();
}ではこのクラスの利用例を下記に掲載します。サンプルプロジェクトのFloatingActionButtonを例に組み込んでみましょう。
class _MyHomePageState extends State<MyHomePage> {
final _throttler = Throttler(const Duration(seconds: 1));
// 中略
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body:
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
)
,
floatingActionButton: FloatingActionButton(
onPressed: () {_throttler.run(_incrementCounter);},
tooltip: 'Increment',
child: const Icon(Icons.add),
)
);
}
}
これだけで連打対策ができるようになりました。良かったですね。