Flutter Demo

文章目录

前言

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

正则查找

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

bash 复制代码
/// ```dart\s*\n(?:/// .*\n)*?/// ```

index

bash 复制代码
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

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

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

lib/src/animation/tween_sequence.dart

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

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

lib/src/cupertino

lib/src/cupertino/app.dart

dart 复制代码
const CupertinoApp(
  home: CupertinoPageScaffold(
    navigationBar: CupertinoNavigationBar(
      middle: Text('Home'),
    ),
    child: Center(child: Icon(CupertinoIcons.share)),
  ),
  debugShowCheckedModeBanner: false,
)
dart 复制代码
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)),
      );
    }
  },
)
dart 复制代码
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

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

lib/src/cupertino/debug.dart

dart 复制代码
assert(debugCheckHasCupertinoLocalizations(context));

lib/src/cupertino/icons.dart

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

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

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

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

lib/src/foundation/assertions.dart

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

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

dart 复制代码
assert(() {
  // ...debug-only code here...
  return true;
}());

lib/src/foundation/diagnostics.dart

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

lib/src/foundation/print.dart

dart 复制代码
if (kDebugMode) {
  debugPrint('A useful message');
}

lib/src/foundation/stack_frame.dart

dart 复制代码
final List<StackFrame> currentFrames = StackFrame.fromStackTrace(StackTrace.current);

lib/src/gestures

lib/src/gestures/events.dart

dart 复制代码
assert(smallestButton(0x01) == 0x01);
assert(smallestButton(0x11) == 0x01);
assert(smallestButton(0x10) == 0x10);
assert(smallestButton(0) == 0);
dart 复制代码
  assert(isSingleButton(0x1));
  assert(!isSingleButton(0x11));
  assert(!isSingleButton(0));

lib/src/gestures/gesture_details.dart

dart 复制代码
void handlePositionedGestures(PositionedGestureDetails details) {
  // Handle the positional information of the gesture details.
}

lib/src/gestures/pointer_signal_resolver.dart

dart 复制代码
void handleSignalEvent(PointerSignalEvent event) {
  GestureBinding.instance.pointerSignalResolver.register(event, (PointerSignalEvent event) {
    // handle the event...
  });
}

lib/src/gestures/tap_and_drag.dart

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

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

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

lib/src/material/banner.dart

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

lib/src/material/bottom_app_bar.dart

dart 复制代码
Scaffold(
  bottomNavigationBar: BottomAppBar(
    color: Colors.white,
    child: bottomAppBarContents,
  ),
  floatingActionButton: const FloatingActionButton(onPressed: null),
)

lib/src/material/button_bar.dart

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: () {}),
  ],
);
dart 复制代码
// 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

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: () {
    // ...
  },
),
dart 复制代码
ElevatedButton(
  style: const ButtonStyle(
    backgroundColor: WidgetStatePropertyAll<Color>(Colors.green),
  ),
  child: const Text('Let me play among the stars'),
  onPressed: () {
    // ...
  },
),
dart 复制代码
TextButton(
  style: TextButton.styleFrom(foregroundColor: Colors.green),
  child: const Text('Let me see what spring is like'),
  onPressed: () {
    // ...
  },
),
dart 复制代码
MaterialApp(
  theme: ThemeData(
    textButtonTheme: TextButtonThemeData(
      style: TextButton.styleFrom(foregroundColor: Colors.green),
    ),
  ),
  home: const MyAppHome(),
),

lib/src/material/carousel.dart

dart 复制代码
Scaffold(
  body: CarouselView(
    scrollDirection: Axis.vertical,
    itemExtent: double.infinity,
    children: List<Widget>.generate(10, (int index) {
      return Center(child: Text('Item $index'));
    }),
  ),
),
dart 复制代码
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

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

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

lib/src/material/circle_avatar.dart

dart 复制代码
CircleAvatar(
  backgroundImage: NetworkImage(userAvatarUrl),
)
dart 复制代码
CircleAvatar(
  backgroundColor: Colors.brown.shade800,
  child: const Text('AH'),
)

