Flutter原生iOS对话框插件native_ios_dialog的使用

发布于 1周前 作者 itying888 来自 Flutter

Flutter原生iOS对话框插件native_ios_dialog的使用

Native iOS Dialog

native_ios_dialog 是一个Flutter插件,它使显示与iOS原生等效的 CupertinoAlertDialogCupertinoActionSheet 对话框变得简单。

Usage

要使用此插件,请将 native_ios_dialog 添加为依赖项到你的 pubspec.yaml 文件中。Flutter中的对话框功能非常强大,但是 CupertinoAlertDialogs 并不能完全提供与原生iOS对话框相同的感觉,因此创建了这个插件。通过该插件,你可以拥有iOS提供的所有自定义选项。

Types of dialogs

  • Alert
  • Action Sheet

Alert Action Sheet

Types of buttons

  • Default
  • Destructive
  • Cancel

每个按钮也可以被禁用。

Default Destructive Cancel

Sample Usage

Info dialog

NativeIosDialog(
  title: "Info",
  message: "Please consider the following information in this dialog.",
  style: style,
  actions: [
    NativeIosDialogAction(
      text: "OK",
      style: NativeIosDialogActionStyle.defaultStyle,
      onPressed: () {},
    ),
  ],
).show();

Confirm dialog

NativeIosDialog(
  title: "Confirm",
  message: "Please confirm the following information in this dialog.",
  style: style,
  actions: [
    NativeIosDialogAction(
      text: "OK",
      style: NativeIosDialogActionStyle.defaultStyle,
      onPressed: () {},
    ),
    NativeIosDialogAction(
      text: "Cancel",
      style: NativeIosDialogActionStyle.cancel,
      onPressed: () {},
    ),
  ],
).show();

完整示例代码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:native_ios_dialog/native_ios_dialog.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const CupertinoApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int currentDialogStyle = 0;

  @override
  Widget build(BuildContext context) {
    final NativeIosDialogStyle style = currentDialogStyle == 0
        ? NativeIosDialogStyle.alert
        : NativeIosDialogStyle.actionSheet;
    return CupertinoPageScaffold(
      navigationBar: const CupertinoNavigationBar(
        middle: Text("Native iOS Dialogs"),
      ),
      child: ListView(
        children: [
          const SizedBox(height: 12),
          const SimpleDivider(text: "Basic examples"),
          SimpleButton(
            text: "Info Dialog",
            onPressed: () {
              NativeIosDialog(
                  title: "Info",
                  message:
                      "Please consider the following information in this dialog.",
                  style: style,
                  actions: [
                    NativeIosDialogAction(
                        text: "OK",
                        style: NativeIosDialogActionStyle.defaultStyle,
                        onPressed: () {}),
                  ]).show();
            },
          ),
          SimpleButton(
            text: "Confirm Dialog",
            onPressed: () {
              NativeIosDialog(
                  title: "Confirm",
                  message:
                      "Please confirm the following information in this dialog.",
                  style: style,
                  actions: [
                    NativeIosDialogAction(
                        text: "OK",
                        style: NativeIosDialogActionStyle.defaultStyle,
                        onPressed: () {}),
                    NativeIosDialogAction(
                        text: "Cancel",
                        style: NativeIosDialogActionStyle.cancel,
                        onPressed: () {}),
                  ]).show();
            },
          ),
          SimpleButton(
            text: "Destructive Confirm Dialog",
            onPressed: () {
              NativeIosDialog(
                  title: "Confirm deletion",
                  message:
                      "Do you want to delete this resource? You cannot undo this action.",
                  style: style,
                  actions: [
                    NativeIosDialogAction(
                        text: "Delete",
                        style: NativeIosDialogActionStyle.destructive,
                        onPressed: () {}),
                    NativeIosDialogAction(
                        text: "Cancel",
                        style: NativeIosDialogActionStyle.cancel,
                        onPressed: () {}),
                  ]).show();
            },
          ),
          SimpleButton(
            text: "Three Buttons",
            onPressed: () {
              NativeIosDialog(
                  title: "Are you sure?",
                  message:
                      "Do you want to apply the changes you made, or do you want to delete this resource?",
                  style: style,
                  actions: [
                    NativeIosDialogAction(
                        text: "Apply",
                        style: NativeIosDialogActionStyle.defaultStyle,
                        onPressed: () {}),
                    NativeIosDialogAction(
                        text: "Delete",
                        style: NativeIosDialogActionStyle.destructive,
                        onPressed: () {}),
                    NativeIosDialogAction(
                        text: "Cancel",
                        style: NativeIosDialogActionStyle.cancel,
                        onPressed: () {}),
                  ]).show();
            },
          ),
          const SimpleDivider(text: "Examples with disabled actions"),
          SimpleButton(
            text: "Confirm Dialog",
            onPressed: () {
              NativeIosDialog(
                  title: "Confirm",
                  message:
                      "Please confirm the following information in this dialog.\n\nOh wait!\nSeems like there is something that prohibits you from confirming this dialog.",
                  style: style,
                  actions: [
                    NativeIosDialogAction(
                        text: "OK",
                        style: NativeIosDialogActionStyle.defaultStyle),
                    NativeIosDialogAction(
                        text: "Cancel",
                        style: NativeIosDialogActionStyle.cancel,
                        onPressed: () {}),
                  ]).show();
            },
          ),
          SimpleButton(
            text: "Destructive Confirm Dialog",
            onPressed: () {
              NativeIosDialog(
                  title: "Confirm deletion",
                  message:
                      "Do you want to delete this resource? You cannot undo this action.\n\nOh wait!\nSeems like there is something that prohibits you from confirming this dialog.",
                  style: style,
                  actions: [
                    NativeIosDialogAction(
                        text: "Delete",
                        style: NativeIosDialogActionStyle.destructive),
                    NativeIosDialogAction(
                        text: "Cancel",
                        style: NativeIosDialogActionStyle.cancel,
                        onPressed: () {}),
                  ]).show();
            },
          ),
          SimpleButton(
            text: "Three Buttons",
            onPressed: () {
              NativeIosDialog(
                  title: "Are you sure?",
                  message:
                      "Do you want to apply the changes you made, or do you want to delete this resource?",
                  style: style,
                  actions: [
                    NativeIosDialogAction(
                        text: "Apply",
                        style: NativeIosDialogActionStyle.defaultStyle),
                    NativeIosDialogAction(
                        text: "Delete",
                        style: NativeIosDialogActionStyle.destructive),
                    NativeIosDialogAction(
                        text: "Cancel",
                        style: NativeIosDialogActionStyle.cancel,
                        onPressed: () {}),
                  ]).show();
            },
          ),
          const SimpleDivider(text: "Other"),
          SimpleButton(
            text: "100 Buttons",
            onPressed: () {
              NativeIosDialog(
                  title: "Uhm...",
                  message:
                      "Please do not use this in production... please do not do this! This dialog is just a demonstration of how iOS handles many buttons.",
                  style: style,
                  actions: [
                    for (int i = 1; i <= 100; i++)
                      NativeIosDialogAction(
                          text: "Action $i",
                          style: NativeIosDialogActionStyle.defaultStyle,
                          onPressed: () {}),
                    NativeIosDialogAction(
                        text: "Cancel",
                        style: NativeIosDialogActionStyle.cancel,
                        onPressed: () {}),
                  ]).show();
            },
          ),
          const SimpleDivider(text: "Configuration"),
          Padding(
            padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 8.0),
            child: CupertinoSlidingSegmentedControl(
                groupValue: currentDialogStyle,
                children: const {0: Text("Alert"), 1: Text("ActionSheet")},
                onValueChanged: (int? newValue) {
                  if (newValue == null) return;
                  setState(() {
                    currentDialogStyle = newValue;
                  });
                }),
          )
        ],
      ),
    );
  }
}

class SimpleButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;

  const SimpleButton({Key? key, required this.text, required this.onPressed})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 16, right: 16, bottom: 8),
      child: CupertinoButton(
        child: Text(
          text,
          style: const TextStyle(color: Colors.white),
        ),
        color: Theme.of(context).primaryColor,
        onPressed: onPressed,
      ),
    );
  }
}

class SimpleDivider extends StatelessWidget {
  final String text;

  const SimpleDivider({Key? key, required this.text}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8.0, left: 16, right: 16),
      child: Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
        const Expanded(
            child: Divider(
          color: Colors.black,
        )),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(text),
        ),
        const Expanded(
            child: Divider(
          color: Colors.black,
        )),
      ]),
    );
  }
}

通过以上代码和说明,你应该能够轻松地在你的Flutter项目中使用 native_ios_dialog 插件来实现原生iOS风格的对话框。


更多关于Flutter原生iOS对话框插件native_ios_dialog的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter原生iOS对话框插件native_ios_dialog的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用native_ios_dialog插件来显示原生iOS对话框的一个代码案例。native_ios_dialog是一个允许Flutter应用调用iOS原生对话框的插件。

首先,你需要在你的pubspec.yaml文件中添加native_ios_dialog依赖:

dependencies:
  flutter:
    sdk: flutter
  native_ios_dialog: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

接下来,在你的Flutter项目中,你需要根据平台条件来调用原生iOS对话框。由于native_ios_dialog只支持iOS,因此你需要使用dart:io库中的Platform.isIOS来检查当前平台是否为iOS。

以下是一个完整的示例代码:

import 'package:flutter/material.dart';
import 'package:native_ios_dialog/native_ios_dialog.dart';
import 'dart:io' show Platform;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Native iOS Dialog Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: _showNativeDialog,
            child: Text('Show Native iOS Dialog'),
          ),
        ),
      ),
    );
  }

  void _showNativeDialog() {
    if (Platform.isIOS) {
      NativeIOSDialog.alert(
        title: 'Alert Title',
        message: 'This is an alert message.',
        actions: [
          DialogAction(
            title: 'Cancel',
            style: DialogActionStyle.cancel,
            handler: () {
              print('Cancel button tapped');
            },
          ),
          DialogAction(
            title: 'OK',
            style: DialogActionStyle.defaultStyle,
            handler: () {
              print('OK button tapped');
            },
          ),
        ],
      );
    } else {
      // 展示一个Flutter对话框作为替代方案(仅用于非iOS平台)
      showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('Alert'),
            content: Text('This is a Flutter alert dialog (non-iOS)'),
            actions: <Widget>[
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text('OK'),
              ),
            ],
          );
        },
      );
    }
  }
}

在这个示例中,当用户点击按钮时,如果当前平台是iOS,则会显示一个原生iOS对话框。对话框包含标题、消息和两个操作按钮:一个取消按钮和一个确定按钮。每个按钮点击时都会打印相应的信息到控制台。

如果当前平台不是iOS,则会显示一个标准的Flutter对话框作为替代方案。

请注意,native_ios_dialog插件依赖于原生iOS代码,因此在运行此代码之前,你需要确保已经正确设置了iOS开发环境,并且已经运行了pod install来安装iOS原生依赖。

希望这个示例代码对你有所帮助!

回到顶部