如何为 Flutter Web 应用程序设置标题和图标?

Bru*_*alo 11 flutter flutter-web

我想要做的是构建一个 flutter web 应用程序,当在浏览器中显示时,该选项卡会显示一个图标和一个标题(目前它只显示世界图标和本地主机...标题)。

实际结果 :

实际结果

预期结果:

想要的结果

编辑:我现在可以添加标题,因为这是在主函数中设置的

Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      leading: Icon(Icons.menu, color: Colors.white,),
      title: Text(_your title here_),
    )
    ...
  );
}
Run Code Online (Sandbox Code Playgroud)

所以,我唯一需要编辑的是网站图标

Die*_*vel 29

为了将标题更改为您想要的,您需要将参数title(即 a String)添加到您的MaterialApp小部件。

return MaterialApp(
  title: "MyTitle", 
  home: MyHomeWidget());
Run Code Online (Sandbox Code Playgroud)


小智 15

  • 编辑标题

这是最简单的。Title只需在每个页面上或直接在materialApp构造函数中使用小部件,并将标题字符串键设置为您需要的标题文本。像这样:

...
Title(
  color: myColors, //not  important  in web but still required
  title: 'web  page title',
  child: myChildWidget,
),
...
Run Code Online (Sandbox Code Playgroud)
  • 编辑图标

如果您的应用程序仅适用于 Web,请使用该dart:html库通过 DOM 访问来执行更改。像这样的东西

import 'dart:html';
...
...
updateIcon(String assetIcon){
      LinkElement link = (document.querySelector("link[rel*='icon']") ??
          document.createElement('link')) as LinkElement;
      link.type = 'image/x-icon';
      link.rel = 'shortcut icon';
      link.href = assetIcon;
}
Run Code Online (Sandbox Code Playgroud)

如果您的应用程序是多平台的,您需要为网络创建单独的主文件,main_web.dart例如. 并在该文件中声明前一个函数。现在,在任何需要设置图标的地方,您只需在使用关键字检查平台后调用该方法即可kIsWeb

例如:更改页面内的图标

...
initState(){
    super.initSate();
    if(kIsWeb){
      WebMixin.updateIcon("assets/home_icon.png"); //WebMixin is just a helper.  replace  it by your  one.
    }
}
...
Run Code Online (Sandbox Code Playgroud)


Abh*_*ran 12

假设您已经有一个favicon.ico文件,将它放在your_project_dir\web文件夹中index.html,如下所示,足以让浏览器将其选中。

在此处输入图片说明

以下是放置favicon.ico' in theweb` 文件夹的结果。确保进行干净的构建。

在此处输入图片说明

在其他情况下,您可以使用link您内部的标签手动提及它,index.html如本维基百科页面中所述

  • 有没有办法动态设置index.html页面的链接和标题?当打开使用 Flutter 构建的网站时,我需要从 API 中获取企业的详细信息,并将 favicon 设置为企业的徽标,将标题设置为企业的名称。 (2认同)

Ste*_*veM 9

您可以设置MaterialApp小部件的onGenerateTitle属性,并提供一个回调函数来构建您的标题。该回调被称为每次重建。如果您希望页面的标题动态更改或希望生成本地化的标题,这将非常有用。onGenerateTitleWidgetsApp

MaterialApp(
  ...
  onGenerateTitle: (BuildContext context) {
    return AppLocalizations.of(context).myTitle;
  }
  ...
);
Run Code Online (Sandbox Code Playgroud)


Joe*_*ler 8

如果您想知道如何更改设备主页上的应用程序名称,可以更新 web/manifest.json 中的“name”和“short_name”值:

"name": "Ideasky",
"short_name": "Ideasky",
Run Code Online (Sandbox Code Playgroud)