Flutter对话框插件kdialogs的使用

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

Flutter对话框插件kdialogs的使用

实现了一些常用的对话框,用于显示加载指示器、确认消息、内容、错误信息等。本文档提供了项目的概述。

实现:

showKDialogWithLoadingMessage:

显示一个带有消息的加载指示器,并提供一个函数来停止指示器。

final close = await showKDialogWithLoadingMessage(context, message: "加载中,请稍候...");
await Future.delayed(const Duration(seconds: 2));
close();

showKDialogWithLoadingIndicator:

显示一个加载指示器,并提供一个函数来停止指示器。

final close = await showKDialogWithLoadingIndicator(context);
await Future.delayed(const Duration(seconds: 2));
close();

showBottomAlertKDialog:

显示一个底部模态对话框,可以显示错误消息,并提供重试选项,如果采取了重试操作,则返回布尔值 true

await showBottomAlertKDialog(context, message: "这是一个错误消息", retryable: true);

showKDialogContent:

允许在对话框中显示内容,并提供各种附加操作。

await showKDialogContent(
  context,
  closeOnOutsideTab: false,
  builder: (context) {
    return Column(
      children: [
        const Text("你好啊!!!"),
        Container(
          color: Colors.green,
          width: 100.0,
          height: 100.0,
        )
      ],
    );
  },
);

showConfirmationKDialog:

显示一个包含取消或接受选项的对话框,如果选择了接受选项,则返回 true

final response = await showConfirmationKDialog(context, title: "确认消息");

showAsyncProgressKDialog:

结合了各种对话框实现,允许请求确认、显示加载指示器、显示错误对话框并呈现重试选项。

// 简单用法
final resultvalue = await showAsyncProgressKDialog<String>(
  context,
  doProcess: () async {
    await Future.delayed(const Duration(seconds: 2)); // 处理过程
    return "value";
  },
  showSuccessSnackBar: true,
);

// 包含确认和重试功能
final resultvalue = await showAsyncProgressKDialog<String>(
  context,
  doProcess: () async {
    await Future.delayed(const Duration(seconds: 2));
    throw "这是一个错误,表示处理无法完成";
  },
  confirmationRequired: true,
  showSuccessSnackBar: true,
  loadingMessage: "处理中...",
  retryable: true,
);

示例:

示例

