Record learning items

flutter.dev/docs

In Flutter, everything is a Widget. A Widget’s function is to “describe the configuration data of a UI element”. This means that the Widget does not represent the final display element to be drawn on the device screen, but rather describes the configuration data of the display element.

In fact, the real class in Flutter that represents the Element displayed on the screen is Element, which means that the Widget simply describes the Element’s configuration data. Also, one Widget can correspond to multiple elements, because the same Widget object can be added to different parts of the UI tree, and when actually rendering, each Element node in the UI tree corresponds to one Widget object.

  • FlutterGo
  • Flutter_Demo

Flutter complete page Widget:Material App,Scaffold,AppBar

🍝MaterialApp

Description: 🤡 The MaterialApp is the most common entry Widget that conforms to the Material Design concept we use in Flutter development. You can think of it as < HTML >
on a web page, and it comes with routing, theme colors,

and so on

title

🤡 description :Strig type. This property is displayed on top of the App in the Android App Manager, and has no effect on iOS devices.

home

🤡 representation :Widget type, which is the first Widget to be displayed when the application starts normally, unless initialRoute is specified. If the initialRoute display fails, the Widget should also be displayed. (On the first page that is displayed after entering the application, a Widget is passed in, but this Widget actually needs to wrap a Scaffold to show that the application uses the Material Design style.)

routes

🤡 Description :Map

is the top-level routing table of the application. When we use Navigator. PushNamed to jump the named route again, we will look up and jump in this route table. If your application has only one page, instead of using routes, specify the Widget corresponding to home (the argument is passed as a key-value pair: key: route name value: corresponding Widget).
,>

routes: {
  "/HomePage": (context) => HomePage(),
  "/AboutPage": (context) => AboutPage(),
},
Copy the code

theme

🤡 description: application theme, a variety of custom colors can be set for application theme switch

