💻
[Flutter] 1画面に2つ以上のFloatingActionButtonを表示する
やりたいこと
Flutterでこんな感じの FloatingActionButotn
が複数ある画面を作ります。
やり方
Scaffold
のコンストラクタの floatingActionButton
に Row
などを渡せばOKです。
引数名だけ見ると FloatingActionButton
のインスタンスしか渡せないように思われますが、実は Widget型ならなんでも渡せます。
上記の画面キャプチャのような例なら、以下のようなコードで実装できます✋
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('タイトル'),
),
body: _buildList(),
floatingActionButton: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
margin: EdgeInsets.only(right: 12),
child: FloatingActionButton(
heroTag: 'clear', // (*)
onPressed: () => _clear(),
child: Icon(Icons.delete),
backgroundColor: Colors.red[500],
),
),
FloatingActionButton(
heroTag: 'check', // (*)
onPressed: () => _check(),
child: Icon(Icons.check),
),
],
),
);
}
コード中に // (*)
とコメントした箇所がポイントで、1画面に複数の FloatingActoinButton
を設置する場合はそれぞれに heroTag
を明示的に指定する必要があります。
これがないと、画面を表示しようとした途端に以下のようなエラーになります。
════════ Exception caught by scheduler library ═════════════════════════════════
The following assertion was thrown during a scheduler callback:
There are multiple heroes that share the same tag within a subtree.
Within each subtree for which heroes are to be animated (i.e. a PageRoute subtree), each Hero must have a unique non-null tag.
In this case, multiple heroes had the following tag: <default FloatingActionButton tag>
Here is the subtree for one of the offending heroes: Hero
tag: <default FloatingActionButton tag>
state: _HeroState#1142d
When the exception was thrown, this was the stack
#0 Hero._allHeroesFor.inviteHero.<anonymous closure>
package:flutter/…/widgets/heroes.dart:266
#1 Hero._allHeroesFor.inviteHero
package:flutter/…/widgets/heroes.dart:277
#2 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:296
#3 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:5821
#4 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:309
...
════════════════════════════════════════════════════════════════════════════════
Discussion