完整示例代码

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:kdialogs/kdialogs.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'KDialogs',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
        useMaterial3: true,
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          child: SizedBox(
            width: double.infinity,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FilledButton(
                  onPressed: () async {
                    final close = await showKDialogWithLoadingMessage(context);
                    await Future.delayed(const Duration(seconds: 2));
                    close();
                  },
                  child: const Text("带消息的加载"),
                ),
                FilledButton(
                  onPressed: () async {
                    final close = await showKDialogWithLoadingIndicator(context);
                    await Future.delayed(const Duration(seconds: 2));
                    close();
                  },
                  child: const Text("仅加载"),
                ),
                FilledButton(
                  onPressed: () async {
                    await showBottomAlertKDialog(context, message: "这是一个错误消息", retryable: true);
                  },
                  child: const Text("底部错误消息"),
                ),
                FilledButton(
                  onPressed: () async {
                    await showKDialogContent(
                      context,
                      closeOnOutsideTab: false,
                      builder: (context) {
                        return Column(
                          children: [
                            const Text("你好啊!!!"),
                            Container(
                              color: Colors.green,
                              width: 100.0,
                              height: 100.0,
                            )
                          ],
                        );
                      },
                    );
                  },
                  child: const Text("显示简单内容"),
                ),
                TextButton(
                  onPressed: () async {
                    final _ = await showConfirmationKDialog(context, message: "你确定吗?");
                  },
                  child: const Text("简单的确认对话框"),
                ),
                FilledButton(
                  onPressed: () async {
                    final _ = await showConfirmationKDialog(context, title: "确认消息");
                  },
                  child: const Text("显示确认对话框"),
                ),
                FilledButton(
                  onPressed: () async {
                    final _ = await showAsyncProgressKDialog<String>(
                      context,
                      doProcess: () async {
                        await Future.delayed(const Duration(seconds: 2));
                        return "value";
                      },
                      showSuccessSnackBar: true,
                    );
                  },
                  child: const Text("成功处理"),
                ),
                FilledButton(
                  onPressed: () async {
                    final _ = await showAsyncProgressKDialog<String>(
                      context,
                      doProcess: () async {
                        await Future.delayed(const Duration(seconds: 2));
                        throw "这是一个错误,表示处理无法完成";
                      },
                      showSuccessSnackBar: true,
                    );
                  },
                  child: const Text("带错误的处理"),
                ),
                FilledButton(
                  onPressed: () async {
                    final _ = await showAsyncProgressKDialog<String>(
                      context,
                      doProcess: () async {
                        await Future.delayed(const Duration(seconds: 2));
                        throw "这是一个错误,表示处理无法完成";
                      },
                      confirmationRequired: true,
                      showSuccessSnackBar: true,
                      loadingMessage: "处理中...",
                      retryable: true,
                    );
                  },
                  child: const Text("带错误和重试的处理"),
                ),
                FilledButton(
                  onPressed: () async {
                    final _ = await showBasicOptionsKDialog(
                      context,
                      allowMultipleSelection: true,
                      searchInput: true,
                      selectedStrings: {"选项 1", "选项 5"},
                      options: getOptions(),
                    );
                  },
                  child: const Text("显示带初始字符串的选项"),
                ),
                FilledButton(
                  onPressed: () async {
                    final result = await showBasicOptionsKDialog(
                      context,
                      allowMultipleSelection: true,
                      searchInput: true,
                      selectedItems: {Person(id: "2", name: "Jose")},
                      options: {
                        Person(id: "1", name: "Kevin"),
                        Person(id: "2", name: "Jose"),
                        Person(id: "3", name: "Martin"),
                      },
                    );
                    if (result == null) return;
                    for (var i in result) {
                      if (kDebugMode) print(i.name);
                    }
                  },
                  child: const Text("显示带初始选项的选项"),
                ),
                FilledButton(
                  onPressed: () async {
                    final _ = await showBasicOptionsKDialog(
                      context,
                      allowMultipleSelection: true,
                      searchInput: true,
                      title: '列表选项',
                      options: getOptions(),
                    );
                  },
                  child: const Text("显示选项"),
                ),
                FilledButton(
                  onPressed: () async {
                    final _ = await showAsyncOptionsDialog(
                      context,
                      allowMultipleSelection: true,
                      searchInput: true,
                      getOptions: () async {
                        final options = getOptions();
                        await Future.delayed(const Duration(seconds: 1));
                        return options;
                      },
                    );
                  },
                  child: const Text("显示异步选项"),
                ),
                FilledButton(
                  onPressed: () async {
                    final _ = await showConfirmationKDialogWithCallback(
                      context,
                      onConfirm: () {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text("好的!!!")),
                        );
                      },
                    );
                  },
                  child: const Text("确认时执行"),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Set<String> getOptions() => {
      "选项 1",
      "选项 2",
      "选项 3",
      "选项 4",
      "选项 5",
      "选项 6",
      "选项 7",
      "选项 8",
      "选项 9",
      "选项 10",
      "选项 11",
      "选项 12",
      "选项 13",
      "选项 14",
      "选项 15",
      "选项 16",
      "选项 17",
      "选项 18",
      "选项 19",
      "选项 20",
      "选项 21",
      "选项 22",
    };

class Person {
  final String? id;
  final String? name;

  Person({
    this.id,
    this.name,
  });

  [@override](/user/override)
  bool operator ==(Object other) {
    return other is Person &&
        other.runtimeType == runtimeType &&
        other.id == id;
  }

  [@override](/user/override)
  int get hashCode => id.hashCode;

  [@override](/user/override)
  String toString() => name ?? "";
}

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

1 回复

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


当然,以下是一个关于如何在Flutter中使用kdialogs插件的示例代码。请注意,kdialogs插件实际上并不是Flutter的官方插件,而且在我最新的知识库中,没有直接找到名为kdialogs的Flutter插件。不过,我会基于常见的对话框操作(比如showDialog)来提供一个示例,你可以根据这个示例来理解和实现类似的对话框功能。

通常,Flutter中创建对话框会使用showDialog函数和AlertDialog组件。下面是一个简单的示例,展示了如何在Flutter中创建一个对话框:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Dialog Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void _showDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('提示'),
          content: Text('这是一个Flutter对话框示例'),
          actions: <Widget>[
            FlatButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            FlatButton(
              child: Text('确定'),
              onPressed: () {
                // 在这里添加点击确定后的逻辑
                Navigator.of(context).pop();
                // 例如,可以更新状态或执行其他操作
                // setState(() {
                //   // 更新状态
                // });
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Dialog Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _showDialog,
          child: Text('显示对话框'),
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个按钮。当点击按钮时,会调用_showDialog函数,该函数使用showDialog来显示一个AlertDialog。这个对话框包含一个标题、一些内容以及两个按钮:一个用于取消,另一个用于确定。

如果你确实在寻找一个名为kdialogs的特定插件,并且它在某个特定的Flutter包管理器(如pub.dev)中可用,你可能需要查看该插件的官方文档或示例代码来获取更具体的用法。不过,大多数情况下,Flutter内置的对话框功能已经足够强大,可以满足大多数需求。

回到顶部