New ThemeData(// primarySwatch: color.blue,)Copy the code

If we wanted to customize a HEX value, then you might want to use

primarySwatch: Color.fromARGB(a, r, g, b). But that’s not going to compile. Because primarySwatch is the MarerialColor type, and the Color type was just returned

Dart file, we need to convert normal such as Hex color to MaterialColor

import 'dart:ui'; import 'package:flutter/material.dart'; // Change the hex when called. MaterialColor createMaterialColor(Color Color) {List strengths = needs change to 0xFF223344 <double>[.05]; Map swatch = <int, Color>{}; final int r = color.red, g = color.green, b = color.blue; for (int i = 1; i < 10; I ++) {strengths.add(0.1 * I); } strengths. Strengths. ForEach ((strength) {final double ds = 0.5 - strength; swatch[(strength * 1000).round()] = Color.fromRGBO( r + ((ds < 0 ? r : (255 - r)) * ds).round(), g + ((ds < 0 ? g : (255 - g)) * ds).round(), b + ((ds < 0 ? b : (255 - b)) * ds).round(), 1, ); }); return MaterialColor(color.value, swatch); } primarySwatch: createMaterialColor(Color(0xFF223344)),Copy the code

Here you can see what themes ThemeData can set

Inheritance: Object -> Diagnosticable -> ThemeData

PrimarySwatch is a “sample” of the theme color, from which other properties can be generated under conditions, for example, if primaryColor is not specified and the current theme is not a dark theme, PrimaryColor specifies the color for primarySwatch by default, and some similar properties such as accentColor and indicatorColor are also affected by primarySwatch

  • ThemeData (Color type attribute)

    • AccentColor – Foreground color (text, buttons, etc.).

    • BackgroundColor – contrast color with primaryColor (e.g. used as the rest of a progress bar).

    • BottomAppBar color – The default color of the BottomAppBar.

    • The default fill color used by RaisedButtons in buttoncolor-material.

    • CanvasColor – The default color of the MaterialType. Canvas Material.

    • Cardcolor-material Is the color when the Card is used.

    • DialogBackgroundColor – The background color of the Dialog element.

    • DisabledColor – Used for Widget invalid color regardless of any state. For example, disable check boxes.

    • DividerColor – The color of the Dividers and PopupMenuDividers, also used in the middle of the ListTiles and in each line of the DataTables.

    • ErrorColor – Used for input validation error colors, such as in TextField.

    • HighlightColor – a highlightColor used for similar ink-splash animations or to indicate that a menu is selected.

    • HintColor – The color used to prompt text or placeholder text, for example in TextField.

    • IndicatorColor – the indicatorColor selected in the TabBar option.

    • PrimaryColor – Background color for the main part of the App (ToolBar, TabBar, etc.).

    • PrimaryColorDark – A darker version of primaryColor.

    • PrimaryColorLight – Lighter version of primaryColor.

    • ScaffoldBackgroundColor – the Material default color on which scaffolds are based, the background color of typical Material applications or application pages.

    • SecondaryHeaderColor – The color of the title of the PaginatedDataTable with selected rows.

    • SelectedRowColor – Highlight color when selecting rows.

    • SplashColor – The color in which ink is sprayed.

    • TextSelectionColor – the color of selected text in a TextField, such as TextField.

    • TextSelectionHandleColor – The handle color used to adjust which part of the current text.

    • ToggleableActiveColor – Used to highlight the active state of toggle widgets such as Switch, Radio, and Checkbox.

    • UnselectedWidgetColor – The color used when the Widget is inactive (but enabled). For example, an unchecked check box. This is usually contrasted with accentColor.

    • FocusColor – The color when the focus is retrieved, for example, some button focus, input box focus.

    • HoverColor – Lingering color after a click, for example, after a button is long pressed and held.

    • CursorColor – input box cursorColor.

  • ThemeData (Theme-related type attributes)

    • AccentIconTheme – IconThemeData type, an image theme that contrasts with the highlight color.

    • AccentTextTheme – the TextTheme type, which contrasts the TextTheme with the highlight color.

    • ChipTheme – ChipThemeData type, used to render Chip colors and styles.

    • The buttonTheme – ButtonThemeData type, which defines the default configuration of controls such as buttons, such as RaisedButton and FlatButton.

    • PrimaryIconTheme – IconThemeData type, an image theme compared to the main color.

    • PrimaryTextTheme – TextThemeData type, a text theme contrasted with the main color.

    • IconTheme – IconThemeData type, an iconTheme that contrasts the card and canvas colors.

    • InputDecorationTheme – inputDecorationTheme type

    • The default InputDecorator, TextField, and TextFormField values are based on this theme.

    • SliderTheme – SliderThemeData type, used to render the color and shape of the Slider.

    • TextTheme – The textTheme type, the text color to contrast with the card and canvas.

    • ToggleButtonsTheme – The ToggleButtonsThemeData type, the theme of ToggleButtons, a new component of Flutter 1.9.

    • TabBarTheme – tabBarTheme type, the theme style of TabBar.

    • TooltipTheme – TooltipThemeData type, toolTip for the theme style.

    • CardTheme – cardTheme type, the theme style of the card.

    • PageTransitionsTheme – pageTransitionsTheme type, page transition theme style.

    • AppBarTheme – appBarTheme type, AppBar theme style.

    • BottomAppBarTheme – bottomAppBarTheme type, which navigates the theme style at the bottom.

    • DialogTheme – dialogTheme type, dialog box theme style.

    • FloatingActionButtonTheme – FloatingActionButtonThemeData type, FloatingActionButton theme style, also is the Scaffold properties.

    • Cupertino ooverridetheme – The cupertino othemedata type, the theme style covered by Cupertino.

    • SnackBarTheme – SnackBarThemeData type, the theme style of the pop-up snackBar.

    • BottomSheetTheme – BottomSheetThemeData type, which slides out the theme style of the dialog box at the bottom.

    • PopupMenuTheme – PopupMenuThemeData type, pop-up menu dialog box theme style.

    • BannerTheme – MaterialBannerThemeData type, Material theme style of the Banner.

    • DividerTheme – DividerThemeData type, the theme style of the Divider component, that is, the horizontal line component.

  • ThemeData (Other types of properties)

    • AccentColorBrightness – Brightness type,

    • AccentColor brightness. Use to determine the color of the text and icon placed at the top of the highlight color (for example, the icon on the -floatingButton).

    • Brightness – The brightness type of the app’s overall theme. Used by widgets such as buttons to determine the color to select when the primary or accent colors are not used.

    • Platform-targetplatform specifies the target type to which the Widget needs to be adapted.

    • SplashFactory – InteractiveInkFeatureFactory type, define InkWall and InkResponse generated the appearance of the ink splash.

    • PrimaryColorBrightness – Brightness type, primaryColor.

    • FontFamily – String, font style.

    • Whether applyElevationOverlayColor – bool type, application cover color elevation.

    • MaterialTapTargetSize – materialTapTargetSize type, Chip components, such as the size of the theme Settings, such as: set to materialTapTargetSize. ShrinkWrap, clip distance from the top to 0; When set to MaterialTapTargetSize. Padded from the top there is a distance.

    • ColorScheme – colorScheme type, scheme group color, a group of 13 colors that can be used to configure color properties for most components.

    • Typographic-typography type used to configure the color and geometric TextTheme values for TextTheme, — primaryTextTheme and accentTextTheme.

    www.pengzhenjin.top/archives/fl…

navigatorKey

NavigatorKey defines the GlobalKey of the current APP instance as the key used when building the navigator. GlobalKey provides state access across widgets.

NavigatorKey. CurrentState is equivalent to the Navigator. Of (context)

GlobalKey<NavigatorState> _navigatorKey=new GlobalKey()
new MaterialApp(
  navigatorKey: _navigatorKey,
);
Copy the code

initialRoute

If the navigator is built, the name of the first route displayed, usually an item defined in Routes, overrides the definition of home

Return MaterialApp(title: 'Application name ', theme: ThemeData(primaryColor: RedAccent), // initialRoute defaults to /. If this is not specified, a key in routes must be replaced with '/' // e.g. 'second': (BuildContext Context) => SecondScreen() instead of '/': (BuildContext Context) => SecondScreen() initialRoute: 'second', routes: <String, WidgetBuilder>{ "third": (BuildContext context) => ThirdScreen(), 'first': (BuildContext context) => FirstScreen(), 'second': (BuildContext context) => SecondScreen() }, );Copy the code

onGenerateRoute

Note that onGenerateRoute only works for named routes.

This method is called when a route is jumped through navigation.of (context).pushnamed and routes cannot be found

Scenario: Suppose we want to develop an e-commerce APP. When users do not log in, they can view information about shops and commodities, but can only view pages such as transaction records, shopping cart and user personal information after logging in. In order to do this, we need to determine the user login status before opening each routing page! Is there a better way to do it if we have to make a judgment call every time we open a route? The answer is yes!

The MaterialApp has an onGenerateRoute property that may be called when the named route is opened. It is possible because Navigator. PushNamed (…) is called. When the named route is enabled, if the specified route name is registered in the routing table, the builder function in the routing table is called to generate routing components. If there is no registration in the routing table, onGenerateRoute is called to generate the route

With the onGenerateRoute callback, it is very easy to implement the above function of controlling page permissions: instead of using a routing table, we provide an onGenerateRoute callback in which unified permissions are controlled, such as:

MaterialApp( ... OnGenerateRoute :(RouteSettings Settings){return MaterialPageRoute(Builder: (context){ String routeName = settings.name; // If the user needs to log in to the routing page, but is not logged in at present, the user directly returns to the routing page, and guides the user to log in. In other cases, routes are normally opened. }); });Copy the code

onUnknownRoute

Called when onGenerateRoute cannot generate a route (except initialRoute)

* If the home page is specified, there is no root route for '/' in routes, there is no root route for '/' in routes. / routes = '/'; / routes = '/'; / routes = '/' There are some onunknownRoutes, such as "Unknown" routes, when the network fails to connect to the networkCopy the code

navigatorObservers

The callbacks of navigation routes, such as push, pop, remove, and replace, are used to retrieve information about the current route and subsequent routes. Route.settings. name Indicates the name of the route

builder

When building a Widget, it is called to configure the font size, orientation, theme color, and so on

onGenerateTitle

If not empty, this callback function is called to generate the application’s title string, otherwise the title is used. If you want to display different descriptions depending on the region use onGenerateTitle(internal callback has context)

MaterialApp(title: 'generalizations ', onGenerateTitle: (context) {var local = Localizations. LocaleOf (context); LanguageCode == 'zh') {return 'laobeng '; } return 'laomeng'; },...).Copy the code

locale

Current locale, if null, uses system locale generally used for language switching

The locale, localizationsDelegates, localeListResolutionCallback, localeResolutionCallback, supportedLocales is the locale, and international related parameters, If your App supports multiple languages, you need to set these parameters. By default, Flutter supports only American English. If you want to add support for other languages, you need to specify other MaterialApp properties and introduce the Flutter_localIzations package. As of April 2019, the Flutter_LocalIzations package is available in 52 languages, and if you want your app to run smoothly on iOS, you must also add the “Flutter_Cupertino_LocalIzations” package

localizationsDelegates

Localization delegate used to change the default tip of the Flutter Widget, button text, etc

localeListResolutionCallback

When an unsupported language is passed in, a similar and supported language can be returned using this callback

new MaterialApp( localeResolutionCallback: (local,support){ if(support.contains(support)){ print('support'); return local; } print('no_support'); return const Locale('us','uk'); }, / / this code was literally fill, possible error locale: locale (' ze ', 'cn'),);Copy the code

supportedLocales

Pass in an array of supported languages

 new MaterialApp(
    supportedLocales: [
      const Locale('uok'),
      const Locale('meg'),
    ],
  );
Copy the code

localeResolutionCallback

Is the difference between localeResolutionCallback and localeListResolutionCallback localeResolutionCallback returns the first parameter is the current language Locale, While localeListResolutionCallback returns the current mobile phone support language collection

debugShowMaterialGrid

Opens the grid paper overlay for the Draw Baseline Grid Material application

showPerformanceOverlay

When true, the top of the application is covered with a LAYER of GPU and UI curves, and the current smoothness can be viewed instantly

checkerboardRasterCacheImages

Opens the checkerboard of the raster cache image

checkerboardOffscreenLayers

Opens the checkerboard of layers rendered to the off-screen bitmap

showSemanticsDebugger

When true, the Widget border opens, similar to the layout boundary shown in Android developer mode

debugShowCheckedModeBanner

Open a small “DEBUG” banner in selected mode to indicate that the application is in selected mode

🍝appBar

The AppBar Material style application bar with toolbars and other widgets is commonly used for the scaffold. AppBar property, which places the application bar in a fixed-height Widget at the top of the screen. For the scrollable application bar, see SliverAppBar, which embeds an AppBar in a sliver for use in a CustomScrollView

In Flutter, the layout of AppBar consists of three components :leading, title, and Actions. Leading is at the far left of AppBar; Title and actions appear on the right.

leading

The component before the title component can be assigned anything — text, ICONS, even multiple widgets in a line.

AppBar(
  leading: Icon(Icons.account_circle_rounded),
),
Copy the code

If leading is not provided, AppBar will automatically bring up the widget for us. Examples include navigation arrows that go back to the previous page or menu ICONS that open drawers.

Navigation arrows automatically appear when the previous route is available.

class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: TextButton( child: Text('Push'), onPressed: () => Navigator.push(context, MaterialPageRoute( builder: (context) { return SecondPage(); },),),),); } } class SecondPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), ); }}Copy the code

