文章目录

前言

学习flutter时,flutter 官网加载比较慢, 那干脆直接看源码中的示例, 示例中包含了很多常用的组件, 这里收集一下, 方便后续查看.

正则查找

安装好 flutter, 在 ~/flutter/packages/flutter/lib/src 目录下有 flutter 源码, 可以直接查看.

/// ```dart\s*\n(?:/// .*\n)*?/// ```

index

AlertDialog,
Align,
Alignment,
AlwaysScrollableScrollPhysics,
AnimatedCrossFade,
AnimatedGrid,
AnimatedList,
AppBar,
AssetImage,

BackdropFilter,
BackdropGroup,
Border,
BorderSide,
BottomAppBar,
BouncingScrollPhysics,
BoxConstraints,
BoxDecoration,
BoxShadow,
Builder,
ButtonBar,
ButtonStyle,
ByteData,

Card,
CarouselView,
Center,
Checkbox,
CheckboxListTile,
Chip,
CircleAvatar,
ClipOval,
ClipRect,
Color,
ColoredBox,
Column,
ConstrainedBox,
ConstraintsTransformBox,
Container,
ContinuousRectangleBorder,
CupertinoApp,
CupertinoButton,
CupertinoListTile,
CupertinoNavigationBar,
CupertinoPageScaffold,
CupertinoSwitch,
CupertinoTextFormFieldRow,
CupertinoThemeData,
CurveTween,
CurvedAnimation,
CustomPaint,
CustomScrollView,

DecoratedBox,
DecorationImage,
DefaultAssetBundle,
DefaultTextEditingShortcuts,
Dialog,
Directionality,
DragBoundary,
Duration,

ElevatedButton,
ErrorSummary,
ExactAssetImage,
Expanded,

FadeInImage,
FadeTransition,
File,
FileImage,
FittedBox,
FlagProperty,
FlexibleSpaceBar,
FloatingActionButton,
FlutterErrorDetails,
FlutterLogo,
Foo,
FooLibraryBinding,
FooPlatformView,
FractionalOffset,

GestureDetector,
GradientRotation,
GravitySimulation,

HtmlElementView,

Icon,
IconButton,
IconData,
Image,
ImageFiltered,
IndexedSemantics,
Ink,
InkWell,
InputDecoration,

LinearGradient,
LinearProgressIndicator,
ListBody,
ListTile,
ListView,
LookupBoundary,

Material,
MaterialApp,
MaterialBanner,
MaterialScrollBehavior,
MediaQuery,
MemoryImage,
MenuStyle,
MenuThemeData,
MergeSemantics,
MessageProperty,
MyApp,
MyAppHome,
MyPage,
MyWidget,

NetworkImage,
NextFocusIntent,

Object,
Offset,
Opacity,
OutlinedButton,
OverflowBar,

Padding,
PageView,
Paint,
PlatformViewLink,
PlatformViewSurface,
PopupMenuDivider,
Positioned,
PreviousFocusIntent,
ProgressIndicatorTheme,
ProgressIndicatorThemeData,

RadialGradient,
RawGestureDetector,
ReorderableDragStartListener,
ReorderableList,
RequestFocusIntent,
ResizeImage,
RichText,
RotatedBox,
RotationTransition,
Row,

SafeArea,
Scaffold,
SelectAllTextIntent,
SelectableRegion,
SelectableText,
SemanticsLabelBuilder,
ShaderMask,
ShapeDecoration,
Shortcuts,
SimpleDialog,
SimpleDialogOption,
SingleActivator,
SingleChildScrollView,
Size,
SizedBox,
Sky,
SliverAppBar,
SliverChildBuilderDelegate,
SliverChildListDelegate,
SliverFixedExtentList,
SliverGrid,
SliverGridDelegateWithFixedCrossAxisCount,
SliverGridDelegateWithMaxCrossAxisExtent,
SliverList,
SliverPadding,
SliverReorderableList,
SnackBar,
Spacer,
SpringDescription,
SpringSimulation,
Stack,
StatefulBuilder,
Step,
StepStyle,
StringProperty,
StrutStyle,
SubmenuButton,
SuggestionSpan,
SweepGradient,
SwitchListTile,

TabController,
TapAndPanGestureRecognizer,
TapGestureRecognizer,
TestAssetBundle,
TestWidget,
Text,
TextButton,
TextButtonThemeData,
TextField,
TextFormField,
TextRange,
TextSelectionTheme,
TextSelectionThemeData,
TextSpan,
TextStyle,
ThemeData,
TimeOfDay,
ToggleButtons,
Tooltip,
TooltipTheme,
TooltipThemeData,
Transform,

View,
WidgetSpan,
Wrap

lib/src/animation

lib/src/animation/animation_controller.dart

Future<void> fadeOutAndUpdateState() async {
  try {
    await fadeAnimationController.forward().orCancel;
    await sizeAnimationController.forward().orCancel;
    setState(() {
      dismissed = true;
    });
  } on TickerCanceled {
    // the animation got canceled, probably because we were disposed
  }
}

lib/src/animation/animations.dart

final Animation<double> animation = CurvedAnimation(
  parent: controller,
  curve: Curves.ease,
);
final Animation<double> animation = CurvedAnimation(
  parent: controller,
  curve: Curves.easeIn,
  reverseCurve: Curves.easeOut,
);

lib/src/animation/tween_sequence.dart

final Animation<double> animation = TweenSequence<double>(
  <TweenSequenceItem<double>>[
    TweenSequenceItem<double>(
      tween: Tween<double>(begin: 5.0, end: 10.0)
        .chain(CurveTween(curve: Curves.ease)),
      weight: 40.0,
    ),
    TweenSequenceItem<double>(
      tween: ConstantTween<double>(10.0),
      weight: 20.0,
    ),
    TweenSequenceItem<double>(
      tween: Tween<double>(begin: 10.0, end: 5.0)
        .chain(CurveTween(curve: Curves.ease)),
      weight: 40.0,
    ),
  ],
).animate(myAnimationController);

lib/src/animation/tween.dart

_animation = _controller.drive(
  Tween<Offset>(
    begin: const Offset(100.0, 50.0),
    end: const Offset(200.0, 300.0),
  ),
);
_animation = Tween<Offset>(
  begin: const Offset(100.0, 50.0),
  end: const Offset(200.0, 300.0),
).animate(_controller);
final Animation<double> animation = _controller.drive(
  CurveTween(curve: Curves.ease),
);

lib/src/cupertino

lib/src/cupertino/app.dart

const CupertinoApp(
  home: CupertinoPageScaffold(
    navigationBar: CupertinoNavigationBar(
      middle: Text('Home'),
    ),
    child: Center(child: Icon(CupertinoIcons.share)),
  ),
  debugShowCheckedModeBanner: false,
)
CupertinoApp(
  routes: <String, WidgetBuilder>{
    '/': (BuildContext context) {
      return const CupertinoPageScaffold(
        navigationBar: CupertinoNavigationBar(
          middle: Text('Home Route'),
        ),
        child: Center(child: Icon(CupertinoIcons.share)),
      );
    },
    '/about': (BuildContext context) {
      return const CupertinoPageScaffold(
        navigationBar: CupertinoNavigationBar(
          middle: Text('About Route'),
        ),
        child: Center(child: Icon(CupertinoIcons.share)),
      );
    }
  },
)
const CupertinoApp(
  theme: CupertinoThemeData(
    brightness: Brightness.dark,
    primaryColor: CupertinoColors.systemOrange,
  ),
  home: CupertinoPageScaffold(
    navigationBar: CupertinoNavigationBar(
      middle: Text('CupertinoApp Theme'),
    ),
    child: Center(child: Icon(CupertinoIcons.share)),
  ),
)

lib/src/cupertino/colors.dart

CupertinoButton(
  // CupertinoDynamicColor works out of box in a CupertinoButton.
  color: const CupertinoDynamicColor.withBrightness(
    color: CupertinoColors.white,
    darkColor: CupertinoColors.black,
  ),
  onPressed: () { },
  child: child,
)
Container(
  // Container is not a Cupertino widget, but CupertinoTheme.of implicitly
  // resolves colors used in the retrieved CupertinoThemeData.
  color: CupertinoTheme.of(context).primaryColor,
)
CupertinoNavigationBar(
  // CupertinoNavigationBar does not know how to resolve colors used in
  // a Border class.
  border: Border(
    bottom: BorderSide(
      color: CupertinoDynamicColor.resolve(CupertinoColors.systemBlue, context),
    ),
  ),
)
Container(
  // Container is not a Cupertino widget.
  color: CupertinoDynamicColor.resolve(CupertinoColors.systemBlue, context),
)

lib/src/cupertino/debug.dart

assert(debugCheckHasCupertinoLocalizations(context));

lib/src/cupertino/icons.dart

const Row(
  mainAxisAlignment: MainAxisAlignment.spaceAround,
  children: <Widget>[
    Icon(
      CupertinoIcons.heart_fill,
      color: Colors.pink,
      size: 24.0,
      semanticLabel: 'Text to announce in accessibility modes',
    ),
    Icon(
      CupertinoIcons.bell_fill,
      color: Colors.green,
      size: 30.0,
    ),
    Icon(
      CupertinoIcons.umbrella_fill,
      color: Colors.blue,
      size: 36.0,
    ),
  ],
)

lib/src/cupertino/switch.dart

MergeSemantics(
  child: CupertinoListTile(
    title: const Text('Lights'),
    trailing: CupertinoSwitch(
      value: _lights,
      onChanged: (bool value) { setState(() { _lights = value; }); },
    ),
    onTap: () { setState(() { _lights = !_lights; }); },
  ),
)

lib/src/cupertino/text_form_field_row.dart

CupertinoTextFormFieldRow(
  prefix: const Text('Username'),
  onSaved: (String? value) {
    // This optional block of code can be used to run
    // code when the user saves the form.
  },
  validator: (String? value) {
    return (value != null && value.contains('@')) ? 'Do not use the @ char.' : null;
  },
)

lib/src/foundation

lib/src/foundation/annotations.dart

