id
stringlengths
14
17
text
stringlengths
23
1.11k
source
stringlengths
35
114
44306f44f88c-4
Other useful widgets and classes for creating a responsive UI: AspectRatio CustomSingleChildLayout CustomMultiChildLayout FittedBox FractionallySizedBox LayoutBuilder MediaQuery MediaQueryData OrientationBuilder Other resources For more information, here are a few resources, including contributions from the Flutter community: Developing for Multiple Screen Sizes and Orientations in Flutter by Deven Joshi Build Responsive UIs in Flutter by Raouf Rahiche Making Cross-platform Flutter Landing Page Responsive by Priyanka Tyagi How to make flutter app responsive according to different screen size?, a question on StackOverflow Creating an adaptive Flutter app
https://docs.flutter.dev/development/ui/layout/adaptive-responsive/index.html
44306f44f88c-5
Creating an adaptive Flutter app Learn more about creating an adaptive Flutter app with Building adaptive apps, written by the gskinner team. You might also check out the following episodes of The Boring Show: Adaptive layouts Adaptive layouts, part 2 For an excellent example of an adaptive app, check out Flutter Folio, a scrapbooking app created in collaboration with gskinner and the Flutter team: The Folio source code is also available on GitHub. Learn more on the gskinner blog. Other resources You can learn more about creating platform adaptive apps in the following resources: Platform-specific behaviors and adaptations, a page on this site. Designing truly adaptive user interfaces a blog post and video by Aloïs Deniel, presented at this year’s FlutterViking conference.
https://docs.flutter.dev/development/ui/layout/adaptive-responsive/index.html
44306f44f88c-6
The Flutter gallery app (repo) has been written as an adaptive app.
https://docs.flutter.dev/development/ui/layout/adaptive-responsive/index.html
fa7670b2f323-0
Dealing with box constraints UI Layout Box constraints Unbounded constraints Flex Note: You might be directed to this page if the framework detects a problem involving box constraints. Note: If you are confused by how constraints, sizing, and positioning work in Flutter, see Understanding constraints. In Flutter, widgets are rendered by their underlying RenderBox objects. Render boxes are given constraints by their parent, and size themselves within those constraints. Constraints consist of minimum and maximum widths and heights; sizes consist of a specific width and height. Generally, there are three kinds of boxes, in terms of how they handle their constraints: Those that try to be as big as possible. For example, the boxes used by Center and ListView.
https://docs.flutter.dev/development/ui/layout/box-constraints/index.html
fa7670b2f323-1
Those that try to be the same size as their children. For example, the boxes used by Transform and Opacity. Those that try to be a particular size. For example, the boxes used by Image and Text. Some widgets, for example Container, vary from type to type based on their constructor arguments. In the case of Container, it defaults to trying to be as big as possible, but if you give it a width, for instance, it tries to honor that and be that particular size. Others, for example Row and Column (flex boxes) vary based on the constraints they are given, as described below in the “Flex” section.
https://docs.flutter.dev/development/ui/layout/box-constraints/index.html
fa7670b2f323-2
The constraints are sometimes “tight”, meaning that they leave no room for the render box to decide on a size (for example, if the minimum and maximum width are the same, it is said to have a tight width). An example of this is the App widget, which is contained by the RenderView class: the box used by the child returned by the application’s build function is given a constraint that forces it to exactly fill the application’s content area (typically, the entire screen). Many of the boxes in Flutter, especially those that just take a single child, pass their constraint on to their children. This means that if you nest a bunch of boxes inside each other at the root of your application’s render tree, they’ll all exactly fit in each other, forced by these tight constraints. Some boxes loosen the constraints, meaning the maximum is maintained but the minimum is removed. For example, Center. Unbounded constraints
https://docs.flutter.dev/development/ui/layout/box-constraints/index.html
fa7670b2f323-3
Unbounded constraints In certain situations, the constraint that is given to a box is unbounded, or infinite. This means that either the maximum width or the maximum height is set to double.infinity. A box that tries to be as big as possible won’t function usefully when given an unbounded constraint and, in debug mode, such a combination throws an exception that points to this file. The most common cases where a render box finds itself with unbounded constraints are within flex boxes (Row and Column), and within scrollable regions (ListView and other ScrollView subclasses). In particular, ListView tries to expand to fit the space available in its cross-direction (for example, if it’s a vertically-scrolling block, it tries to be as wide as its parent). If you nest a vertically scrolling ListView inside a horizontally scrolling ListView, the inner one tries to be as wide as possible, which is infinitely wide, since the outer one is scrollable in that direction.
https://docs.flutter.dev/development/ui/layout/box-constraints/index.html
fa7670b2f323-4
Flex Flex boxes themselves (Row and Column) behave differently based on whether they are in bounded constraints or unbounded constraints in their given direction. In bounded constraints, they try to be as big as possible in that direction. In unbounded constraints, they try to fit their children in that direction. In this case, you cannot set flex on the children to anything other than 0. In the widget library, this means that you cannot use Expanded when the flex box is inside another flex box or inside a scrollable. If you do, you’ll get an exception message pointing you at this document. In the cross direction, for example, in the width for Column (vertical flex) or in the height for Row (horizontal flex), they must never be unbounded, otherwise they would not be able to reasonably align their children.
https://docs.flutter.dev/development/ui/layout/box-constraints/index.html
8b28ba4cbacb-0
Building adaptive apps UI Layout Building adaptive apps Overview Building adaptive layouts Layout widgets Visual density Contextual layout Screen-based breakpoints Use LayoutBuilder for extra flexibility Device segmentation Single source of truth for styling Design to the strengths of each form factor Use desktop build targets for rapid testing Solve touch first Input Scroll wheel Tab traversal and focus interactions Controlling traversal order Keyboard accelerators Mouse enter, exit, and hover Idioms and norms Consider expected behavior on each platform Find a platform advocate Stay unique Common idioms and norms to consider
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-1
Common idioms and norms to consider Scrollbar appearance and behavior Multi-select Selectable text Title bars Context menus and tooltips Horizontal button order Menu bar Drag and drop Educate yourself on basic usability principles Overview Flutter provides new opportunities to build apps that can run on mobile, desktop, and the web from a single codebase. However, with these opportunities, come new challenges. You want your app to feel familiar to users, adapting to each platform by maximizing usability and ensuring a comfortable and seamless experience. That is, you need to build apps that are not just multiplatform, but are fully platform adaptive. There are many considerations for developing platform-adaptive apps, but they fall into three major categories: Layout Input Idioms and norms
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-2
Layout Input Idioms and norms This page covers all three categories in detail using code snippets to illustrate the concepts. If you’d like to see how these concepts come together, check out the Flokk and Folio examples that were built using the concepts described here. Original demo code for adaptive app development techniques from flutter-adaptive-demo. Building adaptive layouts One of the first things you must consider when bringing your app to multiple platforms is how to adapt it to the various sizes and shapes of the screens that it will run on. Layout widgets If you’ve been building apps or websites, you’re probably familiar with creating responsive interfaces. Luckily for Flutter developers, there are a large set of widgets to make this easier. Some of Flutter’s most useful layout widgets include: Single child
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-3
Single child Align—Aligns a child within itself. It takes a double value between -1 and 1, for both the vertical and horizontal alignment. AspectRatio—Attempts to size the child to a specific aspect ratio. ConstrainedBox—Imposes size constraints on its child, offering control over the minimum or maximum size. CustomSingleChildLayout—Uses a delegate function to position a single child. The delegate can determine the layout constraints and positioning for the child. Expanded and Flexible—Allows a child of a Row or Column to shrink or grow to fill any available space. FractionallySizedBox—Sizes its child to a fraction of the available space. LayoutBuilder—Builds a widget that can reflow itself based on its parents size. SingleChildScrollView—Adds scrolling to a single child. Often used with a Row or Column.
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-4
Multichild Column, Row, and Flex—Lays out children in a single horizontal or vertical run. Both Column and Row extend the Flex widget. CustomMultiChildLayout—Uses a delegate function to position multiple children during the layout phase. Flow—Similar to CustomMultiChildLayout, but more efficient because it’s performed during the paint phase rather than the layout phase. ListView, GridView, and CustomScrollView—Provides scrollable lists of children. Stack—Layers and positions multiple children relative to the edges of the Stack. Functions similarly to position-fixed in CSS. Table—Uses a classic table layout algorithm for its children, combining multiple rows and columns. Wrap—Displays its children in multiple horizontal or vertical runs. To see more available widgets and example code, see Layout widgets. Visual density
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-5
Visual density Different input devices offer various levels of precision, which necessitate differently sized hit areas. Flutter’s VisualDensity class makes it easy to adjust the density of your views across the entire application, for example, by making a button larger (and therefore easier to tap) on a touch device. When you change the VisualDensity for your MaterialApp, MaterialComponents that support it animate their densities to match. By default, both horizontal and vertical densities are set to 0.0, but you can set the densities to any negative or positive value that you want. By switching between different densities, you can easily adjust your UI: To set a custom visual density, inject the density into your MaterialApp theme: To use VisualDensity inside your own views, you can look it up:
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-6
To use VisualDensity inside your own views, you can look it up: Not only does the container react automatically to changes in density, it also animates when it changes. This ties together your custom components, along with the built-in components, for a smooth transition effect across the app. As shown, VisualDensity is unit-less, so it can mean different things to different views. In this example, 1 density unit equals 6 pixels, but this is totally up to your views to decide. The fact that it is unit-less makes it quite versatile, and it should work in most contexts. It’s worth noting that the Material Components generally use a value of around 4 logical pixels for each visual density unit. For more information about the supported components, see VisualDensity API. For more information about density principles in general, see the Material Design guide. Contextual layout
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-7
Contextual layout If you need more than density changes and can’t find a widget that does what you need, you can take a more procedural approach to adjust parameters, calculate sizes, swap widgets, or completely restructure your UI to suit a particular form factor. Screen-based breakpoints The simplest form of procedural layouts uses screen-based breakpoints. In Flutter, this can be done with the MediaQuery API. There are no hard and fast rules for the sizes to use here, but these are general values: Using breakpoints, you can set up a simple system to determine the device type: As an alternative, you could abstract it more and define it in terms of small to large: Screen-based breakpoints are best used for making top-level decisions in your app. Changing things like visual density, paddings, or font-sizes are best when defined on a global basis.
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-8
You can also use screen-based breakpoints to reflow your top-level widget trees. For example, you could switch from a vertical to a horizontal layout when the user isn’t on a handset: In another widget, you might swap some of the children completely: Use LayoutBuilder for extra flexibility Even though checking total screen size is great for full-screen pages or making global layout decisions, it’s often not ideal for nested subviews. Often, subviews have their own internal breakpoints and care only about the space that they have available to render. The simplest way to handle this in Flutter is using the LayoutBuilder class. LayoutBuilder allows a widget to respond to incoming local size constraints, which can make the widget more versatile than if it depended on a global value. The previous example could be rewritten using LayoutBuilder:
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-9
The previous example could be rewritten using LayoutBuilder: This widget can now be composed within a side panel, dialog, or even a full-screen view, and adapt its layout to whatever space is provided. Device segmentation There are times when you want to make layout decisions based on the actual platform you’re running on, regardless of size. For example, when building a custom title bar, you might need to check the operating system type and tweak the layout of your title bar, so it doesn’t get covered by the native window buttons. To determine which combination of platforms you’re on, you can use the Platform API along with the kIsWeb value: The Platform API can’t be accessed from web builds without throwing an exception, because the dart.io package is not supported on the web target. As a result, this code checks for web first, and because of short-circuiting, Dart will never call Platform on web targets.
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-10
Single source of truth for styling You’ll probably find it easier to maintain your views if you create a single source of truth for styling values like padding, spacing, corner shape, font sizes, and so on. This can be done easily with some helper classes: These constants can then be used in place of hard-coded numeric values: With all views referencing the same shared-design system rules, they tend to look better and more consistent. Making a change or adjusting a value for a specific platform can be done in a single place, instead of using an error-prone search and replace. Using shared rules has the added benefit of helping enforce consistency on the design side. Some common design system categories that can be represented this way are: Animation timings Sizes and breakpoints Insets and paddings Corner radius Shadows Strokes Font families, sizes, and styles
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-11
Strokes Font families, sizes, and styles Like most rules, there are exceptions: one-off values that are used nowhere else in the app. There is little point in cluttering up the styling rules with these values, but it’s worth considering if they should be derived from an existing value (for example, padding + 1.0). You should also watch for reuse or duplication of the same semantic values. Those values should likely be added to the global styling ruleset. Design to the strengths of each form factor Beyond screen size, you should also spend time considering the unique strengths and weaknesses of different form factors. It isn’t always ideal for your multiplatform app to offer identical functionality everywhere. Consider whether it makes sense to focus on specific capabilities, or even remove certain features, on some device categories.
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-12
For example, mobile devices are portable and have cameras, but they aren’t well suited for detailed creative work. With this in mind, you might focus more on capturing content and tagging it with location data for a mobile UI, but focus on organizing or manipulating that content for a tablet or desktop UI. Another example is leveraging the web’s extremely low barrier for sharing. If you’re deploying a web app, decide which deep links to support, and design your navigation routes with those in mind. The key takeaway here is to think about what each platform does best and see if there are unique capabilities you can leverage. Use desktop build targets for rapid testing One of the most effective ways to test adaptive interfaces is to take advantage of the desktop build targets.
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-13
When running on a desktop, you can easily resize the window while the app is running to preview various screen sizes. This, combined with hot reload, can greatly accelerate the development of a responsive UI. Solve touch first Building a great touch UI can often be more difficult than a traditional desktop UI due, in part, to the lack of input accelerators like right-click, scroll wheel, or keyboard shortcuts. One way to approach this challenge is to focus initially on a great touch-oriented UI. You can still do most of your testing using the desktop target for its iteration speed. But, remember to switch frequently to a mobile device to verify that everything feels right. After you have the touch interface polished, you can tweak the visual density for mouse users, and then layer on all the additional inputs. Approach these other inputs as accelerator—alternatives that make a task faster. The important thing to consider is what a user expects when using a particular input device, and work to reflect that in your app.
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-14
Input Of course, it isn’t enough to just adapt how your app looks, you also have to support varying user inputs. The mouse and keyboard introduce input types beyond those found on a touch device—like scroll wheel, right-click, hover interactions, tab traversal, and keyboard shortcuts. Scroll wheel Scrolling widgets like ScrollView or ListView support the scroll wheel by default, and because almost every scrollable custom widget is built using one of these, it works with them as well. If you need to implement custom scroll behavior, you can use the Listener widget, which lets you customize how your UI reacts to the scroll wheel. Tab traversal and focus interactions Users with physical keyboards expect that they can use the tab key to quickly navigate your application, and users with motor or vision differences often rely completely on keyboard navigation.
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-15
There are two considerations for tab interactions: how focus moves from widget to widget, known as traversal, and the visual highlight shown when a widget is focused. Most built-in components, like buttons and text fields, support traversal and highlights by default. If you have your own widget that you want included in traversal, you can use the FocusableActionDetector widget to create your own controls. It combines the functionality of Actions, Shortcuts, MouseRegion, and Focus widgets to create a detector that defines actions and key bindings, and provides callbacks for handling focus and hover highlights. Controlling traversal order To get more control over the order that widgets are focused on when the user presses tab, you can use FocusTraversalGroup to define sections of the tree that should be treated as a group when tabbing. For example, you might to tab through all the fields in a form before tabbing to the submit button:
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-16
Flutter has several built-in ways to traverse widgets and groups, defaulting to the ReadingOrderTraversalPolicy class. This class usually works well, but it’s possible to modify this using another predefined TraversalPolicy class or by creating a custom policy. Keyboard accelerators In addition to tab traversal, desktop and web users are accustomed to having various keyboard shortcuts bound to specific actions. Whether it’s the Delete key for quick deletions or Control+N for a new document, be sure to consider the different accelerators your users expect. The keyboard is a powerful input tool, so try to squeeze as much efficiency from it as you can. Your users will appreciate it! Keyboard accelerators can be accomplished in a few ways in Flutter depending on your goals. If you have a single widget like a TextField or a Button that already has a focus node, you can wrap it in a RawKeyboardListener and listen for keyboard events:
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-17
If you’d like to apply a set of keyboard shortcuts to a large section of the tree, you can use the Shortcuts widget: The Shortcuts widget is useful because it only allows shortcuts to be fired when this widget tree or one of its children has focus and is visible. The final option is a global listener. This listener can be used for always-on, app-wide shortcuts or for panels that can accept shortcuts whenever they’re visible (regardless of their focus state). Adding global listeners is easy with RawKeyboard: To check key combinations with the global listener, you can use the RawKeyboard.instance.keysPressed map. For example, a method like the following can check whether any of the provided keys are being held down: Putting these two things together, you can fire an action when Shift+N is pressed:
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-18
One note of caution when using the static listener, is that you often need to disable it when the user is typing in a field or when the widget it’s associated with is hidden from view. Unlike with Shortcuts or RawKeyboardListener, this is your responsibility to manage. This can be especially important when you’re binding a Delete/Backspace accelerator for Delete, but then have child TextFields that the user might be typing in. Mouse enter, exit, and hover On desktop, it’s common to change the mouse cursor to indicate the functionality about the content the mouse is hovering over. For example, you usually see a hand cursor when you hover over a button, or an I cursor when you hover over text. The Material Component set has built-in support for your standard button and text cursors. To change the cursor from within your own widgets, use MouseRegion: MouseRegion is also useful for creating custom rollover and hover effects: Idioms and norms
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-19
Idioms and norms The final area to consider for adaptive apps is platform standards. Each platform has its own idioms and norms; these nominal or de facto standards inform user expectations of how an application should behave. Thanks, in part to the web, users are accustomed to more customized experiences, but reflecting these platform standards can still provide significant benefits: Reduce cognitive load—By matching the user’s existing mental model, accomplishing tasks becomes intuitive, which requires less thinking, boosts productivity, and reduces frustrations. Build trust—Users can become wary or suspicious when applications don’t adhere to their expectations. Conversely, a UI that feels familiar can build user trust and can help improve the perception of quality. This often has the added benefit of better app store ratings—something we can all appreciate! Consider expected behavior on each platform
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-20
Consider expected behavior on each platform The first step is to spend some time considering what the expected appearance, presentation, or behavior is on this platform. Try to forget any limitations of your current implementation, and just envision the ideal user experience. Work backwards from there. Another way to think about this is to ask, “How would a user of this platform expect to achieve this goal?” Then, try to envision how that would work in your app without any compromises. This can be difficult if you aren’t a regular user of the platform. You might be unaware of the specific idioms and can easily miss them completely. For example, a lifetime Android user will likely be unaware of platform conventions on iOS, and the same holds true for macOS, Linux, and Windows. These differences might be subtle to you, but be painfully obvious to an experienced user. Find a platform advocate
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-21
Find a platform advocate If possible, assign someone as an advocate for each platform. Ideally, your advocate uses the platform as their primary device, and can offer the perspective of a highly opinionated user. To reduce the number of people, combine roles. Have one advocate for Windows and Android, one for Linux and the web, and one for Mac and iOS. The goal is to have constant, informed feedback so the app feels great on each platform. Advocates should be encouraged to be quite picky, calling out anything they feel differs from typical applications on their device. A simple example is how the default button in a dialog is typically on the left on Mac and Linux, but is on the right on Windows. Details like that are easy to miss if you aren’t using a platform on a regular basis.
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-22
Important: Advocates don’t need to be developers or even full-time team members. They can be designers, stakeholders, or external testers that are provided with regular builds. Stay unique Conforming to expected behaviors doesn’t mean that your app needs to use default components or styling. Many of the most popular multiplatform apps have very distinct and opinionated UIs including custom buttons, context menus, and title bars. The more you can consolidate styling and behavior across platforms, the easier development and testing will be. The trick is to balance creating a unique experience with a strong identity, while respecting the norms of each platform. Common idioms and norms to consider Take a quick look at a few specific norms and idioms you might want to consider, and how you could approach them in Flutter. Scrollbar appearance and behavior
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-23
Scrollbar appearance and behavior Desktop and mobile users expect scrollbars, but they expect them to behave differently on different platforms. Mobile users expect smaller scrollbars that only appear while scrolling, whereas desktop users generally expect omnipresent, larger scrollbars that they can click or drag. Flutter comes with a built-in Scrollbar widget that already has support for adaptive colors and sizes according to the current platform. The one tweak you might want to make is to toggle alwaysShown when on a desktop platform: This subtle attention to detail can make your app feel more comfortable on a given platform. Multi-select Dealing with multi-select within a list is another area with subtle differences across platforms: To perform a platform-aware check for control or command, you can write something like this:
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-24
A final consideration for keyboard users is the Select All action. If you have a large list of items of selectable items, many of your keyboard users will expect that they can use Control+A to select all the items. Touch devices On touch devices, multi-selection is typically simplified, with the expected behavior being similar to having the isMultiSelectModifier down on the desktop. You can select or deselect items using a single tap, and will usually have a button to Select All or Clear the current selection. How you handle multi-selection on different devices depends on your specific use cases, but the important thing is to make sure that you’re offering each platform the best interaction model possible. Selectable text A common expectation on the web (and to a lesser extent desktop) is that most visible text can be selected with the mouse cursor. When text is not selectable, users on the web tend to have an adverse reaction.
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-25
Luckily, this is easy to support with the SelectableText widget: To support rich text, then use TextSpan: Title bars On modern desktop applications, it’s common to customize the title bar of your app window, adding a logo for stronger branding or contextual controls to help save vertical space in your main UI. This isn’t supported directly in Flutter, but you can use the bits_dojo package to disable the native title bars, and replace them with your own. This package lets you add whatever widgets you want to the TitleBar because it uses pure Flutter widgets under the hood. This makes it easy to adapt the title bar as you navigate to different sections of the app. Context menus and tooltips On desktop, there are several interactions that manifest as a widget shown in an overlay, but with differences in how they’re triggered, dismissed, and positioned:
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-26
Context menu—Typically triggered by a right-click, a context menu is positioned close to the mouse, and is dismissed by clicking anywhere, selecting an option from the menu, or clicking outside it. Tooltip—Typically triggered by hovering for 200-400ms over an interactive element, a tooltip is usually anchored to a widget (as opposed to the mouse position) and is dismissed when the mouse cursor leaves that widget. Popup panel (also known as flyout)—Similar to a tooltip, a popup panel is usually anchored to a widget. The main difference is that panels are most often shown on a tap event, and they usually don’t hide themselves when the cursor leaves. Instead, panels are typically dismissed by clicking outside the panel or by pressing a Close or Submit button. To show basic tooltips in Flutter, use the built-in Tooltip widget:
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-27
Flutter also provides built-in context menus when editing or selecting text. To show more advanced tooltips, popup panels, or create custom context menus, you either use one of the available packages, or build it yourself using a Stack or Overlay. Some available packages include: context_menus anchored_popups flutter_portal super_tooltip custom_pop_up_menu While these controls can be valuable for touch users as accelerators, they are essential for mouse users. These users expect to right-click things, edit content in place, and hover for more information. Failing to meet those expectations can lead to disappointed users, or at least, a feeling that something isn’t quite right. Horizontal button order
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-28
Horizontal button order On Windows, when presenting a row of buttons, the confirmation button is placed at the start of the row (left side). On all other platforms, it’s the opposite. The confirmation button is placed at the end of the row (right side). This can be easily handled in Flutter using the TextDirection property on Row: Menu bar Another common pattern on desktop apps is the menu bar. On Windows and Linux, this menu lives as part of the Chrome title bar, whereas on macOS, it’s located along the top of the primary screen. Currently, you can specify custom menu bar entries using a prototype plugin, but it’s expected that this functionality will eventually be integrated into the main SDK.
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-29
It’s worth mentioning that on Windows and Linux, you can’t combine a custom title bar with a menu bar. When you create a custom title bar, you’re replacing the native one completely, which means you also lose the integrated native menu bar. If you need both a custom title bar and a menu bar, you can achieve that by implementing it in Flutter, similar to a custom context menu. Drag and drop One of the core interactions for both touch-based and pointer-based inputs is drag and drop. Although this interaction is expected for both types of input, there are important differences to think about when it comes to scrolling lists of draggable items. Generally speaking, touch users expect to see drag handles to differentiate draggable areas from scrollable ones, or alternatively, to initiate a drag by using a long press gesture. This is because scrolling and dragging are both sharing a single finger for input.
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-30
Mouse users have more input options. They can use a wheel or scrollbar to scroll, which generally eliminates the need for dedicated drag handles. If you look at the macOS Finder or Windows Explorer, you’ll see that they work this way: you just select an item and start dragging. In Flutter, you can implement drag and drop in many ways. Discussing specific implementations is outside the scope of this article, but some high level options are: Use the Draggable and DragTarget APIs directly for a custom look and feel. Hook into onPan gesture events, and move an object yourself within a parent Stack. Use one of the pre-made list packages on pub.dev. Educate yourself on basic usability principles Of course, this page doesn’t constitute an exhaustive list of the things you might consider. The more operating systems, form factors, and input devices you support, the more difficult it becomes to spec out every permutation in design.
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
8b28ba4cbacb-31
Taking time to learn basic usability principles as a developer empowers you to make better decisions, reduces back-and-forth iterations with design during production, and results in improved productivity with better outcomes. Here are some resources to get you started: Material guidelines on responsive UI layout Material design for large screens Build high quality apps (Android) UI design do’s and don’ts (Apple) Human interface guidelines (Apple) Responsive design techniques (Microsoft) Machine sizes and breakpoints (Microsoft)
https://docs.flutter.dev/development/ui/layout/building-adaptive-apps/index.html
258879a6e4b2-0
Understanding constraints UI Layout Understanding constraints Note: To better understand how Flutter implements layout constraints, check out the following 5-minute video: Decoding Flutter: Unbounded height and width When someone learning Flutter asks you why some widget with width:100 isn’t 100 pixels wide, the default answer is to tell them to put that widget inside of a Center, right? Don’t do that. If you do, they’ll come back again and again, asking why some FittedBox isn’t working, why that Column is overflowing, or what IntrinsicWidth is supposed to be doing. Instead, first tell them that Flutter layout is very different from HTML layout (which is probably where they’re coming from), and then make them memorize the following rule: Constraints go down. Sizes go up. Parent sets position.
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-1
Constraints go down. Sizes go up. Parent sets position. Flutter layout can’t really be understood without knowing this rule, so Flutter developers should learn it early on. In more detail: A widget gets its own constraints from its parent. A constraint is just a set of 4 doubles: a minimum and maximum width, and a minimum and maximum height. Then the widget goes through its own list of children. One by one, the widget tells its children what their constraints are (which can be different for each child), and then asks each child what size it wants to be. Then, the widget positions its children (horizontally in the x axis, and vertically in the y axis), one by one. And, finally, the widget tells its parent about its own size (within the original constraints, of course). For example, if a composed widget contains a column with some padding, and wants to lay out its two children as follows:
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-2
The negotiation goes something like this: Widget: “Hey parent, what are my constraints?” Parent: “You must be from 80 to 300 pixels wide, and 30 to 85 tall.” Widget: “Hmmm, since I want to have 5 pixels of padding, then my children can have at most 290 pixels of width and 75 pixels of height.” Widget: “Hey first child, You must be from 0 to 290 pixels wide, and 0 to 75 tall.” First child: “OK, then I wish to be 290 pixels wide, and 20 pixels tall.” Widget: “Hmmm, since I want to put my second child below the first one, this leaves only 55 pixels of height for my second child.”
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-3
Widget: “Hey second child, You must be from 0 to 290 wide, and 0 to 55 tall.” Second child: “OK, I wish to be 140 pixels wide, and 30 pixels tall.” Widget: “Very well. My first child has position x: 5 and y: 5, and my second child has x: 80 and y: 25.” Widget: “Hey parent, I’ve decided that my size is going to be 300 pixels wide, and 60 pixels tall.” Limitations As a result of the layout rule mentioned above, Flutter’s layout engine has a few important limitations: A widget can decide its own size only within the constraints given to it by its parent. This means a widget usually can’t have any size it wants.
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-4
A widget can’t know and doesn’t decide its own position in the screen, since it’s the widget’s parent who decides the position of the widget. Since the parent’s size and position, in its turn, also depends on its own parent, it’s impossible to precisely define the size and position of any widget without taking into consideration the tree as a whole. If a child wants a different size from its parent and the parent doesn’t have enough information to align it, then the child’s size might be ignored. Be specific when defining alignment. Examples For an interactive experience, use the following DartPad. Use the numbered horizontal scrolling bar to switch between 29 different examples. If you prefer, you can grab the code from this GitHub repo. The examples are explained in the following sections. Example 1
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-5
The examples are explained in the following sections. Example 1 The screen is the parent of the Container, and it forces the Container to be exactly the same size as the screen. So the Container fills the screen and paints it red. Example 2 The red Container wants to be 100 × 100, but it can’t, because the screen forces it to be exactly the same size as the screen. So the Container fills the screen. Example 3 The screen forces the Center to be exactly the same size as the screen, so the Center fills the screen. The Center tells the Container that it can be any size it wants, but not bigger than the screen. Now the Container can indeed be 100 × 100. Example 4 This is different from the previous example in that it uses Align instead of Center.
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-6
This is different from the previous example in that it uses Align instead of Center. Align also tells the Container that it can be any size it wants, but if there is empty space it won’t center the Container. Instead, it aligns the container to the bottom-right of the available space. Example 5 The screen forces the Center to be exactly the same size as the screen, so the Center fills the screen. The Center tells the Container that it can be any size it wants, but not bigger than the screen. The Container wants to be of infinite size, but since it can’t be bigger than the screen, it just fills the screen. Example 6 The screen forces the Center to be exactly the same size as the screen, so the Center fills the screen.
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-7
The Center tells the Container that it can be any size it wants, but not bigger than the screen. Since the Container has no child and no fixed size, it decides it wants to be as big as possible, so it fills the whole screen. But why does the Container decide that? Simply because that’s a design decision by those who created the Container widget. It could have been created differently, and you have to read the Container documentation to understand how it behaves, depending on the circumstances. Example 7 The screen forces the Center to be exactly the same size as the screen, so the Center fills the screen. The Center tells the red Container that it can be any size it wants, but not bigger than the screen. Since the red Container has no size but has a child, it decides it wants to be the same size as its child. The red Container tells its child that it can be any size it wants, but not bigger than the screen.
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-8
The child is a green Container that wants to be 30 × 30. Given that the red Container sizes itself to the size of its child, it is also 30 × 30. The red color isn’t visible because the green Container entirely covers the red Container. Example 8 The red Container sizes itself to its children’s size, but it takes its own padding into consideration. So it is also 30 × 30 plus padding. The red color is visible because of the padding, and the green Container has the same size as in the previous example. Example 9 You might guess that the Container has to be between 70 and 150 pixels, but you would be wrong. The ConstrainedBox only imposes additional constraints from those it receives from its parent.
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-9
Here, the screen forces the ConstrainedBox to be exactly the same size as the screen, so it tells its child Container to also assume the size of the screen, thus ignoring its constraints parameter. Example 10 Now, Center allows ConstrainedBox to be any size up to the screen size. The ConstrainedBox imposes additional constraints from its constraints parameter onto its child. The Container must be between 70 and 150 pixels. It wants to have 10 pixels, so it ends up having 70 (the minimum). Example 11 Center allows ConstrainedBox to be any size up to the screen size. The ConstrainedBox imposes additional constraints from its constraints parameter onto its child. The Container must be between 70 and 150 pixels. It wants to have 1000 pixels, so it ends up having 150 (the maximum). Example 12
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-10
Example 12 Center allows ConstrainedBox to be any size up to the screen size. The ConstrainedBox imposes additional constraints from its constraints parameter onto its child. The Container must be between 70 and 150 pixels. It wants to have 100 pixels, and that’s the size it has, since that’s between 70 and 150. Example 13 The screen forces the UnconstrainedBox to be exactly the same size as the screen. However, the UnconstrainedBox lets its child Container be any size it wants. Example 14 The screen forces the UnconstrainedBox to be exactly the same size as the screen, and UnconstrainedBox lets its child Container be any size it wants.
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-11
Unfortunately, in this case the Container is 4000 pixels wide and is too big to fit in the UnconstrainedBox, so the UnconstrainedBox displays the much dreaded “overflow warning”. Example 15 The screen forces the OverflowBox to be exactly the same size as the screen, and OverflowBox lets its child Container be any size it wants. OverflowBox is similar to UnconstrainedBox; the difference is that it won’t display any warnings if the child doesn’t fit the space. In this case, the Container has 4000 pixels of width, and is too big to fit in the OverflowBox, but the OverflowBox simply shows as much as it can, with no warnings given. Example 16 This won’t render anything, and you’ll see an error in the console. The UnconstrainedBox lets its child be any size it wants, however its child is a Container with infinite size.
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-12
Flutter can’t render infinite sizes, so it throws an error with the following message: BoxConstraints forces an infinite width. Example 17 Here you won’t get an error anymore, because when the LimitedBox is given an infinite size by the UnconstrainedBox; it passes a maximum width of 100 down to its child. If you swap the UnconstrainedBox for a Center widget, the LimitedBox won’t apply its limit anymore (since its limit is only applied when it gets infinite constraints), and the width of the Container is allowed to grow past 100. This explains the difference between a LimitedBox and a ConstrainedBox. Example 18 The screen forces the FittedBox to be exactly the same size as the screen. The Text has some natural width (also called its intrinsic width) that depends on the amount of text, its font size, and so on.
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-13
The FittedBox lets the Text be any size it wants, but after the Text tells its size to the FittedBox, the FittedBox scales the Text until it fills all of the available width. Example 19 But what happens if you put the FittedBox inside of a Center widget? The Center lets the FittedBox be any size it wants, up to the screen size. The FittedBox then sizes itself to the Text, and lets the Text be any size it wants. Since both FittedBox and the Text have the same size, no scaling happens. Example 20 However, what happens if FittedBox is inside of a Center widget, but the Text is too large to fit the screen? FittedBox tries to size itself to the Text, but it can’t be bigger than the screen. It then assumes the screen size, and resizes Text so that it fits the screen, too. Example 21
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-14
Example 21 If, however, you remove the FittedBox, the Text gets its maximum width from the screen, and breaks the line so that it fits the screen. Example 22 FittedBox can only scale a widget that is bounded (has non-infinite width and height). Otherwise, it won’t render anything, and you’ll see an error in the console. Example 23 The screen forces the Row to be exactly the same size as the screen. Just like an UnconstrainedBox, the Row won’t impose any constraints onto its children, and instead lets them be any size they want. The Row then puts them side-by-side, and any extra space remains empty. Example 24
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-15
Example 24 Since Row won’t impose any constraints onto its children, it’s quite possible that the children might be too big to fit the available width of the Row. In this case, just like an UnconstrainedBox, the Row displays the “overflow warning”. Example 25 When a Row’s child is wrapped in an Expanded widget, the Row won’t let this child define its own width anymore. Instead, it defines the Expanded width according to the other children, and only then the Expanded widget forces the original child to have the Expanded’s width. In other words, once you use Expanded, the original child’s width becomes irrelevant, and is ignored. Example 26
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-16
Example 26 If all of Row’s children are wrapped in Expanded widgets, each Expanded has a size proportional to its flex parameter, and only then each Expanded widget forces its child to have the Expanded’s width. In other words, Expanded ignores the preferred width of its children. Example 27 Example 28 The screen forces the Scaffold to be exactly the same size as the screen, so the Scaffold fills the screen. The Scaffold tells the Container that it can be any size it wants, but not bigger than the screen. Note: When a widget tells its child that it can be smaller than a certain size, we say the widget supplies loose constraints to its child. More on that later. Example 29
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-17
Example 29 If you want the Scaffold’s child to be exactly the same size as the Scaffold itself, you can wrap its child with SizedBox.expand. Note: When a widget tells its child that it must be of a certain size, we say the widget supplies tight constraints to its child. Tight vs. loose constraints It’s very common to hear that some constraint is “tight” or “loose”, so it’s worth knowing what that means. A tight constraint offers a single possibility, an exact size. In other words, a tight constraint has its maximum width equal to its minimum width; and has its maximum height equal to its minimum height. If you go to Flutter’s box.dart file and search for the BoxConstraints constructors, you’ll find the following: BoxConstraints tight Size size
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-18
tight Size size minWidth size width maxWidth size width minHeight size height maxHeight size height If you revisit Example 2 above, it tells us that the screen forces the red Container to be exactly the same size as the screen. The screen does that, of course, by passing tight constraints to the Container. A loose constraint, on the other hand, sets the maximum width and height, but lets the widget be as small as it wants. In other words, a loose constraint has a minimum width and height both equal to zero: BoxConstraints loose Size size minWidth 0.0 maxWidth
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-19
minWidth 0.0 maxWidth size width minHeight 0.0 maxHeight size height Example 3, it tells us that the Learning the layout rules for specific widgets Knowing the general layout rule is necessary, but it’s not enough. Each widget has a lot of freedom when applying the general rule, so there is no way of knowing what it will do by just reading the widget’s name. If you try to guess, you’ll probably guess wrong. You can’t know exactly how a widget behaves unless you’ve read its documentation, or studied its source-code.
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-20
The layout source-code is usually complex, so it’s probably better to just read the documentation. However, if you decide to study the layout source-code, you can easily find it by using the navigating capabilities of your IDE. Here is an example: Find a Column in your code and navigate to its source code. To do this, use command+B (macOS) or control+B (Windows/Linux) in Android Studio or IntelliJ. You’ll be taken to the basic.dart file. Since Column extends Flex, navigate to the Flex source code (also in basic.dart). Scroll down until you find a method called createRenderObject(). As you can see, this method returns a RenderFlex. This is the render-object for the Column. Now navigate to the source-code of RenderFlex, which takes you to the flex.dart file. Scroll down until you find a method called performLayout(). This is the method that does the layout for the Column.
https://docs.flutter.dev/development/ui/layout/constraints/index.html
258879a6e4b2-21
Article by Marcelo Glasberg Marcelo originally published this content as Flutter: The Advanced Layout Rule Even Beginners Must Know on Medium. We loved it and asked that he allow us to publish in on docs.flutter.dev, to which he graciously agreed. Thanks, Marcelo! You can find Marcelo on GitHub and pub.dev. Also, thanks to Simon Lightfoot for creating the header image at the top of the article.
https://docs.flutter.dev/development/ui/layout/constraints/index.html
902b1ec1e7c0-0
Layouts in Flutter UI Layout Lay out a widget 1. Select a layout widget 2. Create a visible widget 3. Add the visible widget to the layout widget 4. Add the layout widget to the page Material apps Non-Material apps Lay out multiple widgets vertically and horizontally Aligning widgets Sizing widgets Packing widgets Nesting rows and columns Common layout widgets Standard widgets Material widgets Container GridView ListView Stack Card ListTile Constraints Videos Other resources What's the point? Widgets are classes used to build UIs. Widgets are used for both layout and UI elements. Compose simple widgets to build complex widgets.
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-1
Compose simple widgets to build complex widgets. The core of Flutter’s layout mechanism is widgets. In Flutter, almost everything is a widget—even layout models are widgets. The images, icons, and text that you see in a Flutter app are all widgets. But things you don’t see are also widgets, such as the rows, columns, and grids that arrange, constrain, and align the visible widgets. You create a layout by composing widgets to build more complex widgets. For example, the first screenshot below shows 3 icons with a label under each one: The second screenshot displays the visual layout, showing a row of 3 columns where each column contains an icon and a label. Note: Most of the screenshots in this tutorial are displayed with debugPaintSizeEnabled set to true so you can see the visual layout. For more information, see Debugging layout issues visually, a section in Using the Flutter inspector.
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-2
Here’s a diagram of the widget tree for this UI: Most of this should look as you might expect, but you might be wondering about the containers (shown in pink). Container is a widget class that allows you to customize its child widget. Use a Container when you want to add padding, margins, borders, or background color, to name some of its capabilities. In this example, each Text widget is placed in a Container to add margins. The entire Row is also placed in a Container to add padding around the row. The rest of the UI in this example is controlled by properties. Set an Icon’s color using its color property. Use the Text.style property to set the font, its color, weight, and so on. Columns and rows have properties that allow you to specify how their children are aligned vertically or horizontally, and how much space the children should occupy. Lay out a widget
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-3
Lay out a widget How do you lay out a single widget in Flutter? This section shows you how to create and display a simple widget. It also shows the entire code for a simple Hello World app. In Flutter, it takes only a few steps to put text, an icon, or an image on the screen. 1. Select a layout widget Choose from a variety of layout widgets based on how you want to align or constrain the visible widget, as these characteristics are typically passed on to the contained widget. This example uses Center which centers its content horizontally and vertically. 2. Create a visible widget For example, create a Text widget: Create an Image widget: Create an Icon widget: 3. Add the visible widget to the layout widget All layout widgets have either of the following:
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-4
All layout widgets have either of the following: A child property if they take a single child—for example, Center or Container A children property if they take a list of widgets—for example, Row, Column, ListView, or Stack. Add the Text widget to the Center widget: 4. Add the layout widget to the page A Flutter app is itself a widget, and most widgets have a build() method. Instantiating and returning a widget in the app’s build() method displays the widget. Material apps For a Material app, you can use a Scaffold widget; it provides a default banner, background color, and has API for adding drawers, snack bars, and bottom sheets. Then you can add the Center widget directly to the body property for the home page. lib/main.dart (MyApp)
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-5
lib/main.dart (MyApp) Note: The Material library implements widgets that follow Material Design principles. When designing your UI, you can exclusively use widgets from the standard widgets library, or you can use widgets from the Material library. You can mix widgets from both libraries, you can customize existing widgets, or you can build your own set of custom widgets. Non-Material apps For a non-Material app, you can add the Center widget to the app’s build() method: lib/main.dart (MyApp) By default a non-Material app doesn’t include an AppBar, title, or background color. If you want these features in a non-Material app, you have to build them yourself. This app changes the background color to white and the text to dark grey to mimic a Material app. That’s it! When you run the app, you should see Hello World.
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-6
That’s it! When you run the app, you should see Hello World. App source code: Material app Non-Material app Lay out multiple widgets vertically and horizontally One of the most common layout patterns is to arrange widgets vertically or horizontally. You can use a Row widget to arrange widgets horizontally, and a Column widget to arrange widgets vertically. What's the point? Row and Column are two of the most commonly used layout patterns. Row and Column each take a list of child widgets. A child widget can itself be a Row, Column, or other complex widget. You can specify how a Row or Column aligns its children, both vertically and horizontally. You can stretch or constrain specific child widgets.
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-7
You can stretch or constrain specific child widgets. You can specify how child widgets use the Row’s or Column’s available space. To create a row or column in Flutter, you add a list of children widgets to a Row or Column widget. In turn, each child can itself be a row or column, and so on. The following example shows how it is possible to nest rows or columns inside of rows or columns. This layout is organized as a Row. The row contains two children: a column on the left, and an image on the right: The left column’s widget tree nests rows and columns. You’ll implement some of Pavlova’s layout code in Nesting rows and columns. ListTile, an easy-to-use widget with properties for leading and trailing icons, and up to 3 lines of text. Instead of Column, you might prefer
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-8
ListView, a column-like layout that automatically scrolls if its content is too long to fit the available space. For more information, see Common layout widgets. Aligning widgets You control how a row or column aligns its children using the mainAxisAlignment and crossAxisAlignment properties. For a row, the main axis runs horizontally and the cross axis runs vertically. For a column, the main axis runs vertically and the cross axis runs horizontally. The MainAxisAlignment and CrossAxisAlignment enums offer a variety of constants for controlling alignment. pubspec.yaml file or Adding assets and images. You don’t need to do this if you’re referencing online images using
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-9
In the following example, each of the 3 images is 100 pixels wide. The render box (in this case, the entire screen) is more than 300 pixels wide, so setting the main axis alignment to spaceEvenly divides the free horizontal space evenly between, before, and after each image. Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Image.asset('images/pic1.jpg'), Image.asset('images/pic2.jpg'), Image.asset('images/pic3.jpg'), ], ); App source: row_column Columns work the same way as rows. The following example shows a column of 3 images, each is 100 pixels high. The height of the render box (in this case, the entire screen) is more than 300 pixels, so setting the main axis alignment to spaceEvenly divides the free vertical space evenly between, above, and below each image.
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-10
Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Image.asset('images/pic1.jpg'), Image.asset('images/pic2.jpg'), Image.asset('images/pic3.jpg'), ], ); App source: row_column Sizing widgets When a layout is too large to fit a device, a yellow and black striped pattern appears along the affected edge. Here is an example of a row that is too wide: Widgets can be sized to fit within a row or column by using the Expanded widget. To fix the previous example where the row of images is too wide for its render box, wrap each image with an Expanded widget. Expanded( child: Image.asset('images/pic1.jpg'), ), Expanded( child: Image.asset('images/pic2.jpg'), ),
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-11
Expanded( child: Image.asset('images/pic3.jpg'), ), ], ); App source: sizing Perhaps you want a widget to occupy twice as much space as its siblings. For this, use the Expanded widget flex property, an integer that determines the flex factor for a widget. The default flex factor is 1. The following code sets the flex factor of the middle image to 2: flex: 2, child: Image.asset('images/pic2.jpg'), ), Expanded( child: Image.asset('images/pic3.jpg'), ), ], ); App source: sizing Packing widgets
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-12
App source: sizing Packing widgets By default, a row or column occupies as much space along its main axis as possible, but if you want to pack the children closely together, set its mainAxisSize to MainAxisSize.min. The following example uses this property to pack the star icons together. mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.star, color: Colors.green[500]), Icon(Icons.star, color: Colors.green[500]), Icon(Icons.star, color: Colors.green[500]), const Icon(Icons.star, color: Colors.black), const Icon(Icons.star, color: Colors.black), ], ) App source: pavlova Nesting rows and columns
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-13
App source: pavlova Nesting rows and columns The layout framework allows you to nest rows and columns inside of rows and columns as deeply as you need. Let’s look at the code for the outlined section of the following layout: The outlined section is implemented as two rows. The ratings row contains five stars and the number of reviews. The icons row contains three columns of icons and text. The widget tree for the ratings row: The ratings variable creates a row containing a smaller row of 5 star icons, and text:
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-14
ratings = Container( padding: const EdgeInsets.all(20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ stars, const Text( '170 Reviews', style: TextStyle( color: Colors.black, fontWeight: FontWeight.w800, fontFamily: 'Roboto', letterSpacing: 0.5, fontSize: 20, ), ), ], ), ); Tip: To minimize the visual confusion that can result from heavily nested layout code, implement pieces of the UI in variables and functions. The icons row, below the ratings row, contains 3 columns; each column contains an icon and two lines of text, as you can see in its widget tree: The iconList variable defines the icons row:
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-15
The iconList variable defines the icons row: iconList = DefaultTextStyle.merge( style: descTextStyle, child: Container( padding: const EdgeInsets.all(20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Column( children: [ Icon(Icons.kitchen, color: Colors.green[500]), const Text('PREP:'), const Text('25 min'), ], ), Column( children: [ Icon(Icons.timer, color: Colors.green[500]), const Text('COOK:'), const Text('1 hr'), ], ), Column( children: [ Icon(Icons.restaurant, color: Colors.green[500]), const Text('FEEDS:'), const Text('4-6'), ], ), ], ), ), );
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-16
The leftColumn variable contains the ratings and icons rows, as well as the title and text that describes the Pavlova: leftColumn = Container( padding: const EdgeInsets.fromLTRB(20, 30, 20, 20), child: Column( children: [ titleText, subTitle, ratings, iconList, ], ), ); The left column is placed in a SizedBox to constrain its width. Finally, the UI is constructed with the entire row (containing the left column and the image) inside a Card. Pavlova image is from Pixabay. You can embed an image from the net using pubspec file, and accessed using Adding assets and images.
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-17
pubspec file, and accessed using Adding assets and images. Tip: The Pavlova example runs best horizontally on a wide device, such as a tablet. If you are running this example in the iOS simulator, you can select a different device using the Hardware > Device menu. For this example, we recommend the iPad Pro. You can change its orientation to landscape mode using Hardware > Rotate. You can also change the size of the simulator window (without changing the number of logical pixels) using Window > Scale. App source: pavlova Common layout widgets
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-18
App source: pavlova Common layout widgets Flutter has a rich library of layout widgets. Here are a few of those most commonly used. The intent is to get you up and running as quickly as possible, rather than overwhelm you with a complete list. For information on other available widgets, refer to the Widget catalog, or use the Search box in the API reference docs. Also, the widget pages in the API docs often make suggestions about similar widgets that might better suit your needs. The following widgets fall into two categories: standard widgets from the widgets library, and specialized widgets from the Material library. Any app can use the widgets library but only Material apps can use the Material Components library. Standard widgets Container: Adds padding, margins, borders, background color, or other decorations to a widget. GridView: Lays widgets out as a scrollable grid.
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-19
GridView: Lays widgets out as a scrollable grid. ListView: Lays widgets out as a scrollable list. Stack: Overlaps a widget on top of another. Material widgets Card: Organizes related info into a box with rounded corners and a drop shadow. ListTile: Organizes up to 3 lines of text, and optional leading and trailing icons, into a row. Container Many layouts make liberal use of Containers to separate widgets using padding, or to add borders or margins. You can change the device’s background by placing the entire layout into a Container and changing its background color or image. Summary (Container) Add padding, margins, borders Change background color or image Contains a single child widget, but that child can be a Row, Column, or even the root of a widget tree Examples (Container)
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-20
Examples (Container) This layout consists of a column with two rows, each containing 2 images. A Container is used to change the background color of the column to a lighter grey. Container( decoration: const BoxDecoration( color: Colors.black26, ), child: Column( children: [ _buildImageRow(1), _buildImageRow(3), ], ), ); } A Container is also used to add a rounded border and margins to each image: Container( decoration: BoxDecoration( border: Border.all(width: 10, color: Colors.black38), borderRadius: const BorderRadius.all(Radius.circular(8)), ), margin: const EdgeInsets.all(4), child: Image.asset('images/pic$imageIndex.jpg'), ), );
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-21
Widget _buildImageRow(int imageIndex) => Row( children: [ _buildDecoratedImage(imageIndex), _buildDecoratedImage(imageIndex + 1), ], ); You can find more Container examples in the tutorial and the Flutter Gallery (running app, repo). App source: container GridView Use GridView to lay widgets out as a two-dimensional list. GridView provides two pre-fabricated lists, or you can build your own custom grid. When a GridView detects that its contents are too long to fit the render box, it automatically scrolls. Summary (GridView) Lays widgets out in a grid Detects when the column content exceeds the render box and automatically provides scrolling
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-22
Detects when the column content exceeds the render box and automatically provides scrolling Build your own custom grid, or use one of the provided grids: GridView.count allows you to specify the number of columns GridView.extent allows you to specify the maximum pixel width of a tile Note: When displaying a two-dimensional list where it’s important which row and column a cell occupies (for example, it’s the entry in the “calorie” column for the “avocado” row), use Table or DataTable. Examples (GridView) Uses GridView.extent to create a grid with tiles a maximum 150 pixels wide. App source: grid_and_list Uses GridView.count to create a grid that’s 2 tiles wide in portrait mode, and 3 tiles wide in landscape mode. The titles are created by setting the footer property for each GridTile.
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-23
Dart code: grid_list_demo.dart from the Flutter Gallery GridView.extent( maxCrossAxisExtent: 150, padding: const EdgeInsets.all(4), mainAxisSpacing: 4, crossAxisSpacing: 4, children: _buildGridTileList(30)); // The images are saved with names pic0.jpg, pic1.jpg...pic29.jpg. // The List.generate() constructor allows an easy way to create // a list when objects have a predictable naming pattern. List<Container> _buildGridTileList(int count) => List.generate( count, (i) => Container(child: Image.asset('images/pic$i.jpg'))); ListView ListView, a column-like widget, automatically provides scrolling when its content is too long for its render box. Summary (ListView)
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-24
Summary (ListView) A specialized Column for organizing a list of boxes Can be laid out horizontally or vertically Detects when its content won’t fit and provides scrolling Less configurable than Column, but easier to use and supports scrolling Examples (ListView) Uses ListView to display a list of businesses using ListTiles. A Divider separates the theaters from the restaurants. App source: grid_and_list Uses ListView to display the Colors from the Material Design palette for a particular color family. Dart code: colors_demo.dart from the Flutter Gallery
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-25
ListView( children: [ _tile('CineArts at the Empire', '85 W Portal Ave', Icons.theaters), _tile('The Castro Theater', '429 Castro St', Icons.theaters), _tile('Alamo Drafthouse Cinema', '2550 Mission St', Icons.theaters), _tile('Roxie Theater', '3117 16th St', Icons.theaters), _tile('United Artists Stonestown Twin', '501 Buckingham Way', Icons.theaters), _tile('AMC Metreon 16', '135 4th St #3000', Icons.theaters), const Divider(), _tile('K\'s Kitchen', '757 Monterey Blvd', Icons.restaurant),
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-26
_tile('Emmy\'s Restaurant', '1923 Ocean Ave', Icons.restaurant), _tile( 'Chaiya Thai Restaurant', '272 Claremont Blvd', Icons.restaurant), _tile('La Ciccia', '291 30th St', Icons.restaurant), ], ); }
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-27
ListTile _tile(String title, String subtitle, IconData icon) { return ListTile( title: Text(title, style: const TextStyle( fontWeight: FontWeight.w500, fontSize: 20, )), subtitle: Text(subtitle), leading: Icon( icon, color: Colors.blue[500], ), ); } Stack Use Stack to arrange widgets on top of a base widget—often an image. The widgets can completely or partially overlap the base widget. Summary (Stack) Use for widgets that overlap another widget The first widget in the list of children is the base widget; subsequent children are overlaid on top of that base widget A Stack’s content can’t scroll You can choose to clip children that exceed the render box Examples (Stack)
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-28
Examples (Stack) App source: card_and_stack Uses Stack to overlay an icon on top of an image. Dart code: bottom_navigation_demo.dart from the Flutter Gallery Stack( alignment: const Alignment(0.6, 0.6), children: [ const CircleAvatar( backgroundImage: AssetImage('images/pic.jpg'), radius: 100, ), Container( decoration: const BoxDecoration( color: Colors.black45, ), child: const Text( 'Mia B', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ], ); } Card Card, from the
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-29
Card Card, from the Material library, contains related nuggets of information and can be composed from almost any widget, but is often used with ListTile. SizedBox to constrain the size of a card. Elevation in the Material guidelines. Specifying an unsupported value disables the drop shadow entirely. Summary (Card) Implements a Material card Used for presenting related nuggets of information Accepts a single child, but that child can be a Row, Column, or other widget that holds a list of children Displayed with rounded corners and a drop shadow A Card’s content can’t scroll From the Material library Examples (Card)
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-30
From the Material library Examples (Card) A Card containing 3 ListTiles and sized by wrapping it with a SizedBox. A Divider separates the first and second ListTiles. App source: card_and_stack A Card containing an image and text. Dart code: cards_demo.dart from the Flutter Gallery
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-31
Card( child: Column( children: [ ListTile( title: const Text( '1625 Main Street', style: TextStyle(fontWeight: FontWeight.w500), ), subtitle: const Text('My City, CA 99984'), leading: Icon( Icons.restaurant_menu, color: Colors.blue[500], ), ), const Divider(), ListTile( title: const Text( '(408) 555-1212', style: TextStyle(fontWeight: FontWeight.w500), ), leading: Icon( Icons.contact_phone,
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-32
leading: Icon( Icons.contact_phone, color: Colors.blue[500], ), ), ListTile( title: const Text('[email protected]'), leading: Icon( Icons.contact_mail, color: Colors.blue[500], ), ), ], ), ), ); }
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-33
ListTile Use ListTile, a specialized row widget from the Material library, for an easy way to create a row containing up to 3 lines of text and optional leading and trailing icons. ListTile is most commonly used in Card or ListView, but can be used elsewhere. Summary (ListTile) A specialized row that contains up to 3 lines of text and optional icons Less configurable than Row, but easier to use From the Material library Examples (ListTile) A Card containing 3 ListTiles. App source: card_and_stack Uses ListTile with leading widgets. Dart code: list_demo.dart from the Flutter Gallery Constraints
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-34
Constraints To fully understand Flutter’s layout system, you need to learn how Flutter positions and sizes the components in a layout. For more information, see Understanding constraints. Videos The following videos, part of the Flutter in Focus series, explain Stateless and Stateful widgets. Flutter in Focus playlist Each episode of the Widget of the Week series focuses on a widget. Several of them includes layout widgets. Flutter Widget of the Week playlist Other resources The following resources might help when writing layout code. Layout tutorial Learn how to build a layout. Widget catalog Describes many of the widgets available in Flutter. HTML/CSS Analogs in Flutter For those familiar with web programming, this page maps HTML/CSS functionality to Flutter features. Flutter Gallery running app, repo
https://docs.flutter.dev/development/ui/layout/index.html
902b1ec1e7c0-35
Flutter Gallery running app, repo Demo app showcasing many Material Design widgets and other Flutter features. API reference docs Reference documentation for all of the Flutter libraries. Dealing with Box Constraints in Flutter Discusses how widgets are constrained by their render boxes. Adding assets and images Explains how to add images and other assets to your app’s package. Zero to One with Flutter One person’s experience writing his first Flutter app.
https://docs.flutter.dev/development/ui/layout/index.html
6367d524307d-0
Building layouts UI Layout Tutorial Step 0: Create the app base code Step 1: Diagram the layout Step 2: Implement the title row Step 3: Implement the button row Step 4: Implement the text section Step 5: Implement the image section Step 6: Final touch What you’ll learn How Flutter’s layout mechanism works. How to lay out widgets vertically and horizontally. How to build a Flutter layout. This is a guide to building layouts in Flutter. You’ll build the layout for the following app:
https://docs.flutter.dev/development/ui/layout/tutorial/index.html
6367d524307d-1
This guide then takes a step back to explain Flutter’s approach to layout, and shows how to place a single widget on the screen. After a discussion of how to lay widgets out horizontally and vertically, some of the most common layout widgets are covered. If you want a “big picture” understanding of the layout mechanism, start with Flutter’s approach to layout. Step 0: Create the app base code Make sure to set up your environment, then do the following: Create a new Flutter app. Replace the contents in lib/main.dart with the following code: lib/main.dart (all) import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key});
https://docs.flutter.dev/development/ui/layout/tutorial/index.html