Home > Software engineering >  Flutter: alignment(x, y) not working inside column
Flutter: alignment(x, y) not working inside column

Time:07-07

I am trying to position the image to a specific spot on the screen but the Alignment in the y-axis is not working. The following is the code. The image is stuck at top-center of the screen. It can move about the x-axis but not the y-axis, as I have mentioned.

class MyClass extends StatefulWidget {
  const MyClass({Key? key}) : super(key: key);

  @override
  State<MyClass> createState() => _MyClassState();
}

class _MyClassState extends State<MyClass> {
  late double screenWidth, screenHeight;

  @override
  Widget build(BuildContext context) {
    screenHeight = MediaQuery.of(context).size.height;
    screenWidth = MediaQuery.of(context).size.width;

    return Scaffold(
      backgroundColor: const Color(0xFF081F37),
      body: Container(
        child: Column(
          children: [
            Stack(
              children: [
                Container(
                  alignment: Alignment(0, 1),
                  child: const Image(
                      image: AssetImage('assets/images/fp_bg_vector.png')),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

CodePudding user response:

position the image to a specific spot on the screen

You should use the Positioned() widget for that. Here's a complete example:

import 'package:flutter/material.dart';

void main() async {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyClass(),
    );
  }
}

class MyClass extends StatefulWidget {
  const MyClass({Key? key}) : super(key: key);

  @override
  State<MyClass> createState() => _MyClassState();
}

class _MyClassState extends State<MyClass> {
  late double screenWidth, screenHeight;

  @override
  Widget build(BuildContext context) {
    screenHeight = MediaQuery.of(context).size.height;
    screenWidth = MediaQuery.of(context).size.width;

    return Scaffold(
      backgroundColor: const Color(0xFF081F37),
      body: Column(
        children: [
          SizedBox(
            height: screenHeight,
            child: Stack(
              children: [
                Positioned(
                  top: 500,
                  child: const Image(
                      image: AssetImage('assets/images/fp_bg_vector.png')),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
  • Related