/// A copper coffee pot, as desired by Ben Turpin.
/// ...documentation...
(<String>['Pots', 'Coffee'])
(<String>['Copper', 'Cookware'])
('https://example.com/images/coffee.png')
('A proper cup of coffee is made in a proper copper coffee pot.')
class CopperCoffeePot {
  // ...code...
}
/// Utility class for beginning a dream-sharing sequence.
/// ...documentation...
(<String>['Military Technology', 'Experimental'])
('https://docs.example.org/icons/top.png')
class DreamSharing {
  // ...code...
}
/// A famous cat.
///
/// Instances of this class can hunt small animals.
/// This cat has three legs.
(<String>['Animals', 'Cats'])
(<String>['Cute', 'Pets'])
('https://www.examples.net/docs/images/icons/pillar.jpeg')
('A famous three-legged cat.')
class Pillar extends Cat {
  // ...code...
}

lib/src/foundation/assertions.dart

void main() {
  try {
    // Try to do something!
  } catch (error) {
    // Catch & report error.
    FlutterError.reportError(FlutterErrorDetails(
      exception: error,
      library: 'Flutter test framework',
      context: ErrorSummary('while running async test code'),
    ));
  }
}

lib/src/foundation/binding.dart

// continuing from previous example...
class FooLibraryBinding extends BindingBase with BarBinding, FooBinding {
  static FooBinding ensureInitialized() {
    if (FooBinding._instance == null) {
      FooLibraryBinding();
    }
    return FooBinding.instance;
  }
}

lib/src/foundation/constants.dart

assert(() {
  // ...debug-only code here...
  return true;
}());

lib/src/foundation/diagnostics.dart

MessageProperty table = MessageProperty('table size', '$columns\u00D7$rows');
MessageProperty usefulness = MessageProperty('usefulness ratio', 'no metrics collected yet (never painted)');
StringProperty name = StringProperty('name', _name);
FlagProperty(
  'visible',
  value: true,
  ifFalse: 'hidden',
)
FlagProperty(
  'inherit',
  value: inherit,
  ifTrue: '<all styles inherited>',
  ifFalse: '<no style specified>',
)

lib/src/foundation/print.dart

if (kDebugMode) {
  debugPrint('A useful message');
}

lib/src/foundation/stack_frame.dart

final List<StackFrame> currentFrames = StackFrame.fromStackTrace(StackTrace.current);

lib/src/gestures

lib/src/gestures/events.dart

assert(smallestButton(0x01) == 0x01);
assert(smallestButton(0x11) == 0x01);
assert(smallestButton(0x10) == 0x10);
assert(smallestButton(0) == 0);
  assert(isSingleButton(0x1));
  assert(!isSingleButton(0x11));
  assert(!isSingleButton(0));

lib/src/gestures/gesture_details.dart

void handlePositionedGestures(PositionedGestureDetails details) {
  // Handle the positional information of the gesture details.
}

lib/src/gestures/pointer_signal_resolver.dart

void handleSignalEvent(PointerSignalEvent event) {
  GestureBinding.instance.pointerSignalResolver.register(event, (PointerSignalEvent event) {
    // handle the event...
  });
}

lib/src/gestures/tap_and_drag.dart

RawGestureDetector(
  gestures: <Type, GestureRecognizerFactory>{
    TapAndPanGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapAndPanGestureRecognizer>(
      () => TapAndPanGestureRecognizer(),
      (TapAndPanGestureRecognizer instance) {
        instance
          ..onTapDown = (TapDragDownDetails details) { setState(() { _last = 'down_a'; }); }
          ..onDragStart = (TapDragStartDetails details) { setState(() { _last = 'drag_start_a'; }); }
          ..onDragUpdate = (TapDragUpdateDetails details) { setState(() { _last = 'drag_update_a'; }); }
          ..onDragEnd = (TapDragEndDetails details) { setState(() { _last = 'drag_end_a'; }); }
          ..onTapUp = (TapDragUpDetails details) { setState(() { _last = 'up_a'; }); }
          ..onCancel = () { setState(() { _last = 'cancel_a'; }); };
      },
    ),
  },
  child: Container(
    width: 300.0,
    height: 300.0,
    color: Colors.yellow,
    alignment: Alignment.center,
    child: RawGestureDetector(
      gestures: <Type, GestureRecognizerFactory>{
        TapAndPanGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapAndPanGestureRecognizer>(
          () => TapAndPanGestureRecognizer(),
          (TapAndPanGestureRecognizer instance) {
            instance
              ..onTapDown = (TapDragDownDetails details) { setState(() { _last = 'down_b'; }); }
              ..onDragStart = (TapDragStartDetails details) { setState(() { _last = 'drag_start_b'; }); }
              ..onDragUpdate = (TapDragUpdateDetails details) { setState(() { _last = 'drag_update_b'; }); }
              ..onDragEnd = (TapDragEndDetails details) { setState(() { _last = 'drag_end_b'; }); }
              ..onTapUp = (TapDragUpDetails details) { setState(() { _last = 'up_b'; }); }
              ..onCancel = () { setState(() { _last = 'cancel_b'; }); };
          },
        ),
      },
      child: Container(
        width: 150.0,
        height: 150.0,
        color: Colors.blue,
        child: Text(_last),
      ),
    ),
  ),
)

lib/src/material

lib/src/material/app_bar.dart

SliverAppBar(
  expandedHeight: 150.0,
  flexibleSpace: const FlexibleSpaceBar(
    title: Text('Available seats'),
  ),
  actions: <Widget>[
    IconButton(
      icon: const Icon(Icons.add_circle),
      tooltip: 'Add new entry',
      onPressed: () { /* ... */ },
    ),
  ]
)

lib/src/material/app.dart

MaterialApp(
  home: Scaffold(
    appBar: AppBar(
      title: const Text('Home'),
    ),
  ),
  debugShowCheckedModeBanner: false,
)
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'),
        ),
      );
     }
   },
)
MaterialApp(
  theme: ThemeData(
    brightness: Brightness.dark,
    primaryColor: Colors.blueGrey
  ),
  home: Scaffold(
    appBar: AppBar(
      title: const Text('MaterialApp Theme'),
    ),
  ),
)
const MaterialApp(
  title: 'Material App',
  home: Scaffold(
    body: Center(
      child: Text('Hello World'),
    ),
  ),
)

lib/src/material/banner.dart

ScaffoldMessenger.of(context).showMaterialBanner(
  const MaterialBanner(
    content: Text('Message...'),
    actions: <Widget>[
      // ...
    ],
  )
).closed.then((MaterialBannerClosedReason reason) {
   // ...
});

lib/src/material/bottom_app_bar.dart

Scaffold(
  bottomNavigationBar: BottomAppBar(
    color: Colors.white,
    child: bottomAppBarContents,
  ),
  floatingActionButton: const FloatingActionButton(onPressed: null),
)

lib/src/material/button_bar.dart

// Before
ButtonBar(
  alignment: MainAxisAlignment.spaceEvenly,
  children: <Widget>[
    TextButton( child: const Text('Button 1'), onPressed: () {}),
    TextButton( child: const Text('Button 2'), onPressed: () {}),
    TextButton( child: const Text('Button 3'), onPressed: () {}),
  ],
);
// After
OverflowBar(
  alignment: MainAxisAlignment.spaceEvenly,
  children: <Widget>[
    TextButton( child: const Text('Button 1'), onPressed: () {}),
    TextButton( child: const Text('Button 2'), onPressed: () {}),
    TextButton( child: const Text('Button 3'), onPressed: () {}),
  ],
);

lib/src/material/button_style.dart

ElevatedButton(
  style: ButtonStyle(
    backgroundColor: WidgetStateProperty.resolveWith<Color?>(
      (Set<WidgetState> states) {
        if (states.contains(WidgetState.pressed)) {
          return Theme.of(context).colorScheme.primary.withOpacity(0.5);
        }
        return null; // Use the component's default.
      },
    ),
  ),
  child: const Text('Fly me to the moon'),
  onPressed: () {
    // ...
  },
),
ElevatedButton(
  style: const ButtonStyle(
    backgroundColor: WidgetStatePropertyAll<Color>(Colors.green),
  ),
  child: const Text('Let me play among the stars'),
  onPressed: () {
    // ...
  },
),
TextButton(
  style: TextButton.styleFrom(foregroundColor: Colors.green),
  child: const Text('Let me see what spring is like'),
  onPressed: () {
    // ...
  },
),
MaterialApp(
  theme: ThemeData(
    textButtonTheme: TextButtonThemeData(
      style: TextButton.styleFrom(foregroundColor: Colors.green),
    ),
  ),
  home: const MyAppHome(),
),

lib/src/material/carousel.dart

Scaffold(
  body: CarouselView(
    scrollDirection: Axis.vertical,
    itemExtent: double.infinity,
    children: List<Widget>.generate(10, (int index) {
      return Center(child: Text('Item $index'));
    }),
  ),
),
Scaffold(
  body: CarouselView.weighted(
    scrollDirection: Axis.vertical,
    flexWeights: const <int>[1], // Or any positive integers as long as the length of the array is 1.
    children: List<Widget>.generate(10, (int index) {
      return Center(child: Text('Item $index'));
    }),
  ),
),

lib/src/material/checkbox_list_tile.dart

ColoredBox(
  color: Colors.green,
  child: Material(
    child: CheckboxListTile(
      tileColor: Colors.red,
      title: const Text('CheckboxListTile with red background'),
      value: true,
      onChanged:(bool? value) { },
    ),
  ),
)

lib/src/material/chip.dart

Chip(
  avatar: CircleAvatar(
    backgroundColor: Colors.grey.shade800,
    child: const Text('AB'),
  ),
  label: const Text('Aaron Burr'),
)

lib/src/material/circle_avatar.dart

CircleAvatar(
  backgroundImage: NetworkImage(userAvatarUrl),
)
CircleAvatar(
  backgroundColor: Colors.brown.shade800,
  child: const Text('AH'),
)

lib/src/material/colors.dart

ThemeData(
  primarySwatch: Colors.amber,
)
ThemeData(
 colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.amber),
)
Color selection = Colors.green[400]!; // Selects a mid-range green.
Container(
  color: Colors.blue, // same as Colors.blue[500] or Colors.blue.shade500
)

lib/src/material/debug.dart

assert(debugCheckHasMaterial(context));
assert(debugCheckHasMaterialLocalizations(context));
assert(debugCheckHasScaffold(context));
assert(debugCheckHasScaffoldMessenger(context));

