How to display texts in the middle of screen with Column in Flutter?

Viewed 761

I am very new to Flutter. I want to display two text with Column in middle of the screen.

But when I tried Center, it looks like this. It displays texts in top of the screen. Why this happens?

My code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build (BuildContext context) {
    return MaterialApp(
      title: "Flutter Demo",
      theme: ThemeData(
        primarySwatch: Colors.pink,
      ),
      home: MyHomePage(),
    );
  }
}


class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Hello world"),
      ),
      body: Center(
        child: Column(
          children: [
            Text(
              "Hello"
            ),
            Text(
              "World"
            )
          ],
        )
        )
      );
  }
}

Also, when I use Container instead of Column, it displays in center of screen like this.

What's the problem

I'm using Windows 10. Thanks.

2 Answers
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build (BuildContext context) {
    return MaterialApp(
      title: "Flutter Demo",
      theme: ThemeData(
        primarySwatch: Colors.pink,
      ),
      home: MyHomePage(),
    );
  }
}


class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Hello world"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,//main axis the vertical axis in a column so this positions the children at the center of the vertical axis
          crossAxisAlignment: CrossAxisAlignment.center,//the horizontal axis of a column, again we position the children's at the center of the horizontal axis
          children: [
            Text(
              "Hello"
            ),
            Text(
              "World"
            )
          ],
        )
        )
      );
  }
}

This should work What you were missing is mainAxisAlignment and crossAxisiAlignment Remember in Column(), mainAxisAlignment in the vertical axis and crossAxisiAlignment is the horizontal axis and this is opposite in a Row()

Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              "Hello"
            ),
            Text(
              "World"
            )
          ],
        )
Related