0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

FlutterのshowDialogのAlertDialogサンプル

Posted at
  • Android、iOS用でそれぞれ環境に合うDialogを出力する
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class CommonDialogView {
  static Future<T?> show<T extends Object>(BuildContext context, String text) {
    return Platform.isIOS
        ? _showCupertinoDialog<T>(context, text)
        : _showMaterialDialog<T>(context, text);
  }

  static Future<T?> _showCupertinoDialog<T extends Object>(
      BuildContext context, String text) {
    return showCupertinoDialog<T>(
      context: context,
      builder: (BuildContext context) {
        return CupertinoAlertDialog(
          content: _buildContent(text),
          actions: _buildCupertinoActions(context),
        );
      },
    );
  }

  static Future<T?> _showMaterialDialog<T extends Object>(
      BuildContext context, String text) {
    return showDialog<T>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          content: _buildContent(text),
          actions: _buildMaterialActions(context),
        );
      },
    );
  }

  static Widget _buildContent(String text) {
    return SingleChildScrollView(
      child: Center(
        child: Text(
          text,
          style: const TextStyle(fontSize: 16),
        ),
      ),
    );
  }

  static List<Widget> _buildMaterialActions(BuildContext context) {
    return <Widget>[
      TextButton(
        onPressed: () => Navigator.pop(context, 'Cancel'),
        child: const Text('キャンセル'),
      ),
      TextButton(
        onPressed: () => Navigator.of(context).pop(),
        child: const Text('OK'),
      ),
    ];
  }

  static List<Widget> _buildCupertinoActions(BuildContext context) {
    return <Widget>[
      CupertinoDialogAction(
        onPressed: () => Navigator.pop(context, 'Cancel'),
        child: const Text('キャンセル'),
      ),
      CupertinoDialogAction(
        onPressed: () => Navigator.of(context).pop(),
        child: const Text('OK'),
      ),
    ];
  }
}
    // 使用例
    CommonDialogView.show(context,"コンテンツのtext")
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?