lib/src/material/colors.dart

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

lib/src/material/debug.dart

dart 复制代码
assert(debugCheckHasMaterial(context));
dart 复制代码
assert(debugCheckHasMaterialLocalizations(context));
dart 复制代码
assert(debugCheckHasScaffold(context));
dart 复制代码
assert(debugCheckHasScaffoldMessenger(context));

lib/src/material/dialog.dart

dart 复制代码
const Dialog(constraints: BoxConstraints(maxWidth: 560, minHeight: 280));
dart 复制代码
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();
            },
          ),
        ],
      );
    },
  );
}
dart 复制代码
SimpleDialogOption(
  onPressed: () { Navigator.pop(context, Department.treasury); },
  child: const Text('Treasury department'),
)
dart 复制代码
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

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

dart 复制代码
IconButton(
  iconSize: 72,
  icon: const Icon(Icons.favorite),
  onPressed: () {
    // ...
  },
),
dart 复制代码
IconButton(
  icon: const Icon(Icons.favorite, size: 72),
  onPressed: () {
    // ...
  },
),

lib/src/material/icons.dart

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

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'),
        )
      ),
    ),
  ),
)
dart 复制代码
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

dart 复制代码
ElevatedButton(
  style: ElevatedButton.styleFrom(splashFactory: InkSparkle.splashFactory),
  child: const Text('Sparkle!'),
  onPressed: () { },
)

lib/src/material/ink_well.dart

dart 复制代码
assert(debugCheckHasMaterial(context));
dart 复制代码
assert(debugCheckHasMaterial(context));

lib/src/material/list_tile.dart

dart 复制代码
const ColoredBox(
  color: Colors.green,
  child: Material(
    child: ListTile(
      title: Text('ListTile with red background'),
      tileColor: Colors.red,
    ),
  ),
)
dart 复制代码
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.'),
      ),
    ),
  ],
)
dart 复制代码
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 */ }
)
dart 复制代码
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

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'),
),
dart 复制代码
const SubmenuButton(
  menuStyle: MenuStyle(
    backgroundColor: WidgetStatePropertyAll<Color>(Colors.green),
  ),
  menuChildren: <Widget>[ /* ... */ ],
  child: Text('Let me play among the stars'),
),
dart 复制代码
MaterialApp(
  theme: ThemeData(
    menuTheme: const MenuThemeData(
      style: MenuStyle(backgroundColor: WidgetStatePropertyAll<Color>(Colors.red)),
    ),
  ),
  home: const MyAppHome(),
),

lib/src/material/no_splash.dart

dart 复制代码
ElevatedButton(
  style: ElevatedButton.styleFrom(
    splashFactory: NoSplash.splashFactory,
  ),
  onPressed: () { },
  child: const Text('No Splash'),
)

lib/src/material/popup_menu.dart

dart 复制代码
const PopupMenuItem<Menu>(
  value: Menu.itemOne,
  child: Text('Item 1'),
)
dart 复制代码
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

dart 复制代码
const ProgressIndicatorTheme(
  data: ProgressIndicatorThemeData(
    color: Colors.red,
  ),
  child: LinearProgressIndicator()
)

lib/src/material/radio_list_tile.dart

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

dart 复制代码
ListView(
  physics: const AlwaysScrollableScrollPhysics(),
  // ...
)

lib/src/material/scaffold.dart

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

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

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

lib/src/material/snack_bar.dart

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

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

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

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

dart 复制代码
const TextSelectionTheme(
  data: TextSelectionThemeData(
    cursorColor: Colors.blue,
    selectionHandleColor: Colors.lightBlue,
  ),
  child: TextField(),
)

lib/src/material/time_picker.dart

dart 复制代码
Future<TimeOfDay?> selectedTime = showTimePicker(
  initialTime: TimeOfDay.now(),
  context: context,
);
dart 复制代码
Future<TimeOfDay?> selectedTimeRTL = showTimePicker(
  context: context,
  initialTime: TimeOfDay.now(),
  builder: (BuildContext context, Widget? child) {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: child!,
    );
  },
);
dart 复制代码
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

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

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),
  ],
),
dart 复制代码
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),
  ],
),
dart 复制代码
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),
  ],
),
dart 复制代码
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

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

