如何使用go_router路由在Flutter中显示对话框?

afdcj2ne  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(172)

我目前正在使用showGeneralDialog来显示一个对话框弹出,如下所示:

这一切都很好,但它发生在根Navigator级别,我宁愿将我所有的视图作为Go Router路由,这样我就可以在整个应用中以同样的方式控制它们的呈现。
如何在调用路由时使用showGeneralDialog之类的内容?

GoRoute(
  path: '/settings',
  pageBuilder: (context, state) {
    return ???;
  },
),
gzszwxb4

gzszwxb41#

有同样的问题,发现https://croxx5f.hashnode.dev/adding-modal-routes-to-your-gorouter,它对我来说足够好。通过将其 Package 在Dialog中来扩展其构建器。
这就是我最后的样子:

// dialogpage.dart
import 'package:flutter/material.dart';

class DialogPage<T> extends Page<T> {
  final Offset? anchorPoint;
  final Color? barrierColor;
  final bool barrierDismissible;
  final String? barrierLabel;
  final bool useSafeArea;
  final CapturedThemes? themes;
  final WidgetBuilder builder;

  const DialogPage({
    required this.builder,
    this.anchorPoint,
    this.barrierColor = Colors.black87,
    this.barrierDismissible = true,
    this.barrierLabel,
    this.useSafeArea = true,
    this.themes,
    super.key,
    super.name,
    super.arguments,
    super.restorationId,
  });

  @override
  Route<T> createRoute(BuildContext context) => DialogRoute<T>(
        context: context,
        settings: this,
        builder: (context) => Dialog(
          child: builder(context),
        ),
        anchorPoint: anchorPoint,
        barrierColor: barrierColor,
        barrierDismissible: barrierDismissible,
        barrierLabel: barrierLabel,
        useSafeArea: useSafeArea,
        themes: themes,
      );
}

然后这样使用:

GoRoute(
    name: 'bug-report',
    path: '/bug_report',
    pageBuilder: (context, state) => DialogPage(
      builder: (_) => BugReportPage(imagePath: state.queryParams['screenshot']),
    ),
  ),

相关问题