Quickly create beautiful apps with Flutter’s set of visual, structural, platform, and interactive widgets.
Based on the component
Before building a Flutter application, absolutely understand the Widgets. Here is a list of UI controls that are similar to the ones available on iOS.
Container
Container Class is a convenient widget that combines common drawing, positioning, and size widgets.
Do you have widgets that require some background styles? Maybe a background color or shape? Or some size restriction? Try wrapping it in the Container Widget. Container Widgets help you compose, decorate, and position child widgets. If the widget is wrapped in a Container widget without any additional parameters, you won’t notice any difference in appearance. However, if you add the Color parameter, your child window widget will get the background Color. There is nothing else, and the Container resizes itself based on its child widgets. Use the padding property of the Container to add white space between the child widget and the Container boundary, and use the Margin property to add white space around the widget. You can use the Decoration property to add a shape, such as a circle, to the Container. By default, the size of decoration is based on the children of the Container. In this case, the Container aligns with the height of the text widget, the narrowest parameter for the circular decoration. You can use padding and margin as before to design decorations. Using the Alignment attribute, you can align child widgets in a Container. Once the alignment is set, the Container expands to fill in the width and height of its parent. You can do this by setting the width and height properties of the Container. Or use a box layout model to override this setting. For example, with BoxConstraints, your Container can be expanded to fill a given size. You can even apply transform to containers.
Container(
child: Text('Less boring'),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.blue,
),
margin: EdgeInsets.all(25.0),
padding: EdgeInsets.all(40.0),
alignment: Alignment.center,
width: 200,
height: 100,
constraints: BoxConstraints.tightForFinite(
width: 200,
),
transform: Matrix4.rotationZ(0.05));Copy the code
Row
Row class displays the widgets of its child items in a horizontal array (a horizontal list of child widgets). To expand the child to fill the available horizontal space, wrap the child in Expanded Widget. Row widgets do not scroll (generally, it is considered an error if there are more children in the Row than there is in the available room). If you have Row widgets and want them to scroll when space is low, consider using ListView.
Row(
children: const <Widget>[
Expanded(
child: Text('Deliver features faster', textAlign: TextAlign.center),
),
Expanded(
child: Text('Craft beautiful UIs', textAlign: TextAlign.center),
),
Expanded(
child: FittedBox(
fit: BoxFit.contain, // otherwise the logo will be tiny
child: FlutterLogo(), (), [,)Copy the code
Column
The Column class displays the widgets of its child items in a vertical array (a vertical list of child widgets). To expand the child to fill the available vertical space, wrap the child in Expanded Widget. The Column widget does not scroll (and it is generally considered a mistake to have more children in a Column than the number of available rooms). If you have a row of widgets and want them to scroll when you run out of space, consider using ListView.
Column(
children: const <Widget>[
Text('Deliver features faster'),
Text('Craft beautiful UIs'),
Expanded(
child: FittedBox(
fit: BoxFit.contain, // otherwise the logo will be tiny
child: FlutterLogo(), (), [,)Copy the code
Image
Image class Displays the widget for the Image.
Sometimes apps need to display images. Fortunately, Flutter has a widget called Image that comes in handy. This widget allows images to be displayed on the screen. There are many ways that Flutter can extract display images. This Image may come from the Asset Bundle saved by your App using image. Asset and providing the Asset name. Image.asset automatically displays the file in the appropriate version based on the pixel density of the device. All you need to do is provide other versions and add them to pubspec.yaml. You can also display images from the web. To do this, use Image.net Work () and provide a URL. Flutter will display Web images that are cached automatically. Keep in mind that web images may not load as fast as images in Asset and the user has to be connected to the Internet to see the initial image. You can submit a loadingBuilder that the framework calls repeatedly to download images from the network. LoadingBuilder includes the download progress parameter, which you can use to let the user know how long it will take for the actual image to be downloaded and displayed. You can also choose to display images from the user’s device using image.file, and images stored in memory as byte arrays can also be displayed on the screen using image.memory. Parameters can be configured regardless of the source of the image file. Set the width and/or height properties to determine the size of the image and avoid ugly shaking when loading the layout. Set the fit property of the image to allocate space for carving into the layout. The default option is contain but there are other options, including Fill, which contains an image and cover, which does not contain. You can also use color and colorBlendMode to color your images (similar to native Tint color). There are many options. Don’t forget to label the image semanticLabel. These will show up in assistive technologies (similar to voice-overs in iOS) and make your app more accessible. Flutter supports JPEG, PNG, GIF, WebP, bitmap, and WBMP. You can also display GIFs and WebP animations.
Image.network(
'https://example.com/dash.jpg',
loadingBuilder: (context, child, progress) {
return progress == null
? child
: LinearProgressIndicator(...). ; },)Copy the code
Image.file(
'/path/to/dash.jpg'.)Copy the code
Image.memory(
myUint8List,
)
Copy the code
Image.asset(
'assets/images/dash.jpg',
width: 200,
height: 400,
fit: BoxFit.contain,
color: Colors.red,
colorBlendMode: BlendMode.darken,
semanticLabel: 'Dash mascot'.)Copy the code
flutter:
assets:
- images/dash.png
- images/2x/dash.png
Copy the code
Image.network(
'http://example.com/dash.jpg'.)Copy the code
Several constructors are provided for various ways to specify an image:
- New Image, used to get the Image from the ImageProvider.
- New image. asset, used to fetch images from the AssetBundle using key.
- New Image.net Work, used to fetch images from urls.
- New image.file, used to get images from file.
- New image.memory, used to fetch images from the Uint8List.
Supports the following image formats: JPEG, PNG, GIF, Animated GIF, WebP, Animated WebP, BMP, and WBMP. The underlying platform (iOS/ Android) may support other formats. Flutter will attempt to call the platform API to decode an unrecognized format, and if the platform API supports decoding an image, Flutter will be able to render it.
To automatically execute pixel-density-aware asset resolution, Specify the Image with AssetImage and ensure that the MaterialApp, WidgetsApp, or MediaQuery Widget exists above the Image widget in the Widget tree.
The image is drawn using paintImage, which describes the meaning of the various fields on this class in more detail.
The default constructor can be used with any ImageProvider, such as NetworkImage, to display images from the Internet.
const Image(
image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg'),
Copy the code
For convenience, the Image Widget also provides several constructors to display different types of images. In this example, the Image.net Work constructor is used to display images from the Internet.
Image.network('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg')
Copy the code
The image. asset, Image.network, image. file, and image. memory constructors allow custom decoding sizes to be specified with cacheWidth and cacheHeight arguments. The engine decodes the image to a specified size, mainly to reduce ImageCache’s memory usage. In the case of Web images on a Web platform, the cacheWidth and cacheHeight parameters are ignored because the Web engine delegates the decoding of Web images to the Web and does not support custom decoding sizes.
Text
Text class Single-format Text. The Text widget displays a Text string with a single style. Depending on layout constraints, strings may span multiple lines, or they may all appear on the same line. The style argument is optional. When omitted, the text will use the style in the latest enclosing DefaultTextStyle. If the textStyle. inherit attribute for a given style is true (the default), then the given style will be merged with the nearest enclosing DefaultTextStyle. This merging behavior is useful, for example, to make text bold when using the default font family and size.
Text(
'Hello, $_name! How are you? ',
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontWeight: FontWeight.bold),
)
Copy the code
Using the Text.rich constructor, the Text Widget displays paragraphs with different styles of TextSpans. The following example displays “Hello Beautiful World” in a different style for each word.
const Text.rich(
TextSpan(
text: 'Hello'.// default text style
children: <TextSpan>[
TextSpan(text: ' beautiful ', style: TextStyle(fontStyle: FontStyle.italic)),
TextSpan(text: 'world', style: TextStyle(fontWeight: FontWeight.bold)),
],
),
)
Copy the code
Interactivity of Text:
- To make Text react to touch events, wrap it in the GestureDetector Widget of the GestureDetector. OnTap handler.
- In material Design applications, consider using TextButton, or at least InkWell instead of GestureDetector if this is not appropriate.
- To make parts of the text interactive, use RichText and specify TapGestureRecognizer as the TextSpan. Recognizer for the relevant parts of the text.
Icon
Icon class graphical Icon widgets drawn using the glyphs of fonts described in IconData, such as the predefined IconData of Material in Icons.
Icons are not interactive. For interactive ICONS, consider the IconButton in Material.
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: const <Widget>[
Icon(
Icons.favorite,
color: Colors.pink,
size: 24.0,
semanticLabel: 'Text to announce in accessibility modes',),Icon(
Icons.audiotrack,
color: Colors.green,
size: 30.0,),Icon(
Icons.beach_access,
color: Colors.blue,
size: 36.0,),,)Copy the code
RaisedButton
RaisedButton In Class Material Design, a raised rectangular Material button.
This class is deprecated, please use ElevatedButton instead. Deprecated and replaced with ElevatedButton.
ElevatedButton Class uses raised buttons to add dimension to a layout that would otherwise be mostly flat, such as in a long, busy list of content, or in an expansive space. Avoid using promoted buttons on promoted content such as dialogs or cards.
Scaffold
The basic realization of Scaffold Class Material Design layout structure. This Widget class provides apis for displaying drawers, snackbar, and bottom sheet.
AppBar basis
Tabbed AppBar
Appbar
AppBar Class A Material Design application bar consisting of toolbars and other possible widgets such as TabBar and FlexibleSpaceBar.
AppBar with custom bottom widgets
FlutterLogo
FlutterLogo class Flutter logo, in the form of a widge T. This widget complies with the IconTheme.
Placeholder
Placeholder class A widget that maps a box, representing widgets that will be added to the box in the future. This widget is useful during development to indicate that the interface is not complete.
Material Components Widgets
Implements the Visual, effects, motion-rich widgets of the Material Design guide.
BottomNavigationBar
BottomNavigationBar class BottomNavigationBar that makes it easy to switch between taps and browse top level views. (Similar to the function of UITabBarController at the bottom of iOS)
The Material Widget, shown at the bottom of the app, is used to select from a small number of views, usually between three and five (similar to the three to five tabbars at the bottom of the app’s home page in iOS). The bottom navigation bar consists of multiple items in the form of Text Labels, ICONS, or both, all laid on top of the Material. The bottom navigation bar provides quick navigation between the top-level views of the application. For larger screens, side navigation may be more appropriate.
At the bottom of the navigation bar is usually combined with the Scaffold, it as Scaffold. Provide bottomNavigationBar parameters.
The Type in the bottom navigation bar changes how its items are displayed. If not specified, in less than four items automatically set to BottomNavigationBarType. Fixed, otherwise set to BottomNavigationBarType. Shifting. Items must be at least two in length, and the icon and title/label of each item must not be empty.
- BottomNavigationBarType fixed, fewer than four items when the default values. If the Selected Item is not null, render it with selectedItemColor. Otherwise, the ColorScheme. Primary color of the theme is used with the Brightness. Colorscheme. secondary is used with the Brightness. Dark theme. If backgroundColor is null, the backgroundColor of the navigation bar defaults to the Material backgroundColor themedata.canvascolor (essentially an opaque white).
- BottomNavigationBarType. Shifting, when there are four or more items of the default values. If selectedItemColor is null, all items are rendered white. The background color of the navigation bar and the selected item BottomNavigationBarItem. BackgroundColor the same. In this case, assume that each item will have a different background color, and that the background color will be in sharp contrast to white.
int _selectedIndex = 0;
static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: Business',
style: optionStyle,
),
Text(
'Index 2: School',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',),BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',),BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
Copy the code
int _selectedIndex = 0;
static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: Business',
style: optionStyle,
),
Text(
'Index 2: School',
style: optionStyle,
),
Text(
'Index 3: Settings',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
backgroundColor: Colors.red,
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
backgroundColor: Colors.green,
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
backgroundColor: Colors.purple,
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: 'Settings',
backgroundColor: Colors.pink,
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
Copy the code
TabBar
TabBar class A Material Design widget that displays horizontal row of tabs. (Similar to the common sliding tabs in iOS, there is a group of tabs at the top of the page, and clicking on each TAB toggles the view below the TAB.)
DefaultTabController, TabBar, and TabBarView: Do you need to put widgets into tabs? So, you can use DefaultTabController, TabBar, and TabBarView Widgets. To use tabs, you first need a DefaultTabController. The easiest way to keep selected tabs and visible content in sync is to use DefaultTabController. Once you have this, you’ll need a widget that shows the user switching between tabs. At this stage, you can use TabBar, TabBar receives a list of TAB widgets. Finally, you need to create content for each TAB. At this stage, you can use TabBarView, where each widget listed in the subproject corresponds to a TAB in TabBar. There must be a one-to-one match between tabs and TabView’s subitems.
The following example code, TabBar and TabBarView correspond one to one.
Widget build(BuildContext context) {
return DefaultTabController(
initialIndex: 1,
length: 3,
child: Scaffold(
appBar: AppBar(
title: const Text('TabBar Widget'),
bottom: const TabBar(
tabs: <Widget>[
Tab(
icon: Icon(Icons.cloud_outlined),
),
Tab(
icon: Icon(Icons.beach_access_sharp),
),
Tab(
icon: Icon(Icons.brightness_5_sharp),
),
],
),
),
body: const TabBarView(
children: <Widget>[
Center(
child: Text("It's cloudy here"),),Center(
child: Text("It's rainy here"),),Center(
child: Text("It's sunny here"),),),),); }Copy the code
TabBarView
TabBarView Class displays the page view corresponding to the currently selected TAB. Usually used with TabBar. A page view that displays the widget which corresponds to the currently selected tab.
MaterialApp class
The MaterialApp Class is a convenience widget that encapsulates the widgets typically required by an application to implement Material Design. It builds on top of WidgetsApp by adding material- design-specific functionality, such as AnimatedTheme and GridPaper.
The MaterialApp configures The top-level Navigator to search for routes in The following order:
- For the / route, the home property, if non-null, is used.
- Otherwise, the routes table is used, if it has an entry for the route.
- Otherwise, onGenerateRoute is called, if provided. It should return a non-null value for any valid route not handled by home and routes.
- Finally if all else fails onUnknownRoute is called.
If a Navigator is created, at least one of these options must handle the/route, since it is used when an invalid initialRoute is specified on startup (e.g. by another application launching this one with an intent on Android; see dart:ui.PlatformDispatcher.defaultRouteName).
This widget also configures the observer of the top-level Navigator (if any) to perform Hero animations.
If home, routes, onGenerateRoute, and onUnknownRoute are all null, and Builder is not null, then no Navigator is created.
MaterialApp(
routes: <String, WidgetBuilder>{
'/': (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home Route'),),); },'/about': (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('About Route'),),); }},)Copy the code
WidgetsApp
WidgetsApp Class is a convenience widget that encapsulates the widgets typically required by an application.
One of the main roles provided by WidgetsApp is to bind the system back button to eject the Navigator or exit the application.
It is used by MaterialApp and CupertinoApp to implement the basic functions of the application.
Build MediaQuery using mediaQuery.fromWindow. To use an inherited MediaQuery, set useInheritedMediaQuery to true.
Drawer
The Drawer class slides horizontally from the Scaffold edge to display the Material Design panel for navigation links in the application. (Similar to the left and right drawers in iOS App)
Scaffold(
appBar: AppBar(
title: const Text('Drawer Demo'),
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: const <Widget>[
DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text(
'Drawer Header',
style: TextStyle(
color: Colors.white,
fontSize: 24,),),),ListTile(
leading: Icon(Icons.message),
title: Text('Messages'),),ListTile(
leading: Icon(Icons.account_circle),
title: Text('Profile'),),ListTile(
leading: Icon(Icons.settings),
title: Text('Settings'(), [(), (), ()Copy the code
RaisedButton
RaisedButton In Class Material Design, a raised rectangular Material button. This class is deprecated, please use ElevatedButton instead. This class has been deprecated and ElevatedButton is used instead.
FloatingActionButton
FloatingActionButton Class A circular icon button that hovers over the content to show the main action in the application. FloatingActionButton is typically used for Scaffold. FloatingActionButton fields.
Adding FloatingActionButton to Flutter is very easy. You just need to add FloatingActionButton to the Scaffold. But what if you have a BottomNavigationBar and want FloatingActionButton embedded in it? First, add the BottomNavigationBar to your Scaffold. Then, using embedded FloatingActionButtonLocation FloatingActionButton.
Scaffold(
floatingActionButton: ...
bottomNavigationBar: ...
floatingActionButtonLocation:
FloatingActionButtonLocation.endDocked,
);
Copy the code
If you want FloatingActionButton to be displayed in the middle, try changing endDocked to centerDocked. FloatingActionButton is now neatly embedded in the BottomNavigationBar.
/// Flutter code sample for FloatingActionButton
// This example shows how to display a [FloatingActionButton] in a
// [Scaffold], with a pink [backgroundColor] and a thumbs up [Icon].
//
/ /! [](https://flutter.github.io/assets-for-api-docs/assets/material/floating_action_button.png)
import 'package:flutter/material.dart';
void main(a) = >runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatelessWidget()); }}/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Floating Action Button'),
),
body: const Center(child: Text('Press the button below! ')),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Response event after click
// Add your onPressed code here!
},
child: const Icon(Icons.navigation), backgroundColor: Colors.green, ), ); }}Copy the code
FlatButton class
FlatButton Class A flat Material button. (This class is deprecated, please use TextButton instead. This class is deprecated and TextButton is used instead.
IconButton class
IconButton class a Material IconButton that will animate the water when clicked.
/// Flutter code sample for IconButton
// This sample shows an `IconButton` that uses the Material icon "volume_up" to
// increase the volume.
//
/ /! [](https://flutter.github.io/assets-for-api-docs/assets/material/icon_button.png)
import 'package:flutter/material.dart';
void main(a) = >runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatefulWidget(),),),); }}double _volume = 0.0;
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState(a) => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: const Icon(Icons.volume_up),
tooltip: 'Increase volume by 10',
onPressed: () {
setState(() {
_volume += 10; }); },),Text('Volume : $_volume')],); }}Copy the code
PopupMenuButton class
PopupMenuButton Class Displays a list of pop-up menus when the menu is hidden, clicked or called onSelected.
// This is the type used by the popup menu below.
enum WhyFarther { harder, smarter, selfStarter, tradingCharter }
// This menu button widget updates a _selection field (of type WhyFarther, not shown here).
PopupMenuButton<WhyFarther>(
onSelected: (WhyFarther result) { setState(() { _selection = result; }); },
itemBuilder: (BuildContext context) => <PopupMenuEntry<WhyFarther>>[
const PopupMenuItem<WhyFarther>(
value: WhyFarther.harder,
child: Text('Working a lot harder'),),const PopupMenuItem<WhyFarther>(
value: WhyFarther.smarter,
child: Text('Being a lot smarter'),),const PopupMenuItem<WhyFarther>(
value: WhyFarther.selfStarter,
child: Text('Being a self-starter'),),const PopupMenuItem<WhyFarther>(
value: WhyFarther.tradingCharter,
child: Text('Placed in charge of trading charter'),),,)Copy the code
ButtonBar class
ButtonBar class a group of buttons arranged horizontally.
TextField class
TextField Class Text input box. (Analogy to iOS UITextField)
const TextField(
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',),)
Copy the code
Checkbox class
Checkbox Class Checkbox that allows the user to select multiple options from a group.
bool isChecked = false;
@override
Widget build(BuildContext context) {
Color getColor(Set<MaterialState> states) {
const Set<MaterialState> interactiveStates = <MaterialState>{
MaterialState.pressed,
MaterialState.hovered,
MaterialState.focused,
};
if (states.any(interactiveStates.contains)) {
return Colors.blue;
}
return Colors.red;
}
return Checkbox(
checkColor: Colors.white,
fillColor: MaterialStateProperty.resolveWith(getColor),
value: isChecked,
onChanged: (bool? value) {
setState(() { isChecked = value! ; }); }); }Copy the code
Radio class
Radio Class checkbox that allows the user to select an option from a group.
Used to select between multiple mutually exclusive values. When a Radio button in the group is selected, the other Radio buttons in the group stop selecting. The value is type T, which is the type parameter of Radio. Often used for this purpose.
/// Flutter code sample for Radio
// Here is an example of Radio widgets wrapped in ListTiles, which is similar
// to what you could get with the RadioListTile widget.
//
// The currently selected character is passed into `groupValue`, which is
// maintained by the example's `State`. In this case, the first `Radio`
// will start off selected because `_character` is initialized to
// `SingingCharacter.lafayette`.
//
// If the second radio button is pressed, the example's state is updated
// with `setState`, updating `_character` to `SingingCharacter.jefferson`.
// This causes the buttons to rebuild with the updated `groupValue`, and
// therefore the selection of the second button.
//
// Requires one of its ancestors to be a [Material] widget.
import 'package:flutter/material.dart';
void main(a) = >runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatefulWidget(),),),); }}enum SingingCharacter { lafayette, jefferson }
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState(a) => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
SingingCharacter? _character = SingingCharacter.lafayette;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
ListTile(
title: const Text('Lafayette'),
leading: Radio<SingingCharacter>(
value: SingingCharacter.lafayette,
groupValue: _character,
onChanged: (SingingCharacter? value) {
setState(() { _character = value; }); },),),ListTile(
title: const Text('Thomas Jefferson'),
leading: Radio<SingingCharacter>(
value: SingingCharacter.jefferson,
groupValue: _character,
onChanged: (SingingCharacter? value) {
setState(() { _character = value; }); },),),],); }}Copy the code
Switch class
Switch class On/off Switches a single state.
Slider class
The Slider class allows the user to select from a series of values by sliding the Slider.
/// Flutter code sample for Slider
/ /! [A slider widget, consisting of 5 divisions and showing the default value
// indicator.](https://flutter.github.io/assets-for-api-docs/assets/material/slider.png)
//
// The Sliders value is part of the Stateful widget subclass to change the value
// setState was called.
import 'package:flutter/material.dart';
void main(a) = >runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatefulWidget(),),); }}/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState(a) => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
double _currentSliderValue = 20;
@override
Widget build(BuildContext context) {
return Slider(
value: _currentSliderValue,
min: 0,
max: 100,
divisions: 5,
label: _currentSliderValue.round().toString(),
onChanged: (double value) {
setState(() { _currentSliderValue = value; }); }); }}Copy the code
Date & Time Pickers
Date & Time Pickers Date & Time Pickers.
Chip class
Chip Class tag, a Material Widget. It can present a complex content entity, such as a contact, in a small piece.
Card class
Card Class A Material Design Card with rounded corners and shadows.
/// Flutter code sample for Card
// This sample shows creation of a [Card] widget that shows album information and two actions.
import 'package:flutter/material.dart';
void main(a) = >runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatelessWidget(),),); }}/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
leading: Icon(Icons.album),
title: Text('The Enchanted Nightingale'),
subtitle: Text('Music by Julie Gable. Lyrics by Sidney Stein.'),),Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TextButton(
child: const Text('BUY TICKETS'),
onPressed: () {/ *... * /},),const SizedBox(width: 8),
TextButton(
child: const Text('LISTEN'),
onPressed: () {/ *... * /},),const SizedBox(width: 8() [[() [() [() [() [() [() }}Copy the code
ListTile class
ListTile class A fixed-height row, usually containing some text and an icon at the beginning or end of the line.
/// Flutter code sample for ListTile
// Here is an example of a custom list item that resembles a YouTube-related video list item created with [Expanded] and [Container] widgets.
import 'package:flutter/material.dart';
void main(a) = >runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatelessWidget(),),); }}class CustomListItem extends StatelessWidget {
const CustomListItem({
Key? key,
required this.thumbnail,
required this.title,
required this.user,
required this.viewCount,
}) : super(key: key);
final Widget thumbnail;
final String title;
final String user;
final int viewCount;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
flex: 2,
child: thumbnail,
),
Expanded(
flex: 3,
child: _VideoDescription(
title: title,
user: user,
viewCount: viewCount,
),
),
const Icon(
Icons.more_vert,
size: 16.0[, [, [, [; }}class _VideoDescription extends StatelessWidget {
const _VideoDescription({
Key? key,
required this.title,
required this.user,
required this.viewCount,
}) : super(key: key);
final String title;
final String user;
final int viewCount;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(5.0.0.0.0.0.0.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
title,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14.0,),),const Padding(padding: EdgeInsets.symmetric(vertical: 2.0)),
Text(
user,
style: const TextStyle(fontSize: 10.0),),const Padding(padding: EdgeInsets.symmetric(vertical: 1.0)),
Text(
'$viewCount views',
style: const TextStyle(fontSize: 10.0() [() [() [() }}/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ListView(
padding: const EdgeInsets.all(8.0),
itemExtent: 106.0,
children: <CustomListItem>[
CustomListItem(
user: 'Flutter',
viewCount: 999000,
thumbnail: Container(
decoration: const BoxDecoration(color: Colors.blue),
),
title: 'The Flutter YouTube Channel',),CustomListItem(
user: 'Dash',
viewCount: 884000,
thumbnail: Container(
decoration: const BoxDecoration(color: Colors.yellow),
),
title: 'Announcing Flutter 1.0',)]); }}Copy the code
Stepper class
Stepper class a Material Design step indicator that shows a sequence of steps in the process.
/// Flutter code sample for Stepper
import 'package:flutter/material.dart';
void main(a) = >runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatefulWidget(),),),); }}/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState(a) => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _index = 0;
@override
Widget build(BuildContext context) {
return Stepper(
currentStep: _index,
onStepCancel: () {
if (_index > 0) {
setState(() {
_index -= 1;
});
}
},
onStepContinue: () {
if (_index <= 0) {
setState(() {
_index += 1;
});
}
},
onStepTapped: (int index) {
setState(() {
_index = index;
});
},
steps: <Step>[
Step(
title: const Text('Step 1 title'),
content: Container(
alignment: Alignment.centerLeft,
child: const Text('Content for Step 1'))),const Step(
title: Text('Step 2 title'),
content: Text('Content for Step 2'),),,); }}Copy the code
Divider class
Divider Class A logical 1-pixel high horizontal Divider with padding on both sides.
/// Flutter code sample for Divider
// This sample shows how to display a Divider between an orange and blue box inside a column.
// The Divider is 20 logical pixels in height and contains a vertically centered black line that is 5 logical pixels thick. The black line is indented by 20 logical pixels.
import 'package:flutter/material.dart';
void main(a) = >runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatelessWidget(),),); }}/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: <Widget>[
Expanded(
child: Container(
color: Colors.amber,
child: const Center(
child: Text('Above'),),),),const Divider(
height: 50,
thickness: 5,
indent: 20,
endIndent: 20,),// Subheader example from Material spec.
// https://material.io/components/dividers#types
Container(
padding: const EdgeInsets.only(left: 20),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: Text(
'Subheader',
style: Theme.of(context).textTheme.caption,
textAlign: TextAlign.start,
),
),
),
Expanded(
child: Container(
color: Theme.of(context).colorScheme.primary,
child: const Center(
child: Text('Below'(() [[() [[() [() [() }}Copy the code
Refer to the link
Reference link :🔗
- Widgets catalog