dart 复制代码
typography: Typography.material2018(platform: platform)

lib/src/painting

lib/src/painting/borders.dart

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

dart 复制代码
Border.all(width: 2.0, color: const Color(0xFFFFFFFF))
dart 复制代码
Border(bottom: BorderSide(color: Theme.of(context).dividerColor))
dart 复制代码
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

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

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

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

lib/src/painting/edge_insets.dart

dart 复制代码
const EdgeInsets.all(8.0)
dart 复制代码
const EdgeInsets.symmetric(vertical: 8.0)
dart 复制代码
const EdgeInsets.only(left: 40.0)

lib/src/painting/gradient.dart

dart 复制代码
const SweepGradient gradient = SweepGradient(
  colors: <Color>[Color(0xFFFFFFFF), Color(0xFF009900)],
  transform: GradientRotation(math.pi/4),
);
dart 复制代码
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);
}
dart 复制代码
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],
    ),
  )
)
dart 复制代码
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

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

lib/src/painting/image_resolution.dart

dart 复制代码
const AssetImage('icons/heart.png')
dart 复制代码
const AssetImage('icons/heart.png', package: 'my_icons')

lib/src/painting/inline_span.dart

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

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

dart 复制代码
const Text(
  'Hello, world!\nSecond line!',
  style: TextStyle(
    fontSize: 10,
    fontFamily: 'Raleway',
  ),
  strutStyle: StrutStyle(
    fontFamily: 'Roboto',
    fontSize: 30,
    height: 1.5,
  ),
)
dart 复制代码
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,
  ),
)
dart 复制代码
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,
  ),
)
dart 复制代码
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

dart 复制代码
const TextSpan(
  text: 'Hello world!',
  style: TextStyle(color: Colors.black),
)

lib/src/painting/text_style.dart

dart 复制代码
const Text(
  'No, we need bold strokes. We need this plan.',
  style: TextStyle(fontWeight: FontWeight.bold),
)
dart 复制代码
const Text(
  "Welcome to the present, we're running a real nation.",
  style: TextStyle(fontStyle: FontStyle.italic),
)
dart 复制代码
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)),
      ),
    ],
  ),
)
dart 复制代码
Text(
  "These are wise words, enterprising men quote 'em.",
  style: DefaultTextStyle.of(context).style.apply(fontSizeFactor: 2.0),
)
dart 复制代码
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),
)
dart 复制代码
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',
      ),
    ],
  ),
)
dart 复制代码
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],
      ),
    ),
  ],
)
dart 复制代码
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,
        ],
      )
  ),
)
dart 复制代码
const TextStyle(fontFamily: 'Raleway')
dart 复制代码
const TextStyle(fontFamily: 'Raleway', package: 'my_package')
dart 复制代码
const TextStyle(fontFamily: 'Raleway')
dart 复制代码
const TextStyle(
  fontFamily: 'Raleway',
  fontFamilyFallback: <String>[
    'Noto Sans CJK SC',
    'Noto Color Emoji',
  ],
)

lib/src/physics

lib/src/physics/gravity_simulation.dart

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

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

dart 复制代码
AxisDirection get axis => _axis;
AxisDirection _axis = AxisDirection.down; // or initialized in constructor
set axis(AxisDirection value) {
  if (value == _axis) {
    return;
  }
  _axis = value;
  markNeedsLayout();
}
dart 复制代码
class RenderFoo extends RenderBox
  with RenderObjectWithChildMixin<RenderBar> {
  // ...
}
dart 复制代码
class FooParentData extends ContainerBoxParentData<RenderBox> {
  // (any fields you might need for these children)
}
dart 复制代码
// continuing from previous example...
class RenderFoo extends RenderBox with
  ContainerRenderObjectMixin<RenderBox, FooParentData>,
  RenderBoxContainerDefaultsMixin<RenderBox, FooParentData> {
  // ...
}
dart 复制代码
// 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

