Expanded widget in Flutter
Flutter

Expanded widget in Flutter

Editorial Team
Editorial Team

Follow us on Discord or Telegram to get access to free tutorials and updates.

In the previous post about Flutter, we learned how to arrange the widgets as rows and columns. Sometimes, you might have noticed that the context of the text widget is not completely displayed if it has a long text. This post demonstrates how to use the Expanded widget to display such long texts.

If you did not understand what the error was, replace the contents of main.dart with the following code.

import 'package:flutter/material.dart';

void main(){
  runApp(
    MaterialApp(
      title: "My App",
      home: Container(
        color: Colors.indigo,
        child: Row(
          children: <Widget>[
            Text("This is a very looooooong text.", textDirection: TextDirection.ltr,),
            Text("IItem 2", textDirection: TextDirection.ltr,),
          ],
        ),
      ),
    )
  );
}

If you run the project now, you will see an output similar to the one shown below.

Using Expanded widget

The Expanded widget can be used to display content that is wider than the screen. Is simply forces the content of the widget to fit within the available space.

Replace the content of main.dart with the following code to see how the Expanded widget works.

import 'package:flutter/material.dart';

void main(){
  runApp(
    MaterialApp(
      title: "My App",
      home: Container(
        color: Colors.indigo,
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text("This is a very looooooong text.", textDirection: TextDirection.ltr,),
            ),
            Text("IItem 2", textDirection: TextDirection.ltr,),
          ],
        ),
      ),
    )
  );
}

Here, I have placed a Text widget as the child of Expanded widget so that the content of the Text widget will be forced to fit within the size of the screen.

Run the project. You will get an output similar to the one shown below.

Flutter tutorial - Using Expanded widget