Flutter : Fill the image over the body

1.1k Views Asked by At

I am working on a flutter project. I have loaded an image and I want it to fill up the body. After reading the documentation I came up with this:

void main() => runApp(MaterialApp(
  home : Scaffold(
      appBar: AppBar(
        title: Center(
           child: Text("I am rich"),
        ),
        backgroundColor: Colors.amberAccent,
      ),
      backgroundColor: Colors.purple,
      body: Image(
        fit: BoxFit.cover, 
        image: NetworkImage('https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQWqFc0Y7fRegMPpHoqNmD-hdba-3Zk_ttQQw&usqp=CAU'),
      ),
    )
  )
);

But it does not seem to work. Please help

3

There are 3 best solutions below

4
On BEST ANSWER

You can copy paste run full code below
You can directly set width and height to window.physicalSize.width and window.physicalSize.height
And you can use BoxFit.fill, see effect below

Image(
    fit: BoxFit.fill,
    width: window.physicalSize.width,
    height: window.physicalSize.height,

working demo

enter image description here

full code

import 'dart:ui';

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: Center(
          child: Text("I am rich"),
        ),
        backgroundColor: Colors.amberAccent,
      ),
      backgroundColor: Colors.purple,
      body: Image(
        fit: BoxFit.fill,
        width: window.physicalSize.width,
        height: window.physicalSize.height,
        image: NetworkImage(
            'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQWqFc0Y7fRegMPpHoqNmD-hdba-3Zk_ttQQw&usqp=CAU'),
      ),
    )));
0
On

You can use Image.network instead Image widget, as mentioned in official document. Or, you can add height property to image.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var title = 'Web Images';

    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
       body: Image(
        height: double.infinity,
        fit: BoxFit.cover,
        image: NetworkImage(
          'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQWqFc0Y7fRegMPpHoqNmD-hdba-3Zk_ttQQw&usqp=CAU',
        ),
      ),
      ),
    );
  }
}
0
On

Use MediaQuery for this,it will set the image based on the screensize of phone

body: Center(
        child: Image.network(
          'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQWqFc0Y7fRegMPpHoqNmD- hdba-          3Zk_ttQQw&usqp=CAU',
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          fit: BoxFit.fill,
        ),
      ),