dart 复制代码
SemanticsLabelBuilder builder = SemanticsLabelBuilder()
  ..addPart('Hello')
  ..addPart('world');
String label = builder.build(); // "Hello world"
dart 复制代码
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

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

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

lib/src/services/text_formatter.dart

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

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,
      )
    ],
  );
}
dart 复制代码
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

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')),
        );
      }
    ),
  );
}
dart 复制代码
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

dart 复制代码
int highlightedIndex = AutocompleteHighlightedOption.of(context);

lib/src/widgets/basic.dart

dart 复制代码
Directionality(
  textDirection: TextDirection.rtl,
  child: Container(
    margin: const EdgeInsetsDirectional.only(start: 8),
    color: Colors.blue,
  ),
)
dart 复制代码
Opacity(
  opacity: _visible ? 1.0 : 0.0,
  child: const Text("Now you see me, now you don't!"),
)
dart 复制代码
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
)
dart 复制代码
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),
  ),
)
dart 复制代码
 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'),
             ),
           ),
         );
      }
    ),
  );
}
dart 复制代码
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'),
          ),
        ),
      ),
    ),
  ],
)
dart 复制代码
 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),
         ),
       ),
     ],
   );
 }
dart 复制代码
 Widget buildFilter() {
   return ImageFiltered(
     imageFilter: ui.ImageFilter.blur(sigmaX: 6, sigmaY: 6),
     child: Image.asset('image.png'),
   );
 }
dart 复制代码
CustomPaint(
  painter: Sky(),
  child: const Center(
    child: Text(
      'Once upon a time...',
      style: TextStyle(
        fontSize: 40.0,
        fontWeight: FontWeight.w900,
        color: Color(0xFFFFFFFF),
      ),
    ),
  ),
)
dart 复制代码
ClipRect(
  child: Align(
    alignment: Alignment.topCenter,
    heightFactor: 0.5,
    child: Image.network(userAvatarUrl),
  ),
)
dart 复制代码
ClipOval(
  child: Image.asset('images/cat.png'),
)
dart 复制代码
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!'),
    ),
  ),
)
dart 复制代码
const RotatedBox(
  quarterTurns: 3,
  child: Text('Hello World!'),
)
dart 复制代码
const Card(
  child: Padding(
    padding: EdgeInsets.all(16.0),
    child: Text('Hello World!'),
  ),
)
dart 复制代码
Center(
  child: Container(
    height: 120.0,
    width: 120.0,
    color: Colors.blue[50],
    child: const Align(
      alignment: Alignment.topRight,
      child: FlutterLogo(
        size: 60,
      ),
    ),
  ),
)
dart 复制代码
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,
      ),
    ),
  ),
)
dart 复制代码
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,
      ),
    ),
  ),
)
dart 复制代码
const SizedBox(
  width: 200.0,
  height: 300.0,
  child: Card(child: Text('Hello World!')),
)
dart 复制代码
ConstrainedBox(
  constraints: const BoxConstraints.expand(),
  child: const Card(child: Text('Hello World!')),
)
dart 复制代码
Container(
  constraints: const BoxConstraints(minHeight: 40, maxHeight: 100),
  alignment: Alignment.center,
  child: const ConstraintsTransformBox(
    constraintsTransform: ConstraintsTransformBox.maxHeightUnconstrained,
    child: Card(child: Text('Hello World!')),
  )
)
dart 复制代码
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,
    ),
  ],
)
dart 复制代码
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),
        ),
      ),
    ],
  ),
)
dart 复制代码
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(),
      ),
    ),
  ],
)
dart 复制代码
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),
  ],
)
dart 复制代码
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),
  ],
)
dart 复制代码
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),
  ],
)
dart 复制代码
const Column(
  children: <Widget>[
    Text('Deliver features faster'),
    Text('Craft beautiful UIs'),
    Expanded(
      child: FittedBox(
        child: FlutterLogo(),
      ),
    ),
  ],
)
dart 复制代码
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)),
  ],
)
dart 复制代码
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'),
    ),
  ],
)
dart 复制代码
RichText(
  text: TextSpan(
    text: 'Hello ',
    style: DefaultTextStyle.of(context).style,
    children: const <TextSpan>[
      TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),
      TextSpan(text: ' world!'),
    ],
  ),
)
dart 复制代码
RichText(
  text: const TextSpan(text: 'Hello'),
  selectionRegistrar: SelectionContainer.maybeOf(context),
  selectionColor: const Color(0xAF6694e8),
)
dart 复制代码
class TestAssetBundle extends CachingAssetBundle {
  @override
  Future<ByteData> load(String key) async {
    if (key == 'resources/test') {
      return ByteData.sublistView(utf8.encode('Hello World!'));
    }
    return ByteData(0);
  }
}
dart 复制代码
// continuing from previous example...
await tester.pumpWidget(
  MaterialApp(
    home: DefaultAssetBundle(
      bundle: TestAssetBundle(),
      child: const TestWidget(),
    ),
  ),
);
dart 复制代码
MergeSemantics(
  child: Row(
    children: <Widget>[
      Checkbox(
        value: true,
        onChanged: (bool? value) {},
      ),
      const Text('Settings'),
    ],
  ),
)
dart 复制代码
ListView(
  addSemanticIndexes: false,
  semanticChildCount: 2,
  children: const <Widget>[
    IndexedSemantics(index: 0, child: Text('First')),
    Spacer(),
    IndexedSemantics(index: 1, child: Text('Second')),
    Spacer(),
  ],
)
dart 复制代码
class Foo extends StatelessWidget {
  const Foo({super.key});
  @override
  Widget build(BuildContext context) => const Text('foo');
}
dart 复制代码
// continuing from previous example...
const Center(child: Foo())
dart 复制代码
Center(
  child: Builder(
    builder: (BuildContext context) => const Text('foo'),
  ),
)
dart 复制代码
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'),
      )
    ),
  );
}
dart 复制代码
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'),
          ),
        );
      },
    ),
  );
}
dart 复制代码
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