When we added a Drawer to the Scaffold, a menu icon was assigned for leading to open the Drawer.

class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), drawer: Drawer(), ); }}Copy the code

Can use attribute automaticallyImplyLeading to prevent this kind of behavior

leadingWidth

The default

AppBar(
  leading: Icon(Icons.account_circle_rounded),
  leadingWidth: 100, // default is 56
),
Copy the code

automaticallyImplyLeading

Use with leading depends on automaticallyImplyLeading = = true, previous routing or drawers, will automatically appear the corresponding ICON has event, false will prevent this kind of behavior

title

The main Widget of appBar, of type Widget, is used to display titles, such as application titles or page titles.

AppBar(
  title: Text('Profile Page'),
),
Copy the code

But you’re not limited to that, because title also contains a widget. You can use it to display ICONS, images, shapes, or any combination of these using layout widgets such as rows and columns.

AppBar(
  title: Container(
    width: 40,
    child: Image.network('https://book.flutterchina.club/logo.png'),
  ),
),
Copy the code

By default, the title is aligned in the middle of the AppBar, according to the Material guide. You can change it so that it is left of center:

AppBar(
  centerTitle: false
)
Copy the code

titleSpacing

TitleSpacing takes effect when centerTitle is false, meaning the title is on the left

The default centerTitle should be center

There is a limit. Too much and it will fail

When the action is wide enough, the title is also left [centerTitle is also useful here]

AppBar(
  centerTitle: false,
  titleSpacing:100
)
Copy the code

actions

The widget displayed after title is aligned to the list of widgets on the right side of the AppBar. We often see them in apps as buttons to trigger pull-down menus, personal avatars, etc.

AppBar(
    actions: [
        Container(
        width: 30,
        child: Image.network('https://book.flutterchina.club/logo.png'),
        ),
        Icon(Icons.more_vert),
    ]
)
Copy the code

Now that we are familiar with the layout of the AppBar, let’s customize it by using theme options. AppBar contains a variety of properties, including color, size, icon theme, text theme, and so on.

backgroundColor

AppBar(
    backgroundColor: Colors.teal
)
Copy the code

iconTheme

Icon Theme Setting

AppBar(
    iconTheme: IconThemeData(color: Colors.green, size: 36),
    actionsIconTheme: IconThemeData(color: Colors.red, size: 36)
)
Copy the code

ActionsIconTheme replaces iconTheme on action

textTheme

Sets the subject of the text

AppBar(textTheme: textTheme (Headline1: TextStyle(fontSize: 72.0, fontWeight: fontweight.bold), headline6: TextStyle(fontSize: 36.0, fontStyle: fontstyle.italic), bodyText2: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),)Copy the code

Headline6 Is the main text used in the AppBar and dialogs of flutter (e.g. Appbar.title and Alertdialog.title). No change in the upper right corner of the image below

elevation

Controls the coordinates of the shadow bar below

AppBar(
  elevation: 102,
)
Copy the code

primary

Whether the App Bar is displayed at the top of the screen.

If true, the App Bar’s toolbar elements and [bottom] widget are filled at the top with the height of the system status bar. The [flexibleSpace] layout is not affected by the [primary] property.

shadowColor

AppBar(
  shadowColor: Colors.red,
  elevation: 102,
)
Copy the code

toolbarHeight

The height of the navigation bar, default is 56

AppBar(
  toolbarHeight: 120
)
Copy the code

toolbarOpacity

Transparency of the appBar navigation bar. The value 1.0 is completely opaque and the value 0.0 is completely transparent

AppBar (toolbarOpacity: 0.5)Copy the code

flexibleSpace

Similar to freemen, default appears in the upper right corner

