如何为扑朔迷离的Web应用程序设置标题和图标?

时间:2019-12-06 22:15:57

标签: flutter flutter-web

我要做的是构建一个Flutter Web应用程序,当在浏览器中显示该选项卡时,该选项卡将显示一个图标和一个标题(目前,它仅显示世界图标和localhost ...标题)。

实际结果:

Actual Result

所需结果:

Desired Result

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

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

所以,我唯一需要编辑的是收藏夹图标

4 个答案:

答案 0 :(得分:10)

为了将标题更改为所需的标题,您需要向title小部件中添加参数String(其中是MaterialApp)。

return MaterialApp(
  title: "MyTitle", 
  home: MyHomeWidget());

答案 1 :(得分:5)

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

MaterialApp(
  ...
  onGenerateTitle: (BuildContext context) {
    return AppLocalizations.of(context).myTitle;
  }
  ...
);

答案 2 :(得分:1)

假设您已经有一个favicon.ico文件,将其放在your_project_dir\web旁边的index.html文件夹中,如下所示,就足以使浏览器将其拾取。

enter image description here

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

enter image description here

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

答案 3 :(得分:0)

  • 编辑标题

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

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

如果您的应用仅适用于网络,请使用 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;
}

如果您的应用程序是多平台,您需要为网络创建单独的主文件,例如 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.
    }
}
...