404无法加载资源正在将Flutter Web App部署到Firebase Hosting

pgvzfuti  于 2023-04-13  发布在  Flutter
关注(0)|答案(3)|浏览(145)

我正在尝试将我的Flutter应用程序部署到Firebase Hosting。应用程序在flutter run -d chrome下运行良好,并使用flutter build web --web-renderer html --release成功构建
在我的Flutter网页应用程序,我有一个以上的网页。我使用
velocity_x:^3.3.0
因为这个插件使用flutter 2.0导航。
当我打开我的网页主页时,我遇到的问题是正常工作,当我点击下一页打开另一个页面时,但当我刷新第二个页面时,显示404未找到,我不明白我做错了什么。同样的事情在调试模式下工作正常,但在部署我的flutter web后,404问题来了。请帮助我,我尝试了很多,但确实明白我应该怎么做。
我的主.dart文件

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  Vx.setPathUrlStrategy();
  Hive.registerAdapter(MultiAccountAdapter());
  await Hive.openBox<MultiAccount>('accounts');
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

Locale locale;
void getPref() async {
  var res = await SharedPref().getStringVariable("lan");

  if (res != null) {
    if (res != null && res == "ENGLISH") {
      locale = Locale('en', 'US');
    } else if (res != null && res == "DUTCH") {
      locale = Locale('nl', 'NL');
    } else {
      locale = Locale('en', 'US');
    }
  } else {
    locale = ui.window.locale;
    // Get.updateLocale(locale);
  }
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return OverlaySupport(
      child: GetMaterialApp.router(
        debugShowCheckedModeBanner: false,
        translations: LocaleString(),
        locale: locale,
        theme: ThemeData(
          primaryColor: green,
          primaryColorDark: greenDark,
          fontFamily: 'Montserrat-Medium',
          accentColor: Colors.grey,
          cursorColor: greenDark,
          textTheme: TextTheme(
            bodyText1: TextStyle(fontSize: 14.0),
          ),
        ),
        routeInformationParser: VxInformationParser(),
        routerDelegate: VxNavigator(
          routes: VxRoutes.instance.newMethod,
        ),
      ),
    );
  }
}

我的路由文件

class VxRoutes {
  static VxRoutes instance = VxRoutes();
  Map<Pattern, VxPageBuilder> get newMethod {
    return {
      "/": (_, param) => VxRoutePage(
            child: HomeScreen(
              showSnackbar: param ?? false,
            ),
            transition: (animation, child) => FadeTransition(
              opacity: animation,
              child: child,
            ),
          ),
  SteplerDetailScreenRoute: (uri, params) {
        var steplerId = uri.queryParameters["steplerId"];
        if (steplerId == null || steplerId == "") {
          return VxRoutePage(
            child: CrashScreen(),
            transition: (animation, child) => FadeTransition(
              opacity: animation,
              child: child,
            ),
          );
        }
        return VxRoutePage(
          child: SteplerDetailScreen(
            steplerId: int.tryParse(steplerId.toString()),
          ),
          transition: (animation, child) => FadeTransition(
            opacity: animation,
            child: child,
          ),
        );
      },

   FullPhotoRoute: (uri, params) {
        var url = uri.queryParameters["url"];
        if (url == null || url == "") {
          return VxRoutePage(
            child: CrashScreen(),
            transition: (animation, child) => FadeTransition(
              opacity: animation,
              child: child,
            ),
          );
        }
        return VxRoutePage(
          child: FullPhoto(
            url: url,
          ),
          transition: (animation, child) => FadeTransition(
            opacity: animation,
            child: child,
          ),
        );
      },
     
    };
  }
}

我的网站

<!DOCTYPE html>
<html>

<head>

  <base href="/">
  <meta name="google-signin-client_id"abc">
  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">

  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="stepler_web">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">

  <!-- Favicon -->
  <link rel="icon" type="image/png" href="favicon.png" />

  <title>Stepler</title>
  <link rel="manifest" href="manifest.json">
</head>

<body>
  <script
  async
  defer
  crossorigin="anonymous"
  src="https://connect.facebook.net/en_US/sdk.js"
></script>
  <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-messaging.js"></script>
  <script>
    // Your web app's Firebase configuration
    var firebaseConfig = {
      apiKey: "abc",
      authDomain: "abc",
      projectId: "abc",
      storageBucket: "abc",
      messagingSenderId: "abc",
      appId: "abc",
      measurementId: "abc"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
  </script>
  <script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('flutter-first-frame', function () {
        navigator.serviceWorker.register('flutter_service_worker.js');
      });
    }
  </script>
  <script src="main.dart.js" type="application/javascript"></script>
</body>

</html>
ecr0jaav

ecr0jaav1#

按照以下步骤操作
转到您的Firebase控制台(您的代码托管在那里)
编辑.htaccess(不存在请创建,有时不显示,所以启用 * 显示隐藏文件 *)
编辑/添加给定代码。

RewriteEngine on
RewriteCond %{REQUEST_FILENAME}% !-d
RewriteCond %{REQUEST_FILENAME}% !-f
RewriteRule . /index.html [L]

这4行代码是什么意思?
答:它重定向到index.html页面。
因为flutter web是一个基于单文件代码的web应用程序,所以你的URL不存在,比如你的URL是https://yourdomain.com/my-page,但flutter web只有index.html

nbysray5

nbysray52#

我通过删除此Vx.setPathUrlStrategy();解决了此问题

0sgqnhkj

0sgqnhkj3#

下面是另一种重写方法在firebase.json文件中添加以下行

// Serves index.html for requests to files or directories that do not exist
      "rewrites": [ {
        "source": "**",
        "destination": "/index.html"
      } ]

或完整代码

{
  "hosting": {
    "public": "...",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [ {
      "source": "**",
      "destination": "/index.html"
    } ]

  }
}

参考https://firebase.google.com/docs/hosting/full-config?authuser=2

相关问题