In Flutter, a common approach to handle text wrapping involves using the Text widget. You can control the maximum number of lines with the maxLines property and manage overflow behavior using the overflow property. By default, the Text widget automatically wraps text as needed, but for specific layout or design requirements, finer control may be necessary.
Example:
Consider a scenario where we have a long text string that we want to display within a container of fixed width, showing an ellipsis (...) when it exceeds three lines. The implementation is as follows:
dartimport 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Container( padding: EdgeInsets.all(20.0), width: 300, // Set container width child: Text( 'This is a very long text string that we want to handle correctly in Flutter for wrapping. If the text exceeds the container's maximum line count, we want to show an ellipsis.', style: TextStyle(fontSize: 16), // Set text style overflow: TextOverflow.ellipsis, // Show ellipsis for overflow maxLines: 3, // Maximum of 3 lines ), ), ), ); } }
In this example, we begin by importing the Flutter material.dart package and setting up a simple application structure. Within the home page Scaffold, we define a container Container with a fixed width of 300 pixels. Inside this container, we add a Text widget to display the text.
maxLines: 3property sets the text to display at most three lines.overflow: TextOverflow.ellipsisproperty ensures that if the text exceeds three lines, the overflow is shown as an ellipsis (...).
This method is ideal for scenarios like news summaries or product descriptions that require text previews. By appropriately adjusting the maxLines and overflow properties, you can achieve various text display effects to satisfy different UI design needs.