📱
flutter:ボタンにローディングマークを表示させる.
はじめに
- ボタンを押したら,下記のようなローディングのアニメーションを表示させる方法について説明します.
CircularProgressIndicator
を使う.
方法:-
OutlinedButton
を例として,下記のような実装する. - ※ボタンを子widgetに持つ
StatefulWidget
のState
インスタンスに,buttonPressed
のようなbool値を持たせる.そうすれば,ボタンが押されるとすぐにローディングアニメーションが表示されるようになる.
OutlinedButton(
style: DialogButton.style,
onPressed: () async {
setState(() {
buttonPressed = true;
});
・・・・(省略)
},
child: buttonPressed
? const CircularProgressIndicator(
strokeWidth: 2.0, color: CommonColors.textColor)
: const Text('ユーザ名を変更する',
style: CommonTextStyle.dialogButtonTextStyle));
- コード全体(Firebaseに登録したユーザ名を変更するダイアログを実装しています.)
// ダイアログボタン部分
class UpdatingUserNameDialogButton extends StatefulWidget {
final String newUserName;
final UserController userController;
const UpdatingUserNameDialogButton(
{super.key, required this.newUserName, required this.userController});
UpdatingUserNameDialogButtonState createState() =>
UpdatingUserNameDialogButtonState();
}
class UpdatingUserNameDialogButtonState
extends State<UpdatingUserNameDialogButton> {
bool buttonPressed = false;
Widget build(BuildContext context) {
return OutlinedButton(
style: DialogButton.style,
onPressed: () async {
setState(() {
buttonPressed = true;
});
// ユーザ名変更の操作を行う.
bool result = await widget.userController
.updateUserName(userName: widget.newUserName);
if (!context.mounted) {
return;
}
// ユーザ名変更捜査の結果を表示する.
Navigator.pop(context);
SettingDialogController().showUpdatingUserNameResultDialog(
context: context, result: result);
},
child: buttonPressed
? const CircularProgressIndicator(
strokeWidth: 2.0, color: CommonColors.textColor)
: const Text('ユーザ名を変更する',
style: CommonTextStyle.dialogButtonTextStyle));
}
}
参考資料
(公式ドキュメント)
Discussion