lib/src/material/dialog.dart

const Dialog(constraints: BoxConstraints(maxWidth: 560, minHeight: 280));
Future<void> _showMyDialog() async {
  return showDialog<void>(
    context: context,
    barrierDismissible: false, // user must tap button!
    builder: (BuildContext context) {
      return AlertDialog(
        title: const Text('AlertDialog Title'),
        content: const SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              Text('This is a demo alert dialog.'),
              Text('Would you like to approve of this message?'),
            ],
          ),
        ),
        actions: <Widget>[
          TextButton(
            child: const Text('Approve'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}
SimpleDialogOption(
  onPressed: () { Navigator.pop(context, Department.treasury); },
  child: const Text('Treasury department'),
)
Future<void> _askedToLead() async {
  switch (await showDialog<Department>(
    context: context,
    builder: (BuildContext context) {
      return SimpleDialog(
        title: const Text('Select assignment'),
        children: <Widget>[
          SimpleDialogOption(
            onPressed: () { Navigator.pop(context, Department.treasury); },
            child: const Text('Treasury department'),
          ),
          SimpleDialogOption(
            onPressed: () { Navigator.pop(context, Department.state); },
            child: const Text('State department'),
          ),
        ],
      );
    }
  )) {
    case Department.treasury:
      // Let's go.
      // ...
    break;
    case Department.state:
      // ...
    break;
    case null:
      // dialog dismissed
    break;
  }
}

lib/src/material/drawer.dart

ListTile(
  leading: const Icon(Icons.change_history),
  title: const Text('Change history'),
  onTap: () {
    // change app state...
    Navigator.pop(context); // close the drawer
  },
);

lib/src/material/icon_button.dart

IconButton(
  iconSize: 72,
  icon: const Icon(Icons.favorite),
  onPressed: () {
    // ...
  },
),
IconButton(
  icon: const Icon(Icons.favorite, size: 72),
  onPressed: () {
    // ...
  },
),

lib/src/material/icons.dart

const Row(
  mainAxisAlignment: MainAxisAlignment.spaceAround,
  children: <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,
    ),
  ],
)

lib/src/material/ink_decoration.dart

Material(
  color: Colors.teal[900],
  child: Center(
    child: Ink(
      color: Colors.yellow,
      width: 200.0,
      height: 100.0,
      child: InkWell(
        onTap: () { /* ... */ },
        child: const Center(
          child: Text('YELLOW'),
        )
      ),
    ),
  ),
)
Material(
  color: Colors.grey[800],
  child: Center(
    child: Ink.image(
      image: const AssetImage('cat.jpeg'),
      fit: BoxFit.cover,
      width: 300.0,
      height: 200.0,
      child: InkWell(
        onTap: () { /* ... */ },
        child: const Align(
          alignment: Alignment.topLeft,
          child: Padding(
            padding: EdgeInsets.all(10.0),
            child: Text(
              'KITTEN',
              style: TextStyle(
                fontWeight: FontWeight.w900,
                color: Colors.white,
              ),
            ),
          ),
        )
      ),
    ),
  ),
)

lib/src/material/ink_sparkle.dart

ElevatedButton(
  style: ElevatedButton.styleFrom(splashFactory: InkSparkle.splashFactory),
  child: const Text('Sparkle!'),
  onPressed: () { },
)

lib/src/material/ink_well.dart

assert(debugCheckHasMaterial(context));
assert(debugCheckHasMaterial(context));

lib/src/material/list_tile.dart

const ColoredBox(
  color: Colors.green,
  child: Material(
    child: ListTile(
      title: Text('ListTile with red background'),
      tileColor: Colors.red,
    ),
  ),
)
const Row(
  children: <Widget>[
    Expanded(
      child: ListTile(
        leading: FlutterLogo(),
        title: Text('These ListTiles are expanded '),
      ),
    ),
    Expanded(
      child: ListTile(
        trailing: FlutterLogo(),
        title: Text('to fill the available space.'),
      ),
    ),
  ],
)
ListTile(
  leading: const Icon(Icons.flight_land),
  title: const Text("Trix's airplane"),
  subtitle: _act != 2 ? const Text('The airplane is only in Act II.') : null,
  enabled: _act == 2,
  onTap: () { /* react to the tile being tapped */ }
)
ListTile(
  leading: GestureDetector(
    behavior: HitTestBehavior.translucent,
    onTap: () {},
    child: Container(
      width: 48,
      height: 48,
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      alignment: Alignment.center,
      child: const CircleAvatar(),
    ),
  ),
  title: const Text('title'),
  dense: false,
)

lib/src/material/menu_style.dart

SubmenuButton(
  menuStyle: MenuStyle(
    backgroundColor: WidgetStateProperty.resolveWith<Color?>(
      (Set<WidgetState> states) {
        if (states.contains(WidgetState.focused)) {
          return Theme.of(context).colorScheme.primary.withOpacity(0.5);
        }
        return null; // Use the component's default.
      },
    ),
  ),
  menuChildren: const <Widget>[ /* ... */ ],
  child: const Text('Fly me to the moon'),
),
const SubmenuButton(
  menuStyle: MenuStyle(
    backgroundColor: WidgetStatePropertyAll<Color>(Colors.green),
  ),
  menuChildren: <Widget>[ /* ... */ ],
  child: Text('Let me play among the stars'),
),
MaterialApp(
  theme: ThemeData(
    menuTheme: const MenuThemeData(
      style: MenuStyle(backgroundColor: WidgetStatePropertyAll<Color>(Colors.red)),
    ),
  ),
  home: const MyAppHome(),
),

lib/src/material/no_splash.dart

ElevatedButton(
  style: ElevatedButton.styleFrom(
    splashFactory: NoSplash.splashFactory,
  ),
  onPressed: () { },
  child: const Text('No Splash'),
)

lib/src/material/popup_menu.dart

const PopupMenuItem<Menu>(
  value: Menu.itemOne,
  child: Text('Item 1'),
)
PopupMenuButton<Commands>(
  onSelected: (Commands result) {
    switch (result) {
      case Commands.heroAndScholar:
        setState(() { _heroAndScholar = !_heroAndScholar; });
      case Commands.hurricaneCame:
        // ...handle hurricane option
        break;
      // ...other items handled here
    }
  },
  itemBuilder: (BuildContext context) => <PopupMenuEntry<Commands>>[
    CheckedPopupMenuItem<Commands>(
      checked: _heroAndScholar,
      value: Commands.heroAndScholar,
      child: const Text('Hero and scholar'),
    ),
    const PopupMenuDivider(),
    const PopupMenuItem<Commands>(
      value: Commands.hurricaneCame,
      child: ListTile(leading: Icon(null), title: Text('Bring hurricane')),
    ),
    // ...other items listed here
  ],
)

lib/src/material/progress_indicator_theme.dart

const ProgressIndicatorTheme(
  data: ProgressIndicatorThemeData(
    color: Colors.red,
  ),
  child: LinearProgressIndicator()
)

lib/src/material/radio_list_tile.dart

const ColoredBox(
  color: Colors.green,
  child: Material(
    child: RadioListTile<Meridiem>(
      tileColor: Colors.red,
      title: Text('AM'),
      value: Meridiem.am,
    ),
  ),
)

lib/src/material/refresh_indicator.dart

ListView(
  physics: const AlwaysScrollableScrollPhysics(),
  // ...
)

lib/src/material/scaffold.dart

TabController(vsync: tickerProvider, length: tabCount)..addListener(() {
  if (!tabController.indexIsChanging) {
    setState(() {
      // Rebuild the enclosing scaffold with a new AppBar title
      appBarTitle = 'Tab ${tabController.index}';
    });
  }
})

lib/src/material/selectable_text.dart

const SelectableText(
  'Hello! How are you?',
  textAlign: TextAlign.center,
  style: TextStyle(fontWeight: FontWeight.bold),
)
const SelectableText.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)),
    ],
  ),
)

lib/src/material/shadows.dart

kElevationToShadow[12]!.map((BoxShadow shadow) => shadow.copyWith(blurStyle: BlurStyle.outer)).toList(),

lib/src/material/snack_bar.dart

ScaffoldMessenger.of(context).showSnackBar(
  const SnackBar(
    content: Text('He likes me. I think he likes me.'),
  )
).closed.then((SnackBarClosedReason reason) {
   // ...
});

lib/src/material/stepper.dart

Step(
  title: const Text('Step 1'),
  content: const Text('Content for Step 1'),
  stepStyle: StepStyle(
    color: Colors.blue,
    errorColor: Colors.red,
    border: Border.all(color: Colors.grey),
    boxShadow: const BoxShadow(blurRadius: 3.0, color: Colors.black26),
    gradient: const LinearGradient(colors: <Color>[Colors.red, Colors.blue]),
    indexStyle: const TextStyle(color: Colors.white),
  ),
)

lib/src/material/switch_list_tile.dart

ColoredBox(
  color: Colors.green,
  child: Material(
    child: SwitchListTile(
      tileColor: Colors.red,
      title: const Text('SwitchListTile with red background'),
      value: true,
      onChanged:(bool? value) { },
    ),
  ),
)

lib/src/material/text_form_field.dart

TextFormField(
  decoration: const InputDecoration(
    icon: Icon(Icons.person),
    hintText: 'What do people call you?',
    labelText: 'Name *',
  ),
  onSaved: (String? value) {
    // This optional block of code can be used to run
    // code when the user saves the form.
  },
  validator: (String? value) {
    return (value != null && value.contains('@')) ? 'Do not use the @ char.' : null;
  },
)

lib/src/material/text_selection_theme.dart

const TextSelectionTheme(
  data: TextSelectionThemeData(
    cursorColor: Colors.blue,
    selectionHandleColor: Colors.lightBlue,
  ),
  child: TextField(),
)

lib/src/material/time_picker.dart

Future<TimeOfDay?> selectedTime = showTimePicker(
  initialTime: TimeOfDay.now(),
  context: context,
);
Future<TimeOfDay?> selectedTimeRTL = showTimePicker(
  context: context,
  initialTime: TimeOfDay.now(),
  builder: (BuildContext context, Widget? child) {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: child!,
    );
  },
);
Future<TimeOfDay?> selectedTime24Hour = showTimePicker(
  context: context,
  initialTime: const TimeOfDay(hour: 10, minute: 47),
  builder: (BuildContext context, Widget? child) {
    return MediaQuery(
      data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
      child: child!,
    );
  },
);

lib/src/material/time.dart

TimeOfDay now = TimeOfDay.now();
const TimeOfDay releaseTime = TimeOfDay(hour: 15, minute: 0); // 3:00pm
TimeOfDay roomBooked = TimeOfDay.fromDateTime(DateTime.parse('2018-10-20 16:30:04Z')); // 4:30pm

lib/src/material/toggle_buttons.dart

ToggleButtons(
  isSelected: isSelected,
  onPressed: (int index) {
    setState(() {
      isSelected[index] = !isSelected[index];
    });
  },
  children: const <Widget>[
    Icon(Icons.ac_unit),
    Icon(Icons.call),
    Icon(Icons.cake),
  ],
),
ToggleButtons(
  isSelected: isSelected,
  onPressed: (int index) {
    setState(() {
      for (int buttonIndex = 0; buttonIndex < isSelected.length; buttonIndex++) {
        if (buttonIndex == index) {
          isSelected[buttonIndex] = true;
        } else {
          isSelected[buttonIndex] = false;
        }
      }
    });
  },
  children: const <Widget>[
    Icon(Icons.ac_unit),
    Icon(Icons.call),
    Icon(Icons.cake),
  ],
),
ToggleButtons(
  isSelected: isSelected,
  onPressed: (int index) {
    setState(() {
      for (int buttonIndex = 0; buttonIndex < isSelected.length; buttonIndex++) {
        if (buttonIndex == index) {
          isSelected[buttonIndex] = !isSelected[buttonIndex];
        } else {
          isSelected[buttonIndex] = false;
        }
      }
    });
  },
  children: const <Widget>[
    Icon(Icons.ac_unit),
    Icon(Icons.call),
    Icon(Icons.cake),
  ],
),
ToggleButtons(
  isSelected: isSelected,
  onPressed: (int index) {
    int count = 0;
    for (final bool value in isSelected) {
      if (value) {
        count += 1;
      }
    }
    if (isSelected[index] && count < 2) {
      return;
    }
    setState(() {
      isSelected[index] = !isSelected[index];
    });
  },
  children: const <Widget>[
    Icon(Icons.ac_unit),
    Icon(Icons.call),
    Icon(Icons.cake),
  ],
),

lib/src/material/tooltip_theme.dart

TooltipTheme(
  data: TooltipThemeData(
    decoration: BoxDecoration(
      color: Colors.blue.withOpacity(0.9),
      borderRadius: BorderRadius.zero,
    ),
  ),
  child: Tooltip(
    message: 'Example tooltip',
    child: IconButton(
      iconSize: 36.0,
      icon: const Icon(Icons.touch_app),
      onPressed: () {},
    ),
  ),
)

lib/src/material/typography.dart

typography: Typography.material2018(platform: platform)

lib/src/painting

lib/src/painting/borders.dart

Container(
  padding: const EdgeInsets.all(8.0),
  decoration: BoxDecoration(
    border: Border(
      top: BorderSide(width: 16.0, color: Colors.lightBlue.shade50),
      bottom: BorderSide(width: 16.0, color: Colors.lightBlue.shade900),
    ),
  ),
  child: const Text('Flutter in the sky', textAlign: TextAlign.center),
)

lib/src/painting/box_border.dart

Border.all(width: 2.0, color: const Color(0xFFFFFFFF))
Border(bottom: BorderSide(color: Theme.of(context).dividerColor))
Container(
  decoration: const BoxDecoration(
    border: Border(
      top: BorderSide(color: Color(0xFFFFFFFF)),
      left: BorderSide(color: Color(0xFFFFFFFF)),
      right: BorderSide(),
      bottom: BorderSide(),
    ),
  ),
  child: Container(
    padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 2.0),
    decoration: const BoxDecoration(
      border: Border(
        top: BorderSide(color: Color(0xFFDFDFDF)),
        left: BorderSide(color: Color(0xFFDFDFDF)),
        right: BorderSide(color: Color(0xFF7F7F7F)),
        bottom: BorderSide(color: Color(0xFF7F7F7F)),
      ),
      color: Color(0xFFBFBFBF),
    ),
    child: const Text(
      'OK',
      textAlign: TextAlign.center,
      style: TextStyle(color: Color(0xFF000000))
    ),
  ),
)

lib/src/painting/box_decoration.dart

Container(
  decoration: BoxDecoration(
    color: const Color(0xff7c94b6),
    image: const DecorationImage(
      image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
      fit: BoxFit.cover,
    ),
    border: Border.all(
      width: 8,
    ),
    borderRadius: BorderRadius.circular(12),
  ),
)

lib/src/painting/box_fit.dart

void paintImage(ui.Image image, Rect outputRect, Canvas canvas, Paint paint, BoxFit fit) {
  final Size imageSize = Size(image.width.toDouble(), image.height.toDouble());
  final FittedSizes sizes = applyBoxFit(fit, imageSize, outputRect.size);
  final Rect inputSubrect = Alignment.center.inscribe(sizes.source, Offset.zero & imageSize);
  final Rect outputSubrect = Alignment.center.inscribe(sizes.destination, outputRect);
  canvas.drawImageRect(image, inputSubrect, outputSubrect, paint);
}

lib/src/painting/continuous_rectangle_border.dart

Widget build(BuildContext context) {
  return Material(
    shape: ContinuousRectangleBorder(
      borderRadius: BorderRadius.circular(28.0),
    ),
  );
}

lib/src/painting/edge_insets.dart

const EdgeInsets.all(8.0)
const EdgeInsets.symmetric(vertical: 8.0)
const EdgeInsets.only(left: 40.0)

lib/src/painting/gradient.dart

const SweepGradient gradient = SweepGradient(
  colors: <Color>[Color(0xFFFFFFFF), Color(0xFF009900)],
  transform: GradientRotation(math.pi/4),
);
void paintSky(Canvas canvas, Rect rect) {
  const RadialGradient gradient = RadialGradient(
    center: Alignment(0.7, -0.6), // near the top right
    radius: 0.2,
    colors: <Color>[
      Color(0xFFFFFF00), // yellow sun
      Color(0xFF0099FF), // blue sky
    ],
    stops: <double>[0.4, 1.0],
  );
  // rect is the area we are painting over
  final Paint paint = Paint()
    ..shader = gradient.createShader(rect);
  canvas.drawRect(rect, paint);
}
Container(
  decoration: const BoxDecoration(
    gradient: SweepGradient(
      center: FractionalOffset.center,
      colors: <Color>[
        Color(0xFF4285F4), // blue
        Color(0xFF34A853), // green
        Color(0xFFFBBC05), // yellow
        Color(0xFFEA4335), // red
        Color(0xFF4285F4), // blue again to seamlessly transition to the start
      ],
      stops: <double>[0.0, 0.25, 0.5, 0.75, 1.0],
    ),
  )
)
Container(
  decoration: const BoxDecoration(
    gradient: SweepGradient(
      center: FractionalOffset.center,
      colors: <Color>[
        Color(0xFF4285F4), // blue
        Color(0xFF34A853), // green
        Color(0xFFFBBC05), // yellow
        Color(0xFFEA4335), // red
        Color(0xFF4285F4), // blue again to seamlessly transition to the start
      ],
      stops: <double>[0.0, 0.25, 0.5, 0.75, 1.0],
      transform: GradientRotation(math.pi/4),
    ),
  ),
)

lib/src/painting/image_provider.dart

   Image(
     image: ResizeImage(
       FileImage(File('path/to/image')),
       width: MediaQuery.widthOf(context) ~/ 2, // Half of the screen's width.
     ),
   );
const ExactAssetImage('icons/heart.png', scale: 1.5)
const ExactAssetImage('icons/heart.png', scale: 1.5, package: 'my_icons')

lib/src/painting/image_resolution.dart

const AssetImage('icons/heart.png')
const AssetImage('icons/heart.png', package: 'my_icons')

lib/src/painting/inline_span.dart

Text.rich(
  TextSpan(
    text: 'My name is ',
    style: const TextStyle(color: Colors.black),
    children: <InlineSpan>[
      WidgetSpan(
        alignment: PlaceholderAlignment.baseline,
        baseline: TextBaseline.alphabetic,
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 100),
          child: const TextField(),
        )
      ),
      const TextSpan(
        text: '.',
      ),
    ],
  ),
)

lib/src/painting/shape_decoration.dart

Container(
  decoration: ShapeDecoration(
    color: Colors.white,
    shape: Border.all(
      color: Colors.red,
      width: 8.0,
    ) + Border.all(
      color: Colors.green,
      width: 8.0,
    ) + Border.all(
      color: Colors.blue,
      width: 8.0,
    ),
  ),
  child: const Text('RGB', textAlign: TextAlign.center),
)

lib/src/painting/strut_style.dart

const Text(
  'Hello, world!\nSecond line!',
  style: TextStyle(
    fontSize: 10,
    fontFamily: 'Raleway',
  ),
  strutStyle: StrutStyle(
    fontFamily: 'Roboto',
    fontSize: 30,
    height: 1.5,
  ),
)
const Text.rich(
  TextSpan(
    text: 'First line!\n',
    style: TextStyle(
      fontSize: 14,
      fontFamily: 'Roboto'
    ),
    children: <TextSpan>[
      TextSpan(
        text: 'Second line!\n',
        style: TextStyle(
          fontSize: 16,
          fontFamily: 'Roboto',
        ),
      ),
      TextSpan(
        text: 'Third line!\n',
        style: TextStyle(
          fontSize: 14,
          fontFamily: 'Roboto',
        ),
      ),
    ],
  ),
  strutStyle: StrutStyle(
    fontFamily: 'Roboto',
    height: 1.5,
  ),
)
const Text.rich(
  TextSpan(
    text: '---------         ---------\n',
    style: TextStyle(
      fontSize: 14,
      fontFamily: 'Roboto',
    ),
    children: <TextSpan>[
      TextSpan(
        text: '^^^M^^^\n',
        style: TextStyle(
          fontSize: 30,
          fontFamily: 'Roboto',
        ),
      ),
      TextSpan(
        text: 'M------M\n',
        style: TextStyle(
          fontSize: 30,
          fontFamily: 'Roboto',
        ),
      ),
    ],
  ),
  strutStyle: StrutStyle(
    fontFamily: 'Roboto',
    fontSize: 14,
    height: 1,
    forceStrutHeight: true,
  ),
)
const Text.rich(
  TextSpan(
    text: '       he candle flickered\n',
    style: TextStyle(
      fontSize: 14,
      fontFamily: 'Serif'
    ),
    children: <TextSpan>[
      TextSpan(
        text: 'T',
        style: TextStyle(
          fontSize: 37,
          fontFamily: 'Serif'
        ),
      ),
      TextSpan(
        text: 'in the moonlight as\n',
        style: TextStyle(
          fontSize: 14,
          fontFamily: 'Serif'
        ),
      ),
      TextSpan(
        text: 'Dash the bird fluttered\n',
        style: TextStyle(
          fontSize: 14,
          fontFamily: 'Serif'
        ),
      ),
      TextSpan(
        text: 'off into the distance.',
        style: TextStyle(
          fontSize: 14,
          fontFamily: 'Serif'
        ),
      ),
    ],
  ),
  strutStyle: StrutStyle(
    fontFamily: 'Serif',
    fontSize: 14,
    forceStrutHeight: true,
  ),
)

lib/src/painting/text_span.dart

const TextSpan(
  text: 'Hello world!',
  style: TextStyle(color: Colors.black),
)

lib/src/painting/text_style.dart

const Text(
  'No, we need bold strokes. We need this plan.',
  style: TextStyle(fontWeight: FontWeight.bold),
)
const Text(
  "Welcome to the present, we're running a real nation.",
  style: TextStyle(fontStyle: FontStyle.italic),
)
RichText(
  text: TextSpan(
    style: DefaultTextStyle.of(context).style,
    children: <TextSpan>[
      TextSpan(
        text: "You don't have the votes.\n",
        style: TextStyle(color: Colors.black.withOpacity(0.6)),
      ),
      TextSpan(
        text: "You don't have the votes!\n",
        style: TextStyle(color: Colors.black.withOpacity(0.8)),
      ),
      TextSpan(
        text: "You're gonna need congressional approval and you don't have the votes!\n",
        style: TextStyle(color: Colors.black.withOpacity(1.0)),
      ),
    ],
  ),
)
Text(
  "These are wise words, enterprising men quote 'em.",
  style: DefaultTextStyle.of(context).style.apply(fontSizeFactor: 2.0),
)
const Text(
  'Ladies and gentlemen, you coulda been anywhere in the world tonight, but you’re here with us in New York City.',
  style: TextStyle(height: 5, fontSize: 10),
)
RichText(
  text: const TextSpan(
    text: "Don't tax the South ",
    children: <TextSpan>[
      TextSpan(
        text: 'cuz',
        style: TextStyle(
          color: Colors.black,
          decoration: TextDecoration.underline,
          decorationColor: Colors.red,
          decorationStyle: TextDecorationStyle.wavy,
        ),
      ),
      TextSpan(
        text: ' we got it made in the shade',
      ),
    ],
  ),
)
Stack(
  children: <Widget>[
    // Stroked text as border.
    Text(
      'Greetings, planet!',
      style: TextStyle(
        fontSize: 40,
        foreground: Paint()
          ..style = PaintingStyle.stroke
          ..strokeWidth = 6
          ..color = Colors.blue[700]!,
      ),
    ),
    // Solid text as fill.
    Text(
      'Greetings, planet!',
      style: TextStyle(
        fontSize: 40,
        color: Colors.grey[300],
      ),
    ),
  ],
)
Text(
  'Greetings, planet!',
  style: TextStyle(
    fontSize: 40,
    foreground: Paint()
      ..shader = ui.Gradient.linear(
        const Offset(0, 20),
        const Offset(150, 20),
        <Color>[
          Colors.red,
          Colors.yellow,
        ],
      )
  ),
)
const TextStyle(fontFamily: 'Raleway')
const TextStyle(fontFamily: 'Raleway', package: 'my_package')
const TextStyle(fontFamily: 'Raleway')
const TextStyle(
  fontFamily: 'Raleway',
  fontFamilyFallback: <String>[
    'Noto Sans CJK SC',
    'Noto Color Emoji',
  ],
)

lib/src/physics

lib/src/physics/gravity_simulation.dart

void _startFall() {
  _controller.animateWith(GravitySimulation(
    10.0, // acceleration, pixels per second per second
    0.0, // starting position, pixels
    300.0, // ending position, pixels
    0.0, // starting velocity, pixels per second
  ));
}

lib/src/physics/spring_simulation.dart

void _startSpringMotion() {
  _controller.animateWith(SpringSimulation(
    const SpringDescription(
      mass: 1.0,
      stiffness: 300.0,
      damping: 15.0,
    ),
    0.0, // starting position
    1.0, // ending position
    0.0, // starting velocity
  ));
}

lib/src/rendering/box.dart

AxisDirection get axis => _axis;
AxisDirection _axis = AxisDirection.down; // or initialized in constructor
set axis(AxisDirection value) {
  if (value == _axis) {
    return;
  }
  _axis = value;
  markNeedsLayout();
}
class RenderFoo extends RenderBox
  with RenderObjectWithChildMixin<RenderBar> {
  // ...
}
class FooParentData extends ContainerBoxParentData<RenderBox> {
  // (any fields you might need for these children)
}
// continuing from previous example...
class RenderFoo extends RenderBox with
  ContainerRenderObjectMixin<RenderBox, FooParentData>,
  RenderBoxContainerDefaultsMixin<RenderBox, FooParentData> {
  // ...
}
// continuing from previous example...
RenderBox? child = firstChild;
while (child != null) {
  final FooParentData childParentData = child.parentData! as FooParentData;
  // ...operate on child and childParentData...
  assert(child.parentData == childParentData);
  child = childParentData.nextSibling;
}

lib/src/semantics

lib/src/semantics/semantics.dart

SemanticsLabelBuilder builder = SemanticsLabelBuilder()
  ..addPart('Hello')
  ..addPart('world');
String label = builder.build(); // "Hello world"
SemanticsLabelBuilder builder = SemanticsLabelBuilder(textDirection: TextDirection.ltr)
  ..addPart('Welcome', textDirection: TextDirection.ltr)
  ..addPart('مرحبا', textDirection: TextDirection.rtl); // Arabic
String label = builder.build(); // "Welcome \u202Bمرحبا\u202C" (with Unicode embedding)

lib/src/services

lib/src/services/hardware_keyboard.dart

void handleMessage(FocusNode node, KeyMessage message) {
  final List<KeyEventResult> results = <KeyEventResult>[];
  if (node.onKeyEvent != null) {
    for (final KeyEvent event in message.events) {
      results.add(node.onKeyEvent!(node, event));
    }
  }
  if (node.onKey != null && message.rawEvent != null) {
    results.add(node.onKey!(node, message.rawEvent!));
  }
  final KeyEventResult result = combineKeyEventResults(results);
  // Progress based on `result`...
}

lib/src/services/spell_check.dart

SuggestionSpan suggestionSpan =
  const SuggestionSpan(
    TextRange(start: 7, end: 12),
    <String>['word', 'world', 'old'],
);

lib/src/services/text_formatter.dart

// _pattern is a RegExp or other Pattern object
TextInputFormatter.withFunction(
  (TextEditingValue oldValue, TextEditingValue newValue) {
    return _pattern.hasMatch(newValue.text) ? newValue : oldValue;
  },
),

lib/src/widgets

lib/src/widgets/animated_cross_fade.dart

Widget defaultLayoutBuilder(Widget topChild, Key topChildKey, Widget bottomChild, Key bottomChildKey) {
  return Stack(
    children: <Widget>[
      Positioned(
        key: bottomChildKey,
        left: 0.0,
        top: 0.0,
        right: 0.0,
        child: bottomChild,
      ),
      Positioned(
        key: topChildKey,
        child: topChild,
      )
    ],
  );
}
AnimatedCrossFade(
  duration: const Duration(seconds: 3),
  firstChild: const FlutterLogo(style: FlutterLogoStyle.horizontal, size: 100.0),
  secondChild: const FlutterLogo(style: FlutterLogoStyle.stacked, size: 100.0),
  crossFadeState: _first ? CrossFadeState.showFirst : CrossFadeState.showSecond,
)

lib/src/widgets/animated_scroll_view.dart

Widget myWidget(BuildContext context) {
  return MediaQuery.removePadding(
    context: context,
    removeTop: true,
    removeBottom: true,
    child: AnimatedList(
      initialItemCount: 50,
      itemBuilder: (BuildContext context, int index, Animation<double> animation) {
        return Card(
          color: Colors.amber,
          child: Center(child: Text('$index')),
        );
      }
    ),
  );
}
Widget myWidget(BuildContext context) {
  return MediaQuery.removePadding(
    context: context,
    removeTop: true,
    removeBottom: true,
    child: AnimatedGrid(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
      ),
      initialItemCount: 50,
      itemBuilder: (BuildContext context, int index, Animation<double> animation) {
        return Card(
          color: Colors.amber,
          child: Center(child: Text('$index')),
        );
      }
    ),
  );
}

lib/src/widgets/autocomplete.dart

int highlightedIndex = AutocompleteHighlightedOption.of(context);

lib/src/widgets/basic.dart

Directionality(
  textDirection: TextDirection.rtl,
  child: Container(
    margin: const EdgeInsetsDirectional.only(start: 8),
    color: Colors.blue,
  ),
)
Opacity(
  opacity: _visible ? 1.0 : 0.0,
  child: const Text("Now you see me, now you don't!"),
)
Image.network(
  'https://raw.githubusercontent.com/flutter/assets-for-api-docs/main/packages/diagrams/assets/blend_mode_destination.jpeg',
  color: const Color.fromRGBO(255, 255, 255, 0.5),
  colorBlendMode: BlendMode.modulate
)
ShaderMask(
  shaderCallback: (Rect bounds) {
    return RadialGradient(
      center: Alignment.topLeft,
      radius: 1.0,
      colors: <Color>[Colors.yellow, Colors.deepOrange.shade900],
      tileMode: TileMode.mirror,
    ).createShader(bounds);
  },
  child: const Text(
    "I'm burning the memories",
    style: TextStyle(color: Colors.white),
  ),
)
 Widget build(BuildContext context) {
   return BackdropGroup(
     child: ListView.builder(
       itemCount: 60,
       itemBuilder: (BuildContext context, int index) {
         return ClipRect(
           child: BackdropFilter.grouped(
             filter: ui.ImageFilter.blur(
               sigmaX: 40,
               sigmaY: 40,
             ),
             child: Container(
               color: Colors.black.withOpacity(0.2),
               height: 200,
               child: const Text('Blur item'),
             ),
           ),
         );
      }
    ),
  );
}
Stack(
  fit: StackFit.expand,
  children: <Widget>[
    Text('0' * 10000),
    Center(
      child: ClipRect(  // <-- clips to the 200x200 [Container] below
        child: BackdropFilter(
          filter: ui.ImageFilter.blur(
            sigmaX: 5.0,
            sigmaY: 5.0,
          ),
          child: Container(
            alignment: Alignment.center,
            width: 200.0,
            height: 200.0,
            child: const Text('Hello World'),
          ),
        ),
      ),
    ),
  ],
)
 Widget buildBackdrop() {
   return Stack(
     children: <Widget>[
       Positioned.fill(child: Image.asset('image.png')),
       Positioned.fill(
         child: BackdropFilter(
           filter: ui.ImageFilter.blur(sigmaX: 6, sigmaY: 6),
         ),
       ),
     ],
   );
 }
 Widget buildFilter() {
   return ImageFiltered(
     imageFilter: ui.ImageFilter.blur(sigmaX: 6, sigmaY: 6),
     child: Image.asset('image.png'),
   );
 }
CustomPaint(
  painter: Sky(),
  child: const Center(
    child: Text(
      'Once upon a time...',
      style: TextStyle(
        fontSize: 40.0,
        fontWeight: FontWeight.w900,
        color: Color(0xFFFFFFFF),
      ),
    ),
  ),
)
ClipRect(
  child: Align(
    alignment: Alignment.topCenter,
    heightFactor: 0.5,
    child: Image.network(userAvatarUrl),
  ),
)
ClipOval(
  child: Image.asset('images/cat.png'),
)
ColoredBox(
  color: Colors.black,
  child: Transform(
    alignment: Alignment.topRight,
    transform: Matrix4.skewY(0.3)..rotateZ(-math.pi / 12.0),
    child: Container(
      padding: const EdgeInsets.all(8.0),
      color: const Color(0xFFE8581C),
      child: const Text('Apartment for rent!'),
    ),
  ),
)
const RotatedBox(
  quarterTurns: 3,
  child: Text('Hello World!'),
)
const Card(
  child: Padding(
    padding: EdgeInsets.all(16.0),
    child: Text('Hello World!'),
  ),
)
Center(
  child: Container(
    height: 120.0,
    width: 120.0,
    color: Colors.blue[50],
    child: const Align(
      alignment: Alignment.topRight,
      child: FlutterLogo(
        size: 60,
      ),
    ),
  ),
)
Center(
  child: Container(
    height: 120.0,
    width: 120.0,
    color: Colors.blue[50],
    child: const Align(
      alignment: Alignment(0.2, 0.6),
      child: FlutterLogo(
        size: 60,
      ),
    ),
  ),
)
Center(
  child: Container(
    height: 120.0,
    width: 120.0,
    color: Colors.blue[50],
    child: const Align(
      alignment: FractionalOffset(0.2, 0.6),
      child: FlutterLogo(
        size: 60,
      ),
    ),
  ),
)
const SizedBox(
  width: 200.0,
  height: 300.0,
  child: Card(child: Text('Hello World!')),
)
ConstrainedBox(
  constraints: const BoxConstraints.expand(),
  child: const Card(child: Text('Hello World!')),
)
Container(
  constraints: const BoxConstraints(minHeight: 40, maxHeight: 100),
  alignment: Alignment.center,
  child: const ConstraintsTransformBox(
    constraintsTransform: ConstraintsTransformBox.maxHeightUnconstrained,
    child: Card(child: Text('Hello World!')),
  )
)
Stack(
  children: <Widget>[
    Container(
      width: 100,
      height: 100,
      color: Colors.red,
    ),
    Container(
      width: 90,
      height: 90,
      color: Colors.green,
    ),
    Container(
      width: 80,
      height: 80,
      color: Colors.blue,
    ),
  ],
)
SizedBox(
  width: 250,
  height: 250,
  child: Stack(
    children: <Widget>[
      Container(
        width: 250,
        height: 250,
        color: Colors.white,
      ),
      Container(
        padding: const EdgeInsets.all(5.0),
        alignment: Alignment.bottomCenter,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: <Color>[
              Colors.black.withAlpha(0),
              Colors.black12,
              Colors.black45
            ],
          ),
        ),
        child: const Text(
          'Foreground Text',
          style: TextStyle(color: Colors.white, fontSize: 20.0),
        ),
      ),
    ],
  ),
)
const Row(
  children: <Widget>[
    Expanded(
      child: Text('Deliver features faster', textAlign: TextAlign.center),
    ),
    Expanded(
      child: Text('Craft beautiful UIs', textAlign: TextAlign.center),
    ),
    Expanded(
      child: FittedBox(
        child: FlutterLogo(),
      ),
    ),
  ],
)
const Row(
  children: <Widget>[
    FlutterLogo(),
    Text("Flutter's hot reload helps you quickly and easily experiment, build UIs, add features, and fix bug faster. Experience sub-second reload times, without losing state, on emulators, simulators, and hardware for iOS and Android."),
    Icon(Icons.sentiment_very_satisfied),
  ],
)
const Row(
  children: <Widget>[
    FlutterLogo(),
    Expanded(
      child: Text("Flutter's hot reload helps you quickly and easily experiment, build UIs, add features, and fix bug faster. Experience sub-second reload times, without losing state, on emulators, simulators, and hardware for iOS and Android."),
    ),
    Icon(Icons.sentiment_very_satisfied),
  ],
)
const Row(
  textDirection: TextDirection.rtl,
  children: <Widget>[
    FlutterLogo(),
    Expanded(
      child: Text("Flutter's hot reload helps you quickly and easily experiment, build UIs, add features, and fix bug faster. Experience sub-second reload times, without losing state, on emulators, simulators, and hardware for iOS and Android."),
    ),
    Icon(Icons.sentiment_very_satisfied),
  ],
)
const Column(
  children: <Widget>[
    Text('Deliver features faster'),
    Text('Craft beautiful UIs'),
    Expanded(
      child: FittedBox(
        child: FlutterLogo(),
      ),
    ),
  ],
)
Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  mainAxisSize: MainAxisSize.min,
  children: <Widget>[
    const Text('We move under cover and we move as one'),
    const Text('Through the night, we have one shot to live another day'),
    const Text('We cannot let a stray gunshot give us away'),
    const Text('We will fight up close, seize the moment and stay in it'),
    const Text("It's either that or meet the business end of a bayonet"),
    const Text("The code word is 'Rochambeau,' dig me?"),
    Text('Rochambeau!', style: DefaultTextStyle.of(context).style.apply(fontSizeFactor: 2.0)),
  ],
)
Wrap(
  spacing: 8.0, // gap between adjacent chips
  runSpacing: 4.0, // gap between lines
  children: <Widget>[
    Chip(
      avatar: CircleAvatar(backgroundColor: Colors.blue.shade900, child: const Text('AH')),
      label: const Text('Hamilton'),
    ),
    Chip(
      avatar: CircleAvatar(backgroundColor: Colors.blue.shade900, child: const Text('ML')),
      label: const Text('Lafayette'),
    ),
    Chip(
      avatar: CircleAvatar(backgroundColor: Colors.blue.shade900, child: const Text('HM')),
      label: const Text('Mulligan'),
    ),
    Chip(
      avatar: CircleAvatar(backgroundColor: Colors.blue.shade900, child: const Text('JL')),
      label: const Text('Laurens'),
    ),
  ],
)
RichText(
  text: TextSpan(
    text: 'Hello ',
    style: DefaultTextStyle.of(context).style,
    children: const <TextSpan>[
      TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),
      TextSpan(text: ' world!'),
    ],
  ),
)
RichText(
  text: const TextSpan(text: 'Hello'),
  selectionRegistrar: SelectionContainer.maybeOf(context),
  selectionColor: const Color(0xAF6694e8),
)
class TestAssetBundle extends CachingAssetBundle {
  
  Future<ByteData> load(String key) async {
    if (key == 'resources/test') {
      return ByteData.sublistView(utf8.encode('Hello World!'));
    }
    return ByteData(0);
  }
}
// continuing from previous example...
await tester.pumpWidget(
  MaterialApp(
    home: DefaultAssetBundle(
      bundle: TestAssetBundle(),
      child: const TestWidget(),
    ),
  ),
);
MergeSemantics(
  child: Row(
    children: <Widget>[
      Checkbox(
        value: true,
        onChanged: (bool? value) {},
      ),
      const Text('Settings'),
    ],
  ),
)
ListView(
  addSemanticIndexes: false,
  semanticChildCount: 2,
  children: const <Widget>[
    IndexedSemantics(index: 0, child: Text('First')),
    Spacer(),
    IndexedSemantics(index: 1, child: Text('Second')),
    Spacer(),
  ],
)
class Foo extends StatelessWidget {
  const Foo({super.key});
  
  Widget build(BuildContext context) => const Text('foo');
}
// continuing from previous example...
const Center(child: Foo())
Center(
  child: Builder(
    builder: (BuildContext context) => const Text('foo'),
  ),
)
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: TextButton(
        onPressed: () {
          // Fails because Scaffold.of() doesn't find anything
          // above this widget's context.
          print(Scaffold.of(context).hasAppBar);
        },
        child: const Text('hasAppBar'),
      )
    ),
  );
}
Widget build(BuildContext context) {
  return Scaffold(
    body: Builder(
      builder: (BuildContext context) {
        return Center(
          child: TextButton(
            onPressed: () {
              print(Scaffold.of(context).hasAppBar);
            },
            child: const Text('hasAppBar'),
          ),
        );
      },
    ),
  );
}
await showDialog<void>(
  context: context,
  builder: (BuildContext context) {
    int? selectedRadio = 0;
    return AlertDialog(
      content: StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: List<Widget>.generate(4, (int index) {
              return Radio<int>(
                value: index,
                groupValue: selectedRadio,
                onChanged: (int? value) {
                  setState(() => selectedRadio = value);
                },
              );
            }),
          );
        },
      ),
    );
  },
);

lib/src/widgets/binding.dart

runWidget(
  View(
    view: myFlutterView,
    child: const MyApp(),
  ),
);

lib/src/widgets/container.dart

const DecoratedBox(
  decoration: BoxDecoration(
    gradient: RadialGradient(
      center: Alignment(-0.5, -0.6),
      radius: 0.15,
      colors: <Color>[
        Color(0xFFEEEEEE),
        Color(0xFF111133),
      ],
      stops: <double>[0.9, 1.0],
    ),
  ),
)
Center(
  child: Container(
    margin: const EdgeInsets.all(10.0),
    color: Colors.amber[600],
    width: 48.0,
    height: 48.0,
  ),
)
Container(
  constraints: BoxConstraints.expand(
    height: Theme.of(context).textTheme.headlineMedium!.fontSize! * 1.1 + 200.0,
  ),
  padding: const EdgeInsets.all(8.0),
  color: Colors.blue[600],
  alignment: Alignment.center,
  transform: Matrix4.rotationZ(0.1),
  child: Text('Hello World',
    style: Theme.of(context)
        .textTheme
        .headlineMedium!
        .copyWith(color: Colors.white)),
)

lib/src/widgets/debug.dart

assert(!debugItemsHaveDuplicateKeys(items));
assert(debugCheckHasTable(context));
assert(debugCheckHasMediaQuery(context));
assert(debugCheckHasDirectionality(context));
assert(debugCheckHasWidgetsLocalizations(context));
assert(debugCheckHasOverlay(context));

lib/src/widgets/default_text_editing_shortcuts.dart


Widget build(BuildContext context) {
  // If using WidgetsApp or its descendants MaterialApp or CupertinoApp,
  // then DefaultTextEditingShortcuts is already being inserted into the
  // widget tree.
  return const DefaultTextEditingShortcuts(
    child: Center(
      child: Shortcuts(
        shortcuts: <ShortcutActivator, Intent>{
          SingleActivator(LogicalKeyboardKey.arrowDown, alt: true): NextFocusIntent(),
          SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): PreviousFocusIntent(),
        },
        child: Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(
                hintText: 'alt + down moves to the next field.',
              ),
            ),
            TextField(
              decoration: InputDecoration(
                hintText: 'And alt + up moves to the previous.',
              ),
            ),
          ],
        ),
      ),
    ),
  );
}

lib/src/widgets/editable_text.dart

onChanged: (String newText) {
  if (newText.isNotEmpty) {
    SemanticsService.announce('\$$newText', Directionality.of(context));
  }
}

lib/src/widgets/fade_in_image.dart

FadeInImage(
  // here `bytes` is a Uint8List containing the bytes for the in-memory image
  placeholder: MemoryImage(bytes),
  image: const NetworkImage('https://backend.example.com/image.png'),
)

lib/src/widgets/focus_traversal.dart

Actions.invoke(context, RequestFocusIntent(focusNode));

lib/src/widgets/framework.dart

class Bar {
  final Object? bar = kDebugMode ? Object() : null;
}
class _MyKey extends GlobalObjectKey {
  const _MyKey(super.value);
}

Widget build(BuildContext context) {
  // here, Scaffold.of(context) returns null
  return Scaffold(
    appBar: AppBar(title: const Text('Demo')),
    body: Builder(
      builder: (BuildContext context) {
        return TextButton(
          child: const Text('BUTTON'),
          onPressed: () {
            Scaffold.of(context).showBottomSheet(
              (BuildContext context) {
                return Container(
                  alignment: Alignment.center,
                  height: 200,
                  color: Colors.amber,
                  child: Center(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        const Text('BottomSheet'),
                        ElevatedButton(
                          child: const Text('Close BottomSheet'),
                          onPressed: () {
                            Navigator.pop(context);
                          },
                        )
                      ],
                    ),
                  ),
                );
              },
            );
          },
        );
      },
    )
  );
}
  
  Widget build(BuildContext context) {
    return OutlinedButton(
      onPressed: () async {
        await Future<void>.delayed(const Duration(seconds: 1));
        if (context.mounted) {
          Navigator.of(context).pop();
        }
      },
      child: const Text('Delayed pop'),
    );
  }

lib/src/widgets/gesture_detector.dart

RawGestureDetector(
  gestures: <Type, GestureRecognizerFactory>{
    TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
      () => TapGestureRecognizer(),
      (TapGestureRecognizer instance) {
        instance
          ..onTapDown = (TapDownDetails details) { setState(() { _last = 'down'; }); }
          ..onTapUp = (TapUpDetails details) { setState(() { _last = 'up'; }); }
          ..onTap = () { setState(() { _last = 'tap'; }); }
          ..onTapCancel = () { setState(() { _last = 'cancel'; }); };
      },
    ),
  },
  child: Container(width: 300.0, height: 300.0, color: Colors.yellow, child: Text(_last)),
)

lib/src/widgets/icon_data.dart


abstract final class MyCustomIcons {
  static const String fontFamily = 'MyCustomIcons';
  static const IconData happyFace = IconData(1, fontFamily: fontFamily);
  static const IconData sadFace = IconData(2, fontFamily: fontFamily);
}

lib/src/widgets/icon.dart

const Row(
  mainAxisAlignment: MainAxisAlignment.spaceAround,
  children: <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,
    ),
  ],
)

lib/src/widgets/image.dart

const Image(
  image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg'),
)
Image.network('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg')

lib/src/widgets/localizations.dart

// continuing from previous example...
MyLocalizations.of(context).title()

lib/src/widgets/lookup_boundary.dart

MyWidget(
  child: LookupBoundary(
    child: Builder(
      builder: (BuildContext context) {
        MyWidget? widget = LookupBoundary.findAncestorWidgetOfExactType<MyWidget>(context);
        return Text('$widget'); // "null"
      },
    ),
  ),
)

lib/src/widgets/navigator.dart

void main() {
  runApp(const MaterialApp(home: MyAppHome()));
}
Navigator.push(context, MaterialPageRoute<void>(
  builder: (BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('My Page')),
      body: Center(
        child: TextButton(
          child: const Text('POP'),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  },
));
Navigator.pop(context);
void main() {
  runApp(MaterialApp(
    home: const MyAppHome(), // becomes the route named '/'
    routes: <String, WidgetBuilder> {
      '/a': (BuildContext context) => const MyPage(title: Text('page A')),
      '/b': (BuildContext context) => const MyPage(title: Text('page B')),
      '/c': (BuildContext context) => const MyPage(title: Text('page C')),
    },
  ));
}
Navigator.pushNamed(context, '/b');
bool? value = await Navigator.push(context, MaterialPageRoute<bool>(
  builder: (BuildContext context) {
    return Center(
      child: GestureDetector(
        child: const Text('OK'),
        onTap: () { Navigator.pop(context, true); }
      ),
    );
  }
));
Navigator.push(context, PageRouteBuilder<void>(
  opaque: false,
  pageBuilder: (BuildContext context, _, _) {
    return const Center(child: Text('My PageRoute'));
  },
  transitionsBuilder: (_, Animation<double> animation, _, Widget child) {
    return FadeTransition(
      opacity: animation,
      child: RotationTransition(
        turns: Tween<double>(begin: 0.5, end: 1.0).animate(animation),
        child: child,
      ),
    );
  }
));

lib/src/widgets/platform_menu_bar.dart

List<PlatformMenuItem> menus = <PlatformMenuItem>[ /* Define menus... */ ];
WidgetsBinding.instance.platformMenuDelegate.setMenus(menus);

lib/src/widgets/platform_view.dart

// In a `build` method...
HtmlElementView.fromTagName(
  tagName: 'div',
  onElementCreated: myOnElementCreated,
);
// In a `build` method...
const HtmlElementView(
  viewType: 'my-view-type',
  onPlatformViewCreated: myOnPlatformViewCreated,
  creationParams: <String, Object?>{
    'key': 'someValue',
  },
);
class FooPlatformView extends StatelessWidget {
  const FooPlatformView({super.key});
  
  Widget build(BuildContext context) {
    return PlatformViewLink(
      viewType: 'webview',
      onCreatePlatformView: createFooWebView,
      surfaceFactory: (BuildContext context, PlatformViewController controller) {
        return PlatformViewSurface(
          gestureRecognizers: gestureRecognizers,
          controller: controller,
          hitTestBehavior: PlatformViewHitTestBehavior.opaque,
        );
      },
   );
  }
}

lib/src/widgets/reorderable_list.dart

DragBoundary(
 child: CustomScrollView(
   slivers: <Widget>[
     SliverReorderableList(
       itemBuilder: (BuildContext context, int index) {
         return ReorderableDragStartListener(
           key: ValueKey<int>(index),
           index: index,
           child: Text('$index'),
         );
       },
       dragBoundaryProvider: (BuildContext context) {
         return DragBoundary.forRectOf(context);
       },
       itemCount: 5,
       onReorder: (int fromIndex, int toIndex) {},
     ),
   ],
 )
)
GlobalKey<ReorderableListState> listKey = GlobalKey<ReorderableListState>();
// ...
Widget build(BuildContext context) {
  return ReorderableList(
    key: listKey,
    itemBuilder: (BuildContext context, int index) => const SizedBox(height: 10.0),
    itemCount: 5,
    onReorder: (int oldIndex, int newIndex) {
       // ...
    },
  );
}
// ...
listKey.currentState!.cancelReorder();

lib/src/widgets/safe_area.dart

SafeArea(
  child: Container(
    constraints: const BoxConstraints.expand(),
    alignment: Alignment.center,
    color: Colors.blue,
    child: const Text('Hello, World!'),
  ),
)

lib/src/widgets/scroll_controller.dart

PageView(
  children: <Widget>[
    ListView(
      controller: _trackingScrollController,
      children: List<Widget>.generate(100, (int i) => Text('page 0 item $i')).toList(),
    ),
    ListView(
      controller: _trackingScrollController,
      children: List<Widget>.generate(200, (int i) => Text('page 1 item $i')).toList(),
    ),
    ListView(
     controller: _trackingScrollController,
     children: List<Widget>.generate(300, (int i) => Text('page 2 item $i')).toList(),
    ),
  ],
)

lib/src/widgets/scroll_delegate.dart

CustomScrollView(
  semanticChildCount: 4,
  slivers: <Widget>[
    SliverGrid(
      gridDelegate: _gridDelegate,
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
           return const Text('...');
         },
         childCount: 2,
       ),
     ),
    SliverGrid(
      gridDelegate: _gridDelegate,
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
           return const Text('...');
         },
         childCount: 2,
         semanticIndexOffset: 2,
       ),
     ),
  ],
)
CustomScrollView(
  semanticChildCount: 5,
  slivers: <Widget>[
    SliverGrid(
      gridDelegate: _gridDelegate,
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
           if (index.isEven) {
             return const Text('...');
           }
           return const Spacer();
         },
         semanticIndexCallback: (Widget widget, int localIndex) {
           if (localIndex.isEven) {
             return localIndex ~/ 2;
           }
           return null;
         },
         childCount: 10,
       ),
     ),
  ],
)