dart 复制代码
runWidget(
  View(
    view: myFlutterView,
    child: const MyApp(),
  ),
);

lib/src/widgets/container.dart

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],
    ),
  ),
)
dart 复制代码
Center(
  child: Container(
    margin: const EdgeInsets.all(10.0),
    color: Colors.amber[600],
    width: 48.0,
    height: 48.0,
  ),
)
dart 复制代码
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

dart 复制代码
assert(!debugItemsHaveDuplicateKeys(items));
dart 复制代码
assert(debugCheckHasTable(context));
dart 复制代码
assert(debugCheckHasMediaQuery(context));
dart 复制代码
assert(debugCheckHasDirectionality(context));
dart 复制代码
assert(debugCheckHasWidgetsLocalizations(context));
dart 复制代码
assert(debugCheckHasOverlay(context));

lib/src/widgets/default_text_editing_shortcuts.dart

dart 复制代码
@override
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

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

lib/src/widgets/fade_in_image.dart

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

dart 复制代码
Actions.invoke(context, RequestFocusIntent(focusNode));

lib/src/widgets/framework.dart

dart 复制代码
class Bar {
  final Object? bar = kDebugMode ? Object() : null;
}
dart 复制代码
class _MyKey extends GlobalObjectKey {
  const _MyKey(super.value);
}
dart 复制代码
@override
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);
                          },
                        )
                      ],
                    ),
                  ),
                );
              },
            );
          },
        );
      },
    )
  );
}
dart 复制代码
  @override
  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

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

dart 复制代码
@staticIconProvider
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

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

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

lib/src/widgets/localizations.dart

dart 复制代码
// continuing from previous example...
MyLocalizations.of(context).title()

lib/src/widgets/lookup_boundary.dart

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

lib/src/widgets/navigator.dart

