Search code examples
imagefluttercentering

How to put Image in Center of the screen whithout margin/padding in Flutter?


Heyy guys, how ya doin? I'm trying to put this image in the middle of the screen, it's just a image with a little text below it, but i can't find a way to do it without using padding or margin. When i use padding or margin to down the image, when i go to the dialog pop up screen, show me this.

image of the error

So, how can i put the image in the center of the screen independent of anything? I've already tryed using Center() and Container, but none worked.

Here's my code bellow. I'll mark the part of the code i wanna change with this symbol *.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'dialogAddUser.dart';

class HomePage extends StatelessWidget {
  static String tag = '/home';

  @override
  Widget build(BuildContext context) {
    Firebase.initializeApp();
    var snapshots = FirebaseFirestore.instance
        .collection('senhas')
        .where('excluido', isEqualTo: false)
        .orderBy('data')
        .snapshots();

    return Scaffold(
      backgroundColor: Colors.grey[200],
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(top: 60, bottom: 0, left: 10),
            child: Text.rich(TextSpan(
              children: <TextSpan>[
                TextSpan(
                  text: 'Bem-vindo(a)',
                  style: TextStyle(
                      fontFamily: 'SanFrancisco',
                      fontSize: 40,
                      fontWeight: FontWeight.w500),
                ),
                TextSpan(
                  text: '\nSuas senhas cadastradas',
                  style: TextStyle(fontSize: 25, fontWeight: FontWeight.w300),
                )
              ],
            )),
          ),
          StreamBuilder(
              stream: snapshots,
              builder: (
                BuildContext context,
                AsyncSnapshot<QuerySnapshot> snapshot,
              ) {
                // Mensagem de erro
                if (snapshot.hasError) {
                  return Center(
                      child: Text('Ocorreu um erro: \n${snapshot.error}'));
                }

                // Bolinha carregando enquanto processa os arquivos.
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(child: CircularProgressIndicator());
                }

                // Se nenhuma senha for encontrada
                **// This is the Part!**
                **********************************************
                if (snapshot.data.docs.length == 0) {
                  return Column(
                    children: <Widget>[  
                      Image(
                        image: AssetImage('assets/no_data_found.png'),
                        height: 350,
                      ),
                      Container(
                        margin: const EdgeInsets.fromLTRB(30, 10, 30, 0),
                        child: Center(
                          child: Text.rich(
                            TextSpan(
                              children: <TextSpan>[
                                TextSpan(
                                    text: 'Oops!\n',
                                    style: TextStyle(
                                        fontFamily: 'SanFrancisco',
                                        fontSize: 40,
                                        fontWeight: FontWeight.w500)),
                                TextSpan(
                                  text: 'Nenhuma senha encontrada',
                                  style: TextStyle(
                                    fontFamily: 'SanFrancisco',
                                    fontSize: 25,
                                    fontWeight: FontWeight.w300,
                                  ),
                                ),
                              ],
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                      // Imagem no_data_found
                    ],
                  );
                }
                ********************************************

                // Mostrando as senhas
                return Flexible(
                  child: ListView.builder(
                    itemCount: snapshot.data.docs.length,
                    itemBuilder: (BuildContext context, int i) {
                      var doc = snapshot.data.docs[i];
                      var itens = doc.data();

                      return Container(
                        padding: const EdgeInsets.fromLTRB(0, 15, 0, 15),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(15)),
                        margin: const EdgeInsets.fromLTRB(15, 15, 15, 5),
                        // Layout de cada senha
                        child: ListTile(
                          isThreeLine: true,
                          leading: IconButton(icon: Icon(Icons.person_rounded)),
                          title: Text(itens['nomeDaSenha'],
                              style: TextStyle(
                                  fontSize: 25, color: Colors.orange[700])),
                          subtitle: Text("Senha: ${itens['senha']}",
                              style: TextStyle(fontSize: 20)),
                          trailing: IconButton(
                            icon: Icon(
                              Icons.delete,
                              size: 30,
                              color: Colors.red[300],
                            ),
                            onPressed: () {
                              doc.reference.delete();
                              Fluttertoast.showToast(
                                  msg: "Senha apagada",
                                  toastLength: Toast.LENGTH_SHORT,
                                  gravity: ToastGravity.BOTTOM,
                                  backgroundColor: Colors.grey[500]);
                            },
                          ),
                        ),
                      );
                    },
                  ),
                );
              }),
        ],
      ),

      // Floating button Adicionar
      floatingActionButton: Padding(
        padding: const EdgeInsets.only(bottom: 15, right: 5),
        child: FloatingActionButton(
          onPressed: () => modalCreate(context),
          tooltip: 'Adicionar',
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

Any question about the code, just let me know. Looking forward the answer, Thanks.


Solution

  • You can use this sample layout. Put it simple I'm using a Stack with center alignment and a Container wrapping outside to fill the screen.

    Full example:

    import "package:flutter/material.dart";
    
    main() {
      runApp(MaterialApp(
        home: HomePage(),
      ));
    }
    
    class HomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.grey[200],
          body: Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            child: Stack(
              alignment: AlignmentDirectional.center,
              children: [
                // This set the position of the inside Container to top-left
                Align(
                    alignment: Alignment.topLeft,
                    child: Container(
                    margin: const EdgeInsets.only(top: 60, bottom: 0, left: 10),
                    child: Text.rich(TextSpan(
                      children: <TextSpan>[
                        TextSpan(
                          text: 'Bem-vindo(a)',
                          style: TextStyle(
                              fontFamily: 'SanFrancisco',
                              fontSize: 40,
                              fontWeight: FontWeight.w500),
                        ),
                        TextSpan(
                          text: '\nSuas senhas cadastradas',
                          style:
                              TextStyle(fontSize: 25, fontWeight: FontWeight.w300),
                        )
                      ],
                    )),
                  ),
                ),
    
                // This Column will align to center
                Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image(
                      image: AssetImage('assets/no_data_found.png'),
                      height: 350,
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(30, 10, 30, 0),
                      child: Center(
                        child: Text.rich(
                          TextSpan(
                            children: <TextSpan>[
                              TextSpan(
                                  text: 'Oops!\n',
                                  style: TextStyle(
                                      fontFamily: 'SanFrancisco',
                                      fontSize: 40,
                                      fontWeight: FontWeight.w500)),
                              TextSpan(
                                text: 'Nenhuma senha encontrada',
                                style: TextStyle(
                                  fontFamily: 'SanFrancisco',
                                  fontSize: 25,
                                  fontWeight: FontWeight.w300,
                                ),
                              ),
                            ],
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
    
          // Floating button Adicionar
          floatingActionButton: Padding(
            padding: const EdgeInsets.only(bottom: 15, right: 5),
            child: FloatingActionButton(
              onPressed: () {},
              tooltip: 'Adicionar',
              child: Icon(Icons.add),
            ),
          ),
        );
      }
    }