lib/src/widgets/scroll_notification_observer.dart

ScrollNotificationObserver.of(context).addListener(_listener);
ScrollNotificationObserver.of(context).removeListener(_listener);
// (e.g. in a stateful widget)
void _listener(ScrollNotification notification) {
  // Do something, maybe setState()
}

lib/src/widgets/scroll_physics.dart

const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics())
ScrollPhysics physics = const BouncingScrollPhysics();
// ...
final ScrollPhysics mergedPhysics = physics.applyTo(const AlwaysScrollableScrollPhysics());
const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics())

lib/src/widgets/scroll_view.dart

CustomScrollView(
  slivers: <Widget>[
    const SliverAppBar(
      pinned: true,
      expandedHeight: 250.0,
      flexibleSpace: FlexibleSpaceBar(
        title: Text('Demo'),
      ),
    ),
    SliverGrid(
      gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: 200.0,
        mainAxisSpacing: 10.0,
        crossAxisSpacing: 10.0,
        childAspectRatio: 4.0,
      ),
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          return Container(
            alignment: Alignment.center,
            color: Colors.teal[100 * (index % 9)],
            child: Text('Grid Item $index'),
          );
        },
        childCount: 20,
      ),
    ),
    SliverFixedExtentList(
      itemExtent: 50.0,
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          return Container(
            alignment: Alignment.center,
            color: Colors.lightBlue[100 * (index % 9)],
            child: Text('List Item $index'),
          );
        },
      ),
    ),
  ],
)
ListView(
  padding: const EdgeInsets.all(8),
  children: <Widget>[
    Container(
      height: 50,
      color: Colors.amber[600],
      child: const Center(child: Text('Entry A')),
    ),
    Container(
      height: 50,
      color: Colors.amber[500],
      child: const Center(child: Text('Entry B')),
    ),
    Container(
      height: 50,
      color: Colors.amber[100],
      child: const Center(child: Text('Entry C')),
    ),
  ],
)
ListView(
  padding: const EdgeInsets.all(20.0),
  children: const <Widget>[
    Text("I'm dedicating every day to you"),
    Text('Domestic life was never quite my style'),
    Text('When you smile, you knock me out, I fall apart'),
    Text('And I thought I was so smart'),
  ],
)
CustomScrollView(
  slivers: <Widget>[
    SliverPadding(
      padding: const EdgeInsets.all(20.0),
      sliver: SliverList(
        delegate: SliverChildListDelegate(
          <Widget>[
            const Text("I'm dedicating every day to you"),
            const Text('Domestic life was never quite my style'),
            const Text('When you smile, you knock me out, I fall apart'),
            const Text('And I thought I was so smart'),
          ],
        ),
      ),
    ),
  ],
)
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: const Text('Empty List Test')),
    body: itemCount > 0
      ? ListView.builder(
          itemCount: itemCount,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              title: Text('Item ${index + 1}'),
            );
          },
        )
      : const Center(child: Text('No items')),
  );
}
GridView.count(
  primary: false,
  padding: const EdgeInsets.all(20),
  crossAxisSpacing: 10,
  mainAxisSpacing: 10,
  crossAxisCount: 2,
  children: <Widget>[
    Container(
      padding: const EdgeInsets.all(8),
      color: Colors.teal[100],
      child: const Text("He'd have you all unravel at the"),
    ),
    Container(
      padding: const EdgeInsets.all(8),
      color: Colors.teal[200],
      child: const Text('Heed not the rabble'),
    ),
    Container(
      padding: const EdgeInsets.all(8),
      color: Colors.teal[300],
      child: const Text('Sound of screams but the'),
    ),
    Container(
      padding: const EdgeInsets.all(8),
      color: Colors.teal[400],
      child: const Text('Who scream'),
    ),
    Container(
      padding: const EdgeInsets.all(8),
      color: Colors.teal[500],
      child: const Text('Revolution is coming...'),
    ),
    Container(
      padding: const EdgeInsets.all(8),
      color: Colors.teal[600],
      child: const Text('Revolution, they...'),
    ),
  ],
)
CustomScrollView(
  primary: false,
  slivers: <Widget>[
    SliverPadding(
      padding: const EdgeInsets.all(20),
      sliver: SliverGrid.count(
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        crossAxisCount: 2,
        children: <Widget>[
          Container(
            padding: const EdgeInsets.all(8),
            color: Colors.green[100],
            child: const Text("He'd have you all unravel at the"),
          ),
          Container(
            padding: const EdgeInsets.all(8),
            color: Colors.green[200],
            child: const Text('Heed not the rabble'),
          ),
          Container(
            padding: const EdgeInsets.all(8),
            color: Colors.green[300],
            child: const Text('Sound of screams but the'),
          ),
          Container(
            padding: const EdgeInsets.all(8),
            color: Colors.green[400],
            child: const Text('Who scream'),
          ),
          Container(
            padding: const EdgeInsets.all(8),
            color: Colors.green[500],
            child: const Text('Revolution is coming...'),
          ),
          Container(
            padding: const EdgeInsets.all(8),
            color: Colors.green[600],
            child: const Text('Revolution, they...'),
          ),
        ],
      ),
    ),
  ],
)
Widget myWidget(BuildContext context) {
  return MediaQuery.removePadding(
    context: context,
    removeTop: true,
    child: GridView.builder(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
      ),
      itemCount: 300,
      itemBuilder: (BuildContext context, int index) {
        return Card(
          color: Colors.amber,
          child: Center(child: Text('$index')),
        );
      }
    ),
  );
}

lib/src/widgets/scrollbar.dart

MaterialApp(
  scrollBehavior: const MaterialScrollBehavior()
    .copyWith(scrollbars: false),
  home: Scaffold(
    appBar: AppBar(title: const Text('Home')),
  ),
)

lib/src/widgets/selectable_region.dart

MaterialApp(
  home: SelectableRegion(
    selectionControls: materialTextSelectionControls,
    child: Scaffold(
      appBar: AppBar(title: const Text('Flutter Code Sample')),
      body: ListView(
        children: const <Widget>[
          Text('Item 0', style: TextStyle(fontSize: 50.0)),
          Text('Item 1', style: TextStyle(fontSize: 50.0)),
        ],
      ),
    ),
  ),
)
Actions.invoke(key.currentContext!, const SelectAllTextIntent(SelectionChangedCause.keyboard));

lib/src/widgets/sliver.dart

SliverFixedExtentList(
  itemExtent: 50.0,
  delegate: SliverChildBuilderDelegate(
    (BuildContext context, int index) {
      return Container(
        alignment: Alignment.center,
        color: Colors.lightBlue[100 * (index % 9)],
        child: Text('list item $index'),
      );
    },
  ),
)
SliverGrid.builder(
  gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
    maxCrossAxisExtent: 200.0,
    mainAxisSpacing: 10.0,
    crossAxisSpacing: 10.0,
    childAspectRatio: 4.0,
  ),
  itemCount: 20,
  itemBuilder: (BuildContext context, int index) {
    return Container(
      alignment: Alignment.center,
      color: Colors.teal[100 * (index % 9)],
      child: Text('grid item $index'),
    );
  },
)

lib/src/widgets/snapshot_widget.dart

void paint(PaintingContext context, Offset offset, Size size, ui.Image image, double pixelRatio) {
  const double radians = 0.5; // Could be driven by an animation.
  final Matrix4 transform = Matrix4.rotationZ(radians);
  context.canvas.transform(transform.storage);
  final Rect src = Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble());
  final Rect dst = Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height);
  final Paint paint = Paint()
    ..filterQuality = FilterQuality.medium;
  context.canvas.drawImageRect(image, src, dst, paint);
}

lib/src/widgets/spacer.dart

const Row(
  children: <Widget>[
    Text('Begin'),
    Spacer(), // Defaults to a flex of one.
    Text('Middle'),
    // Gives twice the space between Middle and End than Begin and Middle.
    Spacer(flex: 2),
    Text('End'),
  ],
)

lib/src/widgets/text.dart

Container(
  width: 100,
  decoration: BoxDecoration(border: Border.all()),
  child: const Text(
    'Hello, how are you?',
    overflow: TextOverflow.ellipsis,
  ),
)
const Text(
  'Hello, how are you?',
  overflow: TextOverflow.fade,
  maxLines: 1,
)
const Text(
  'Hello, how are you?',
  overflow: TextOverflow.fade,
  softWrap: false,
)
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)),
    ],
  ),
)

lib/src/widgets/widget_inspector.dart

extension PaddingModifier on Widget {
  
  Widget padding(EdgeInsetsGeometry padding) {
    return Padding(padding: padding, child: this);
  }
}
// continuing from previous example...
const Text('Hello World!')
    .padding(const EdgeInsets.all(8));

lib/src/widgets/widget_span.dart

const Text.rich(
  TextSpan(
    children: <InlineSpan>[
      TextSpan(text: 'Flutter is'),
      WidgetSpan(
        child: SizedBox(
          width: 120,
          height: 50,
          child: Card(
            child: Center(
              child: Text('Hello World!')
            )
          ),
        )
      ),
      TextSpan(text: 'the best!'),
    ],
  )
)
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