Skip to main content

Flutter Set Widget Position Absolute - Right Way

Position Absolute is a unique way to put a Widget or Container above any Root or Child widget at a fixed position given from left right top and bottom. In position absolute it sticks the given View with given margin from all sides above any view. Basically we fix position of Container on screen. In flutter we can to achieve absolute functionality we will use Positioned widget along with Stack widget as Parent.

Flutter Set Widget Position Absolute - Right Way

1. Defining Stack Widget in the body section of app.
Stack(children: [

])
2. Creating multiple Column Widget inside Stack widget as its children.
Stack(children: [
      Column(children: [
        Container(
          width: double.infinity,
          height: 200,
          color: Colors.brown,
        ),
        Container(
          width: double.infinity,
          height: 200,
          color: Colors.blueGrey,
        ),
      ]),
])
3. Now after closing the Column widget we would define Positioned widget with Top and Left position defined. Here left and top position means it will put the Positioned widget from Top and left side of screen above any View.
Stack(children: [
      Column(children: [
        Container(
          width: double.infinity,
          height: 200,
          color: Colors.brown,
        ),
        Container(
          width: double.infinity,
          height: 200,
          color: Colors.blueGrey,
        ),
      ]),
      Positioned(
          top: 10,
          left: 10,
          child: Container(
            width: 50,
            height: 50,
            color: Colors.deepOrange,
          ))
])
Screenshot:
Flutter Set Widget Position Absolute
Source code for main.dart file:
import 'package:flutter/material.dart';

void main() => runApp(const App());

class App extends StatelessWidget {
  const App({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: SafeArea(
                child: Center(
                    child: Stack(children: [
      Column(children: [
        Container(
          width: double.infinity,
          height: 200,
          color: Colors.brown,
        ),
        Container(
          width: double.infinity,
          height: 200,
          color: Colors.blueGrey,
        ),
      ]),
      Positioned(
          top: 10,
          left: 10,
          child: Container(
            width: 50,
            height: 50,
            color: Colors.deepOrange,
          ))
    ])))));
  }
}

Comments