如何在Flutter应用中添加背景图片?

fcc*_*lho 4 dart flutter

我正在尝试将背景图像添加到我的Flutter应用中,因此我也经历了所有类似的问题。应用程序m运行正常,但没有出现图像。

这是我的小部件代码:

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
        actions: <Widget>[
          new IconButton(icon: const Icon(Icons.list), onPressed: _loadWeb)
        ],
      ),
      body: new Stack(
        children: <Widget>[
          Container(
            child: new DecoratedBox(
              decoration: new BoxDecoration(
                image: new DecorationImage(
                  image: new AssetImage("images/logo.png"),
                  fit: BoxFit.fill,
                ),
              ),
            ),
          ),
          Center(
            child: _authList(),
          )
        ],
      ),

      floatingActionButton: FloatingActionButton(
        onPressed: getFile,
        tooltip: 'Select file',
        child: Icon(Icons.sd_storage),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    ));
  }
Run Code Online (Sandbox Code Playgroud)

该应用程序运行良好,并且堆栈上的第二个小部件(即listView)正常运行,但未显示该图像。

有任何想法吗?

flu*_*ter 15

Scaffold不支持背景图片的任何概念。您可以做的是给Scaffold透明颜色并将其放在中,Container然后使用decoration属性拉入所需的背景图像。应用程序栏也是透明的。

Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Container(
        decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage("images/logo.png"), fit: BoxFit.cover)),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: AppBar(
            elevation: 0,
            backgroundColor: Colors.transparent,
            title: Text('My App'),
            centerTitle: true,
            leading: IconButton(
                icon: Icon(
                  Icons.list,
                  color: Colors.white,
                ),
                onPressed: () {}),
          ),
        ),
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!它工作得很好。我还为容器添加了颜色以避免将图像放置在黑色背景上 (2认同)

Vin*_*nto 12

使用BoxDecorationdecoration的属性Container

  Container(
    decoration: new BoxDecoration(
      image: new DecorationImage(
        image: new AssetImage("images/logo.png"),
        fit: BoxFit.fill,
      ),
    ),
  ),
Run Code Online (Sandbox Code Playgroud)


小智 5

    return MaterialApp(
      title: "MoonLight",
      home: Container(
        decoration:new BoxDecoration(
            image:  new DecorationImage(
              image: new AssetImage("graphics/moon.jpg"),
              fit: BoxFit.cover,)
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
        ),
      ),
    ),
Run Code Online (Sandbox Code Playgroud)