3

在Flutter中设置背景图片 / background image

 3 years ago
source link: https://www.bugcatt.com/archives/1711
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

有时我们需要给APP的某个页面或某个widget添加背景图. 本篇文章就来记录下如何在Flutter中设置背景图片.

有图有真相, 先来看下我们本篇博客将实现的最终效果:

Flutter-%E8%AE%BE%E7%BD%AE%E8%83%8C%E6%99%AF%E5%9B%BE%E7%89%87-background-image-04.png

速度快的同学直接看下面的核心代码!

创建Flutter项目

创建一个新的Flutter项目, 运行查看一下:

Flutter 设置背景图片 background image-02

空白的, 啥也木有.

添加图片资源

这里为大家提供一个好看的背景图:

下载此图片, 重命名为background.jpg. 我们来将其添加至Flutter项目中.

创建资源目录

创建目录./assets/images, 将上面的图片放到该目录下:

引入pubspec.yaml

进入pubspec.yaml, 将背景图片资源文件路径assets/images/background.jpg进行导入:

flutter:
  uses-material-design: true
  assets:
   - assets/images/background.jpg
这里一定要注意缩进, 若格式有误将会出错!

进行package get或在终端中输入:

flutter packages get

展示背景图

回到./lib/main.dart, 进行代码替换:

Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      )
Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/background.jpg"),
            fit: BoxFit.cover,
          ),
        ),
        /*child替换为你自己的子widget*/
        child: null,
      )
再次运行项目, 看看是不是成功了!
Flutter-%E8%AE%BE%E7%BD%AE%E8%83%8C%E6%99%AF%E5%9B%BE%E7%89%87-background-image-04.png
Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/background.jpg"),
            fit: BoxFit.cover,
          ),
        ),
        /*child替换为你自己的子widget*/
        child: null,
      ),

设置背景图其实并不复杂, 我们通过Containerdecoration属性来控制了修饰的元素为图片. 相信各位可以举一反三.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK