Monday, April 16, 2018

Motivational quote app: Add background image to your flutter app Ep.9 Pt.1



Create a directory called assets in you project root directory and inside that directory create another directory called images and add your images to that images directory. Below you can find the link to download images that I used for these few tutorials.

In the pubspec.yaml file find the flutter section add assets section and add images paths to it like in the yaml file below.(/p>

Now, goto main.dart file and delete all the code. Next, import the material file and add the main method with runApp method call.


import 'package:flutter/material.dart';

void main() => runApp(new QuoteApp());


In above line, you can see I have created a anonymous object as the argument to the runApp. That is a StatelessWidget, we are going to create now.


You can use code template to easily create a StatelessWidget stless then press enter or in IntelliJ if did not get intellisence press tab key.

class QuoteApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Container();
  }
}


Now, inside the build method return a material app not container. with title and home property.

title: 'Motivational Quote App',
home:


For the home property add a Scaffold with body property and we are going to to add Stack widget to the body property because we need widgets on top of background image. In this case a text widget.

home: new Scaffold(body: new Stack(children: []),

Now, as a children add a Container widget with a BoxDecoration. And for the image property of BoxDecoration add a AssetImage with image URL and to cover the whole screen we have to use fit property with BoxFit.cover, as below:

body: new Stack(
  children: [
    new Container(
      decoration: new BoxDecoration(
        image: new DecorationImage(
          image: new AssetImage('assets/images/bill-gates.jpg'),
          fit: BoxFit.cover,
        ),
      ),
    ),
  ]
),

Now we have completely added the background image to our flutter app. Now you can add Text widget in top of the image by adding Text Widget as a children of Stack Widget like below:

new Center(
   child: new Text('Never give up'),
)


I have centered the text using Center Widget.

Complete dart, and yaml file and images are below:

pubspec.yaml



main.dart



Some or all images may not free to use. Please only use for learning purposes. You can have you own images
or you can edit/customise images.

Also you can have images with varies resolutions. So that your images will scale occording to the device.

Download images that I used

Follow my previous tutorial for that.

2 comments:

  1. images link does not work. unable to download files.

    ReplyDelete
  2. nice post... Beginners like me need this type post. also recommended to all https://androidride.com/flutter-background-image/

    ReplyDelete