FlexibleSpace: flexibleSpace: flexibleSpace (flexibleSpace: flexibleSpace (flexibleSpace: flexibleSpace (flexibleSpace: flexibleSpace))Copy the code

bottom

PreferredSize type

You can think of it as adding another piece underneath the AppBar

AppBar(bottom: PreferredSize(PreferredSize: const size.fromheight (PreferredSize: const size.fromheight), child: Theme(data: Theme. Of (context). CopyWith (accentColor: color.white), child: Container(height: 48.0, alignment: Alignment. Center, child: Text(' you are thirty '),),))Copy the code

PreferredSize

Custom bottom

This control does not impose any constraints on its children and does not affect the child’s layout in any way.

This control is useful for customizing appbar.bottom and AppBar

Customizable AppBar, also can directly set the height of AppBar (PreferredSize child control AppBar)

appBar: PreferredSize(
    preferredSize: Size.fromHeight(200),
    child: Container(
      color: Colors.blue,
    ),
  )
Copy the code

bottomOpacity

Transparency of the bottom section

shape

The shape of

AppBar(
  shape: BeveledRectangleBorder(
            borderRadius: BorderRadius.circular(18))
)
Copy the code

brightness

Status bar font color

  • Light: black
  • Dark: white
AppBar(
  brightness: Brightness.light,
)
Copy the code

backwardsCompatibility

Unimportant attributes — default to false(not recommended)

foregroundColor

Apply the brightness of the bar material

primary

Whether appBar is displayed at the top of the taskbar

🍝Scaffold

The Scaffold implements the basic Material layout. Scaffold can be used to draw layout control elements that are displayed on a single interface defined in Material.

Display drawers (e.g. left side bar), snack bars and bottom buttons (bottom sheets) are provided.

Scaffold can be thought of as a container of layouts. This container is where we can draw our user interface

appBar

The navigation bar at the top of the page – this goes directly to the AppBar

body

Page Container – Go straight to layout (the next step is to look at layout)

floatingActionButton

Hover button

Scaffold(
  floatingActionButton: FloatingActionButton(
        onPressed: ()=>{},
        tooltip: 'Increment',
        child: Icon(Icons.add),
  )
)
Copy the code

Take a look at FloatingActionButton
  • child

Child control, usually Icon

FloatingActionButton(
    child: Icon(Icons.add),
)
Copy the code
  • tooltip

A prompt message appears at the end of a long press

FloatingActionButton(Tooltip :" Icons ", Child: Icon(icon.add),)Copy the code

  • foregroundColor

Icon and Text colors

FloatingActionButton(Tooltip :" bub ", foregroundColor: Colors. Green, Child: Icon(Icons.add),)Copy the code

Other properties directly see here is based on [style] : www.jianshu.com/p/6ced97ac7…

FloatingActionButtonLocation: suspended button position

Scaffold(
  floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
  floatingActionButton: FloatingActionButton(
        onPressed: ()=>{},
        tooltip: 'Increment',
        child: Icon(Icons.add),
  )
)
Copy the code

There are a lot of a location attribute FloatingActionButtonLocation

  • CenterDocked: bottom to the middle
  • CenterFloat: Bottom center up
  • CenterTop: middle of the top
  • EndDocked: lower right corner
  • EndFloat: lower right corner upper [default]
  • EndTop: upper right corner
  • StartDocked: lower left corner
  • StartFloat: upper left corner
  • StartTop: upper left corner

Add a mini in front of all of the above to make it all smaller, like miniEndDocked remember the hump

floatingActionButtonAnimator

medium.com/@agungsurya…

Hover button animation

Scaffold(
  floatingActionButtonAnimator: FloatingActionButtonAnimator.scaling,
  floatingActionButton: FloatingActionButton(
        onPressed: ()=>{},
        tooltip: 'Increment',
        child: Icon(Icons.add),
  )
)
Copy the code

persistentFooterButtons

Render a set of buttons at the bottom, above [bottomNavigationBar] and below [body]

It also has the property of being affected by properties such as the colour of the Scaffold Settings. To be precise, because persistentFooterButtons only receive an array, any of its properties are affected by other Scaffold properties.

  • Drawer: Menu on the left
Scaffold(
  drawer: Drawer(),
)
Copy the code

Chensong.blog.csdn.net/article/det…

www.jianshu.com/p/728692143…

  • EndDrawer: menu on the right
Scaffold(
  drawer: Drawer(),
)
Copy the code
  • BottomNavigationBar: Bottom navigation TabBar

  • BottomSheet: A control that persists below the body and above the bottom control

  • BackgroundColor: backgroundColor

  • ResizeToAvoidBottomInset: Control interface content body

Whether to rearrange to avoid the bottom being overwritten, such as when the keyboard is displayed, rearrange to avoid the content being overwritten by the keyboard. The default value is true.

  • Primary: Indicates whether the Appbar is displayed at the top of the screen. Default is true

  • DrawerDragStartBehavior: Controls some properties of the drawer

  • ExtendBody: Whether the body extends to the bottom control

  • ExtendBodyBehindAppBar: Default false, when true, the body will be placed at the top of the Appbar, if the appbar is translucent, it can have a frosted glass effect

  • DrawerScrimColor: Mask color

  • DrawerEdgeDragWidth: The width of the slide bar to pull out

  • Whether drawerEnableOpenDragGesture: on the left side of the slide bar can slide

  • Whether endDrawerEnableOpenDragGesture: the right side bar can slide

threeButton.TextButton,OutlinedButton,ElevatedButton

🍝TextButton

TextButton(Child: Text(' pressed '), onPressed: () {}, onLongPress: () {})Copy the code

🍝OutlinedButton

OutlinedButton(Child: Text(" pressed "), onPressed: () {}, onLongPress: () {})Copy the code

🍝ElevatedButton

ElevatedButton(Child: Text(' pressed '), onPressed: () {}, onLongPress: () {})Copy the code

Style [inElevatedButtonFor example]

First, solve the MaterialStateProperty problem

ButtonStyle styles need to be wrapped by the MaterialStateProperty

  • MaterialStateProperty.all

    Is that the wrap value returns the style required by the component

  • MaterialStateProperty. ResolveAs [auxiliary function]

    Source told his first return to determine whether the value of the incoming MaterialStateProperty. After all the parcel value, if it is the solution set of return to the initial value, if not, then returned directly

  • MaterialStateProperty.resolveWith

    This is the solution set of methods, the MaterialStateProperty. All the value of the package once again set back to the initial value

  • TextStyle / / font

    ElevatedButton (child: Text (" cool "), style: ButtonStyle (textStyle: MaterialStateProperty. All (textStyle (fontSize: 36)), ), onPressed: () {}, )Copy the code

  • FixedSize // Size of the button. This size is still limited by the style’s minimumSize

    ElevatedButton (child: Text (" cool "), style: ButtonStyle (fixedSize: MaterialStateProperty. All (Size (20), 50), minimumSize: MaterialStateProperty.all(Size(300, 100))), onPressed: () {}, )Copy the code

  • BackgroundColor // backgroundColor

    ElevatedButton(Child: Text), style: ButtonStyle(backgroundColor: ButtonStyle) MaterialStateProperty.all(Color(0xff2DF8F2))), ), onPressed: () {}, )Copy the code

  • ForegroundColor // Font color

    ElevatedButton(child: Text), style: ButtonStyle(foregroundColor: MaterialStateProperty.all(Color(0xff000000)),), ), onPressed: () {}, )Copy the code

  • OverlayColor specifies the color of a focused, hovered, or pressed button

    ElevatedButton(child: Text), style: ButtonStyle(overlayColor: MaterialStateProperty.all(Color(0xff31C27C)) ,), ), onPressed: () {}, )Copy the code

  • ShadowColor // shadowColor

    It’s more visible when you click on it

    ElevatedButton(Child: Text), style: ButtonStyle(shadowColor: MaterialStateProperty.all(Colors.red)),), ), onPressed: () {}, )Copy the code

  • Elevation // Shadow value

    A shadow layer (shadowColor sets the color of the shadow layer)

    ElevatedButton (child: Text (" cool "), style: ButtonStyle (elevation: MaterialStateProperty. All (5),),), onPressed: () {},Copy the code

  • padding         // padding

    ElevatedButton(Child: Text), style: ButtonStyle(padding: MaterialStateProperty.all(EdgeInsets.all(36)),), ), onPressed: () {}, )Copy the code

  • MinimumSize // minimumSize

    ElevatedButton(Child: Text(" cool "), style: ButtonStyle(minimumSize: MaterialStateProperty.all(Size(300, 100)), ), onPressed: () {}, )Copy the code

  • Side / / frame

    ElevatedButton (child: Text (" cool "), style: ButtonStyle (side: MaterialStateProperty. All (BorderSide (width: 4, color: Color(0xffFFFFFF)), // pressed: () {},)Copy the code

  • Shape / / shape

    The diamond

    ElevatedButton(Child: Text), style: ButtonStyle(Shape: MaterialStateProperty. All (BeveledRectangleBorder (borderRadius: borderRadius. Circular (8))), / / the rounded radians), onPressed: () {},Copy the code

    circular

    ElevatedButton (child: Text (" cool "), style: ButtonStyle (shape: MaterialStateProperty. All (CircleBorder (side: BorderSide(style: borderStyle.None,)), // Rounded arc), onPressed: () {},)Copy the code

  • MouseCursor // When the cursor of the mouse pointer enters or hovers over [InkWell] of this button (this is used on the Web side or PC side)

  • VisualDensity // how compact the button layout is

    Can be extended up, down, left and right distance

    ElevatedButton(child: Text), ButtonStyle: ButtonStyle(visualDensity: visualDensity (horizontal: 2.0, vertical: horizontal) // Pressed: () {},)Copy the code

  • TapTargetSize // Response to the touch area

    Set this parameter to the size of the MaterialTapTarget. Can be set to: value, fill, and shrink wrap properties

    The MaterialTapTargetSize has two values, which are:

    • Padded: Minimum hit area being set is 48*48. [If the actual size is less than 48, it is still 48.]
    • ShrinkWrap: The actual size of the child component.
    ElevatedButton(Child: Text(" cool "), style: ButtonStyle(minimumSize: MaterialStateProperty.all(Size(20, 20)), tapTargetSize: MaterialTapTargetSize.padded), onPressed: () {}, )Copy the code

    Below is a height of less than 48– only 20. The button can also be triggered under the button

  • AnimationDuration // The duration of animation changes for [Shape] and [elevation].

    animationDuration: Duration.zero
    Copy the code
  • EnableFeedback // Whether the detected gesture should provide audible and/or tactile feedback. On Android, for example, a click produces a click, and a long press produces a brief vibration when feedback is enabled. Typically, the component defaults to true.

  • Alignment // Sets the alignment of the child button

alignment: Alignment.bottomCenter
Copy the code

StyleFrom constructs ButtonStyle

Stateless componentStatelessWidgetAnd stateful componentsStatefulWidget

StatelessWidget

The StatessWidget in Flutter is a widget that does not require state changes – it has no internal state to manage. React components React components React components React components React

Icon, ImageIcon, Dialog, AboutDialog, CircleAvatar, and Text are all subclasses of StatelessWidgets

class TextRed extends StatelessWidget { final String text; const TextRed({Key? key, required this.text}) : super(key: key); @override Widget build(BuildContext context) { return Text( text, style: TextStyle(color: Colors.red), ); }}Copy the code

TextRed takes a data source text from the outside and displays it. Stateless components have only one declaration cycle: build, which can only be called in three cases:

  • When the widget is inserted into the tree, which is the first build (initialization)
  • When the widget’s parent changes its passed value, for example,TextRedThe parent of the text class changes the value of text
  • When the InheritedWidget it relies on changes, the famous Provider status management framework is also implemented with an InheritedWidget, so whether it’s at work or in an interview, The rationale and usage scenarios for the InheritedWidget component are the focus of the review.)

Using statelessWidgets is lighter and saves more memory resources. The Statelesswidget is initialized without dynamically updating the UI, which also improves the performance of our software.

StatefulWidget

StatefulWidget is a mutable state widget. Use the setState method to manage state changes for statefulWidgets. A call to setState tells the Flutter framework that a state has changed, and Flutter reruns the build method so that the application can apply the latest state.

It implements a setState method, and when we call this method, the Statefulwidget is re-rendered, not partially updated. When we call setState, Flutter will re-call its build method to rebuild the widget after receiving the message, thus updating the UI.

Checkbox, Radio, Slider, InkWell, Form, and TextField are all stateful widgets and subclasses of StatefulWidgets.

class StatefulWidgetDemoPage extends StatefulWidget { @override _StatefulWidgetDemoPageState createState() => _StatefulWidgetDemoPageState(); } class _StatefulWidgetDemoPageState extends State<StatefulWidgetDemoPage> { @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { setState(() {}); }, child: Icon(Icons.add), ), appBar: AppBar( title: Text("StatefuleWidget Demo"), centerTitle: true, backgroundColor: Colors.blue, ), body: Column( children: [ Container( width: 100, height: 100, margin: EdgeInsets. All (10), /// color a random value color: _randomColor(),,],),); Return color.fromargb (255, Random().nextint (255), Random().nextint (255), Random().nextInt(255)); }}Copy the code

We define a method that generates a randomColor, _randomColor(), which returns a Color object, and then we define a Container whose initialization parameter Color is the return value of _randomColor(). We then call the setState method in the onPressed method of FloatingActionButton, at which point the Flutter redraws the StatefulWidgetDemoPage, so every time the button is clicked, We can see that the colors of the containers are different.

layout

Linear layout

A linear layout is a horizontal or vertical arrangement of subcomponents. Flutter uses rows and columns to achieve a LinearLayout, similar to the LinearLayout control in Android. Row and Column inherit from Flex

Row Horizontal layout —-Column analogy

  • children

An array of child widgets

Drawer(
  child: Row(children: <Widget>[
    Text('This is Drawer'),
    Text('This is Drawer'),
    Text('This is Drawer'),
  ]),
)
Copy the code

  • textDirection

Indicates the layout order of horizontal subcomponents (from left to right or from right to left). The default value is the text direction of the current Locale (for example, left-to-right for Chinese and English, and right-to-left for Arabic).

Drawer(
  Row(
    textDirection: TextDirection.rtl, 
    children: <Widget>[
            Text('This'),
            Text(' is '),
            Text('Drawer'),
          ]),
        )
)
Copy the code

  • mainAxisAlignment

Represents how the child components are aligned in the horizontal space occupied by Row. TextDirection is the reference frame for mainAxisAlignment.

Row( textDirection:ltr, / / MainAxisAlignment. End: right alignment / / MainAxisAlignment center: a center / / MainAxisAlignment. Start: left-aligned MainAxisAlignment: MainAxisAlignment.end ) Row( textDirection:rtl, / / MainAxisAlignment. End: left-aligned / / MainAxisAlignment center: a center / / MainAxisAlignment. Start: right-aligned MainAxisAlignment: MainAxisAlignment.end )Copy the code
  • verticalDirection

    Indicates the alignment of the vertical axis of the Row. The default is verticaldirection. down, which indicates from top to bottom.

  • mainAxisSize

The default is mainAxissize.max, which means that the Row occupies as much horizontal space as possible, regardless of how much horizontal space the child widgets actually occupy, the width of the Row is always equal to the maximum horizontal width. MainAxisSize. Min means to use as little horizontal space as possible. If the children do not use up the horizontal space, the actual width of the Row is equal to the horizontal space occupied by all the children.

  • crossAxisAlignment

Similar to MainAxisAlignment, this refers to the vertical axis

  • textBaseline

The baseline of the text

Elastic layout

An elastic layout allows child components to allocate parent container space proportionally. The concept of flexible layout exists in other UI systems, such as flexible box layout in H5, FlexboxLayout in Android, etc. The elastic layout of the Flutter is implemented through Flex and Expanded

Flex

The Flex component can arrange child components horizontally or vertically. If you know the main axis, using Row or Column is convenient. Because Row and Column inherit from Flex and have basically the same parameters, you can use Row or Column almost anywhere Flex can be used. Flex is powerful on its own, but it can also work with Expanded components for flexible layouts. Let’s discuss Flex and elastic layout related properties only

  • Direction Specifies the direction of the elastic layout. By default, Row is horizontal and Column is vertical
Flex(
  direction: Axis.horizontal,
)
Flex(
  direction: Axis.vertical,
)
Copy the code
  • Children: Array of child components

Expanded

HTML – like elastic properties

You can scale up the space occupied by Row, Column, and Flex child components.

The flex argument is an elastic coefficient, and if it is 0 or NULL, child is inelastic, that is, the space that will not be occupied by extension. If greater than 0, all Expanded partitions the total free space of the spindle in proportion to their Flex

Flex( direction: Axis.horizontal, children: <Widget>[ Expanded( flex: 1, child: Container( width: 301, height: Color: color.red,), Expanded(Flex: 2, child: Container(height: 30.0, color: color.green,),],)Copy the code

I’m going to look at this one later

Fluid layout

Resolve flex layout text beyond boundaries

Wrap

Wrap behaves basically the same as Row, except that it folds when out of display range

Wrap specific properties

  • spacing

Spacing of the main axis child widgets

Padding(Padding: EdgeInsets. Only (top: 100), child: Wrap(Padding: EdgeInsets) Wrapalign. center, // Children: <Widget>[new Chip(Avatar: new CircleAvatar(backgroundColor: Colors.blue, child: Text('A')), label: new Text('Hamilton'), ), new Chip( avatar: new CircleAvatar( backgroundColor: Colors.blue, child: Text('M')), label: new Text('Lafayette'), ), new Chip( avatar: new CircleAvatar( backgroundColor: Colors.blue, child: Text('H')), label: new Text('Mulligan'), ), new Chip( avatar: new CircleAvatar( backgroundColor: Colors.blue, child: Text('J')), label: new Text('Laurens'), ), ], ), )Copy the code

  • runSpacing

Spacing in the longitudinal direction

Putting it in a Flex container will fail

Wrap(runSpacing: 68.0, // children: [//.....] .)Copy the code

  • runAlignment

The alignment of the vertical axis

Wrap(align: wrapalign.end, // align right along the main axis children: [//.....] .)Copy the code

Flow

Flow can be quite complex to use, and you need to implement the position conversion of the child widgets yourself. In many scenarios, the first consideration is whether the Wrap meets the requirements. Flow is mainly used in scenarios where a custom layout strategy is required or where performance is required (such as in animation). Flow has the following advantages:

  • Performance is good; Flow is a very efficient control for adjusting the size and position of subcomponents. Flow is optimized when adjusting the position of subcomponents with the transformation matrix: After Flow positioning, if the size or position of the child component changes, the paintChild method in FlowDelegate is called context.paintChild for redrawing, and context.PaintChild uses the transition matrix for redrawing. There is no actual adjustment of the component position.

  • Flexible; Since we need to implement the FlowDelegate’s paintChildren() method ourselves, we need to calculate the position of each component ourselves, so we can customize the layout strategy.

Class MyFlowDelegate extends FlowDelegate {override void paintChildren(FlowPaintingContext context) {/* Screen width */ var screenW = context.size.width; double padding = 5; // double offsetX = padding; // double offsetY = padding; For (int I = 0; i < context.childCount; If (offsetX + boxSize < screenW) {/* Draw child control */ context.paintChild(I, transform: Matrix4.translationValues(offsetX, offsetY, 0)); /* Change the x coordinate */ offsetX = offsetX + boxSize + padding; } else {/* reset the x coordinate to margin*/ offsetX = padding; /* Count the y coordinate */ offsetY = offsetY + boxSize + padding; / * draw child controls * / context. PaintChild (I, transform: Matrix4 translationValues (offsetX, offsetY, 0)); } } } @override bool shouldRepaint(FlowDelegate oldDelegate) { return true; }}Copy the code
Flowdelegate (), children: <Widget>[new Container(width: 80.0, height: 80.0, color: Color.red,), new Container(width: 80.0, height: 80.0, color: color.green,), new Container(width: 80.0, height: 80.0, color: color.green,), new Container(width: 80.0, height: 80.0, color: color.green,) 80.0, color: color.blue,),],)Copy the code

Stacking, Stack, jam

Allows child components to be stacked in the order declared in the code (child components can position themselves based on the position of four corners from the parent container)

Cascading layouts are similar to absolute positioning on the Web and Frame layouts on Android

In the Flutter, there is an absolute positioning using the Stack and the Positioned piece

  • alignment

    This parameter determines how to position the child which is unpositioned (without using the tourists) or partially Positioned.

    Left, right is the horizontal axis, top, bottom is the vertical axis, as long as the inclusion of a positioning attribute on the axis is considered to have positioning on the axis.

    Stack (alignment: alignment. Center, / / not specified location or part positioning alignment of the widget children: < widgets > [Container (child: Text("Hello world",style: TextStyle(color: color.white)), color: color.red,), toy (left: 18.0, child: Text("I am Jack"),), toy (top: 18.0, child: Text("Your friend"),)],)Copy the code

    We can see Your friend in the middle of 18 at the top,I am Jack in the middle of 18 to the left, Hello World in the middle — nothing wrong

Alignment and relative positioning

CenterIn the middle

Center(
  child: Text('Hello Flutter')),Copy the code

Align(Align layout)

  • Alignment = alignment. Center:
  • WidthFactor: widthFactor
  • HeightFactor: heightFactor
Align(
  alignment: FractionalOffset.topRight,
  child: Text('Hello'),Copy the code

WidthFactor and heightFactor are attributes used to determine the width and height of the Align component itself; These are two scaling factors that multiply the width and height of the child elements, respectively, resulting in the width and height of the Align component

Align(
  widthFactor: 2,
  heightFactor: 2,
  alignment: Alignment.topRight,
  child: FlutterLogo(
    size: 60,
  ),
)
Copy the code

Since the width and height of FlutterLogo is 60, the final width and height of Align are both 2*60=120

  • Alignment properties

It has two common subclasses: Alignment and FractionalOffset

  • Built-in location properties
TopLeft = Alignment(-1.0, -1.0) topCenter = Alignment(0.0, -1.0) topRight = Alignment(1.0, -1.0) centerLeft = Alignment(-1.0, 0.0) Center = Alignment(0.0, 0.0) centerRight = Alignment(1.0, 0.0) BottomLeft = Alignment(-1.0, 1.0) bottomCenter = Alignment(0.0, 1.0) bottomRight = Alignment(1.0, 1.0)Copy the code
  • The custom
(Alignment. * x childWidth childWidth / / 2 + 2, Alignment, y * childHeight childHeight / / 2 + 2) Alignment (0.5, 0.5)Copy the code
  • The instance
Align(widthFactor: 2, heightFactor: 2, alignment: alignment (2,0.0), child: FlutterLogo(size: 60,)Copy the code

Put Alignment(2,0.0) into the above coordinate transformation formula, and the actual offset coordinate of FlutterLogo can be obtained as (90,30).

  • FractionalOffset

FractionalOffset inherits Alignment. The difference between the two is that the coordinate system is different. The origin of Alignment is the center, while the origin of FractionalOffset is the upper left corner.

  • Built-in location properties
TopLeft = FractionalOffset(0.0, 0.0) topCenter = FractionalOffset(0.5, 0.0) topRight = FractionalOffset(1.0, 0.0) centerLeft = FractionalOffset(0.0, 0.5) Center = FractionalOffset(0.5, 0.5) centerRight = FractionalOffset(1, BottomLeft = FractionalOffset(0.0, 1.0) bottomCenter = FractionalOffset(0.5, BottomRight = FractionalOffset(1.0, 1.0)Copy the code
  • The custom
X * childWidth, fractionalOffse. y * childHeight) FractionalOffset(0.5,0.5)Copy the code
  • The instance
Container(height: 120.0, width: 120.0, color: Colors. Blue [50], child: Align(alignment: FractionalOffset(0.2, 0.6), Child: FlutterLogo(size: 60,),)Copy the code

By substituting FractionalOffset(0.2, 0.6) into the coordinate transformation formula, the actual offset of FlutterLogo is (12,36).

  • AlignmentDirectional

AlignmentDirectional coordinates are similar to AlignmentDirectional in that the origin is in the center, but the starting position of AlignmentDirectional is related to the writing direction

TextDirection can determine AlignmentDirectional coordinates

Same as above

Containers (commonly used boxes)

Padding

Padding is also used a lot in Flutter. As a basic control, Flutter has a very simple function. This property, which you’ve written about on other ends, sets the margin property, the empty area of the margin, which is also part of the widget.

There is no separate Margin control in Flutter. There is a Margin property in Container.

if (margin ! = null) current = new Padding(padding: margin, child: current);Copy the code

EdgeInsets

Padding(
  // Add 16 pixels for each side
  padding: EdgeInsets.all(16.0),
  child:Text("Hello world"),
)

Padding(
  // Add 8 pixels of padding on the left
  padding: const EdgeInsets.only(left: 8.0),
  child: Text("Hello world"),
),

Padding(
  // Add 8 pixels of padding up and down
  padding: const EdgeInsets.symmetric(vertical: 8.0),
  child: Text("Hello world"),
)

Padding(
  // Add 8 pixels for each side
  padding: const EdgeInsets.symmetric(horizontal: 8.0),
  child: Text("Hello world"),
)

Padding(
  // Specify the four directions of the complement
  padding: const EdgeInsets.fromLTRB(20.0.. 0.20.0.20.0),
  child: Text("Hello world"),Copy the code

Size of the container

  • ConstrainedBox: Applies to the maximum/minimum width and height that you need to set, the component size from the child component size, but not beyond the set limits.

  • UnconstrainedBox: Used infrequently, a child of -constrainedBox can “break” ConstrainedBox, and portions that are out of bounds are intercepted.

  • SizedBox: suitable for fixed width and height, often used as a gap between two components.

  • AspectRatio: applies to fixed AspectRatio.

  • FractionallySizedBox: Applies to the percentage of parent components.

  • LimitedBox: Applies when there is no parent constraint.

  • Container: Applies to situations where not only size constraints, but also decoration (color, border, etc.) and interior and exterior margins are required.

ConstrainedBox

ConstrainedBox ConstrainedBox ConstrainedBox ConstrainedBox ConstrainedBox ConstrainedBox ConstrainedBox ConstrainedBox ConstrainedBox ConstrainedBox

ConstrainedBox(
  constraints: BoxConstraints(maxHeight: 60, maxWidth: 200),
  child: Container(height: 300, width: 300, color: Colors.red),
)
Copy the code

In this case, the subcomponent cannot exceed the maximum width and height set by BoxConstraints:

If BoxConstraints is used nested, there are two constrainedBoxes

ConstrainedBox(
  constraints: BoxConstraints(maxHeight: 60, maxWidth: 200),
  child: ConstrainedBox(
    constraints: BoxConstraints(maxHeight: 100, maxWidth: 240),
    child: Container(height: 300, width: 300, color: Colors.red),
  ),
)
Copy the code

For example, the maxHeight of the first BoxConstraints constraints is 60, which limits the maximum height of its children to 60. The maxHeight of the second BoxConstraints constraints is 100. Since the second BoxConstraints constraints are also constrained by the first, So the maximum height of the second BoxConstraints can only be 60, and the maximum height of the final subcomponent is 60, and the maximum width is also 200, so the maximum value of the multi-level BoxConstraints nested constraint ends up being the minimum of the multiple BoxConstraints. Similarly, the minimum nested constraint is equal to the maximum of multiple BoxConstraints constraints

  • UnconstrainedBox

The difference is no interception

Hence the yellow bounding border in development

  • SizedBox

A SizedBox is a component with a fixed width and height that is directly specified

SizedBox(
  height: 60,
  width: 200,
  child: RaisedButton(
    child: Text('this is SizedBox'),
  ),
)
Copy the code

We can also set the size to infinity

SizedBox(
  height: double.infinity,
  width: double.infinity,
  ...
)
Copy the code

A SizedBox can have no child components and still take up space, so a SizedBox is perfect for controlling the gap between two components

Column(
  children: <Widget>[
    Container(height: 30,),
    SizedBox(height: 10,),
    Container(height: 30,),
  ],
)
Copy the code
  • AspectRatio

A component with a fixed aspect ratio

If the width of the component is fixed and you want the height to be half the width, you can use AspectRatio to achieve this effect:

Child: Container(color: color.red), AspectRatio(AspectRatio: 2/1, // Can be written as a fraction.Copy the code
  • FractionallySizedBox

When we need a control with a relative size, such as the current button width 70% of the parent component, we can use the FractionallySizedBox to do this.

Wrap the child control with FractionallySizedBox and set the widthFactor widthFactor or heightFactor heightFactor. The values range from 0 to 1. 0.7 means 70% of the parent component.

FractionallySizedBox(
  widthFactor: .7,
  child: RaisedButton(
    child: Text('button'),
  ),
)
Copy the code

Use the alignment parameter to control the display position of the subcomponents. The default position is Center:

FractionallySizedBox(
  alignment: Alignment.centerLeft,
  ...
)
Copy the code

Interval 10 percent of the parent element

Column(
    children: <Widget>[
      Container(
        height: 50,
        color: Colors.red,
      ),
      Flexible(
        child: FractionallySizedBox(
          heightFactor: .1,
        ),
      ),
      Container(
        height: 50,
        color: Colors.blue,
      ),
    ],
  )
Copy the code
  • Container

The Container component should be one of the most commonly used components, and you can set its width and height directly

Container(
  height: 100,
  width: 100,
  ...
)
Copy the code

The Container component has the most properties of any of these components, and is certainly the most complex to use

  • Alignment This
Container(alignment: align.bottomRight, transform: matrix4.rotationx (1), child: Text(' how sweet '),)Copy the code

  • Padding can be used to add white space between this. Padding Container and child elements
  • This. color Background color
  • The this.decoration property allows you to set the background color and shape of the child controls
Container(Child: Text(' cool '), decoration: BoxDecoration(shape: boxshape. circle, color: color.red),)Copy the code

Deoration and Color: Background colors cannot coexist. Only one of the two colors can exist at the same timeCopy the code
  • Enclosing foregroundDecoration paint decoration in front of the child
Container(Child: Text(' rectangle '), foregroundDecoration: BoxDecoration(Shape: BoxShape. Rectangle, color: rectangle Colors.indigo), decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.red), )Copy the code

Container(Child: Text(' rectangle '), foregroundDecoration: BoxDecoration(Shape: BoxShape. Rectangle, color: rectangle Colors.transparent), decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.red), )Copy the code

  • double? Width the width of the
  • double? Height height
  • BoxConstraints? constraints,
  • This. margin is used the same as padding
  • This. transform You can rotate, translate, and scale containers using a transform
Container(transform: matrix4.rotationx (1),// Slant transform Child: Text(' Oh, oh '),)Copy the code
  • this.transformAlignment,

Alignment of rotation, translation and change

The figure above does not have transformAlignment attributes

Container(transform: matrix4.rotationx (1), transformAlignment: align.bottomRight, child: Text(' cow '),)Copy the code

The difference with alignment of the difference between the parent container

  • This. The child child components

  • This. clipBehavior — By default, content beyond bounds is not clipped

  • LimitedBox

A LimitedBox component is a component that can be used to limit the size of a LimitedBox when it is not bound by a parent component

If the parent component of LimitedBox is restricted, then LimitedBox will do nothing. We can assume that there is no LimitedBox component, and the code is as follows:

children:[
  Container(
    height: 100,
    width: 100,
    child: LimitedBox(
      maxHeight: 50,
      maxWidth: 100,
      child: Container(
        color: Colors.green,
      ),
    ),
  )
]
Copy the code

LimitedBox has no effect if the width and height of LimitedBox is not square.

Add the Container component directly to the ListView:

ListView(
  children: <Widget>[
    Container(
      color: Colors.green,
    ),
    Container(
      color: Colors.red,
    ),
  ],
)
Copy the code

You will notice that there is nothing, because when the Container is unconstrained, the size will be set to 0. Just wrap the Container in a LimitedBox:

ListView(
  children: <Widget>[
    LimitedBox(
      maxHeight: 100,
      child: Container(
        color: Colors.green,
      ),
    ),
    LimitedBox(
      maxHeight: 100,
      child: Container(
        color: Colors.red,
      ),
    ),
  ],
)
Copy the code
  • Clip

    • ClipOval: Clipping to inner circle for square and ellipse for rectangle
    SizedBox(height: 100, child: ClipOval(child: Container(color: color.green,)), // Cut to circle)Copy the code

    • ClipRRect: Clipping child components as rounded rectangles
    ClipRRect( borderRadius: BorderRadius.all(Radius.elliptical(30, 30)), child: Container( color: Color.green,)) ClipRRect(// Clipped to a rounded rectangle borderRadius: borderRadius. Circular (5.0), child: Container(color: Colors.green, ), )Copy the code
    • ClipRect: Clipping subcomponents to the size of the actual occupied rectangle (clipping overflow parts)
    Row (mainAxisAlignment: mainAxisAlignment center, children: < widgets > [ClipRect (/ / clipping child will overflow parts: Align (alignment: Alignment. TopLeft, widthFactor:.5, // Set the width to half of the original Alignment. Child: Text(" hello world ",),), Colors.green)) ], )Copy the code

    • CustomClipper

    Clipping a specific area of a child component

    Class MyClipper extends CustomClipper<Rect> {@override Rect getClip(Size Size) => rect.fromltwh (10.0, 15.0, 40.0, 30.0); @override bool shouldReclip(CustomClipper<Rect> oldClipper) => false; } Clipper(MyClipper(), // Use custom Clipper child: avatar)Copy the code