dart 复制代码
void main() {
  runApp(const MaterialApp(home: MyAppHome()));
}
dart 复制代码
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);
          },
        ),
      ),
    );
  },
));
dart 复制代码
Navigator.pop(context);
dart 复制代码
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')),
    },
  ));
}
dart 复制代码
Navigator.pushNamed(context, '/b');
dart 复制代码
bool? value = await Navigator.push(context, MaterialPageRoute<bool>(
  builder: (BuildContext context) {
    return Center(
      child: GestureDetector(
        child: const Text('OK'),
        onTap: () { Navigator.pop(context, true); }
      ),
    );
  }
));
dart 复制代码
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

dart 复制代码
List<PlatformMenuItem> menus = <PlatformMenuItem>[ /* Define menus... */ ];
WidgetsBinding.instance.platformMenuDelegate.setMenus(menus);

lib/src/widgets/platform_view.dart

dart 复制代码
// In a `build` method...
HtmlElementView.fromTagName(
  tagName: 'div',
  onElementCreated: myOnElementCreated,
);
dart 复制代码
// In a `build` method...
const HtmlElementView(
  viewType: 'my-view-type',
  onPlatformViewCreated: myOnPlatformViewCreated,
  creationParams: <String, Object?>{
    'key': 'someValue',
  },
);
dart 复制代码
class FooPlatformView extends StatelessWidget {
  const FooPlatformView({super.key});
  @override
  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

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) {},
     ),
   ],
 )
)
dart 复制代码
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

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

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

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,
       ),
     ),
  ],
)
dart 复制代码
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

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

lib/src/widgets/scroll_physics.dart

dart 复制代码
const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics())
dart 复制代码
ScrollPhysics physics = const BouncingScrollPhysics();
// ...
final ScrollPhysics mergedPhysics = physics.applyTo(const AlwaysScrollableScrollPhysics());
dart 复制代码
const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics())

lib/src/widgets/scroll_view.dart

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'),
          );
        },
      ),
    ),
  ],
)
dart 复制代码
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')),
    ),
  ],
)
dart 复制代码
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'),
  ],
)
dart 复制代码
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'),
          ],
        ),
      ),
    ),
  ],
)
dart 复制代码
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')),
  );
}
dart 复制代码
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...'),
    ),
  ],
)
dart 复制代码
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...'),
          ),
        ],
      ),
    ),
  ],
)
dart 复制代码
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

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

lib/src/widgets/selectable_region.dart

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)),
        ],
      ),
    ),
  ),
)
dart 复制代码
Actions.invoke(key.currentContext!, const SelectAllTextIntent(SelectionChangedCause.keyboard));

lib/src/widgets/sliver.dart

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'),
      );
    },
  ),
)
dart 复制代码
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

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

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

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

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

lib/src/widgets/widget_span.dart

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!'),
    ],
  )
)
相关推荐
2501_944525542 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 账户详情页面
android·java·开发语言·前端·javascript·flutter
2601_949857432 小时前
Flutter for OpenHarmony Web开发助手App实战:快捷键参考
前端·flutter
福大大架构师每日一题2 小时前
ComfyUI v0.11.1正式发布:新增开发者专属节点支持、API节点强化、Python 3.14兼容性更新等全方位优化!
开发语言·python
wangdaoyin20102 小时前
若依vue2前后端分离集成flowable
开发语言·前端·javascript
天天进步20153 小时前
AI Agent 与流式处理:Motia 在生成式 AI 时代的后端范式
javascript
心柠3 小时前
vue3相关知识总结
前端·javascript·vue.js
向阳开的夏天3 小时前
麒麟V10源码编译QT5.6.3 (x86 & arm64)
开发语言·qt
Evand J3 小时前
【MATLAB例程】TOA和TDOA混合定位,适用于二维平面的高精度定位。锚点数量、位置、测量噪声可自行调节
开发语言·matlab·定位·tdoa
mocoding3 小时前
flutter通信小能手pigeon三方库已完成鸿蒙化适配
flutter·华为·harmonyos