Auto-format Framework (#160545)

This auto-formats all *.dart files in the repository outside of the
`engine` subdirectory and enforces that these files stay formatted with
a presubmit check.

**Reviewers:** Please carefully review all the commits except for the
one titled "formatted". The "formatted" commit was auto-generated by
running `dev/tools/format.sh -a -f`. The other commits were hand-crafted
to prepare the repo for the formatting change. I recommend reviewing the
commits one-by-one via the "Commits" tab and avoiding Github's "Files
changed" tab as it will likely slow down your browser because of the
size of this PR.

---------

Co-authored-by: Kate Lovett <katelovett@google.com>
Co-authored-by: LongCatIsLooong <31859944+LongCatIsLooong@users.noreply.github.com>
This commit is contained in:
Michael Goderbauer
2024-12-19 12:06:21 -08:00
committed by GitHub
parent 8e0993eda8
commit 5491c8c146
4411 changed files with 455108 additions and 415991 deletions

View File

@@ -10,10 +10,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MaterialApp(
title: 'Actions Demo',
home: FocusDemo(),
));
runApp(const MaterialApp(title: 'Actions Demo', home: FocusDemo()));
}
/// A class that can hold invocation information that an [UndoableAction] can
@@ -22,11 +19,7 @@ void main() {
/// Instances of this class are returned from [UndoableAction]s and placed on
/// the undo stack when they are invoked.
class Memento extends Object with Diagnosticable {
const Memento({
required this.name,
required this.undo,
required this.redo,
});
const Memento({required this.name, required this.undo, required this.redo});
/// Returns true if this Memento can be used to undo.
///
@@ -190,7 +183,9 @@ class UndoAction extends Action<UndoIntent> {
if (buildContext == null) {
return;
}
final UndoableActionDispatcher manager = Actions.of(primaryFocus?.context ?? FocusDemo.appKey.currentContext!) as UndoableActionDispatcher;
final UndoableActionDispatcher manager =
Actions.of(primaryFocus?.context ?? FocusDemo.appKey.currentContext!)
as UndoableActionDispatcher;
manager.undo();
}
}
@@ -223,18 +218,22 @@ class RedoAction extends Action<RedoIntent> {
}
/// An action that can be undone.
abstract class UndoableAction<T extends Intent> extends Action<T> { }
abstract class UndoableAction<T extends Intent> extends Action<T> {}
class UndoableFocusActionBase<T extends Intent> extends UndoableAction<T> {
@override
@mustCallSuper
Memento invoke(T intent) {
final FocusNode? previousFocus = primaryFocus;
return Memento(name: previousFocus!.debugLabel!, undo: () {
previousFocus.requestFocus();
}, redo: () {
return invoke(intent);
});
return Memento(
name: previousFocus!.debugLabel!,
undo: () {
previousFocus.requestFocus();
},
redo: () {
return invoke(intent);
},
);
}
}
@@ -384,8 +383,19 @@ class _FocusDemoState extends State<FocusDemo> {
policy: ReadingOrderTraversalPolicy(),
child: Shortcuts(
shortcuts: <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.keyZ, meta: Platform.isMacOS, control: !Platform.isMacOS, shift: true): const RedoIntent(),
SingleActivator(LogicalKeyboardKey.keyZ, meta: Platform.isMacOS, control: !Platform.isMacOS): const UndoIntent(),
SingleActivator(
LogicalKeyboardKey.keyZ,
meta: Platform.isMacOS,
control: !Platform.isMacOS,
shift: true,
):
const RedoIntent(),
SingleActivator(
LogicalKeyboardKey.keyZ,
meta: Platform.isMacOS,
control: !Platform.isMacOS,
):
const UndoIntent(),
},
child: FocusScope(
key: FocusDemo.appKey,
@@ -394,68 +404,70 @@ class _FocusDemoState extends State<FocusDemo> {
child: DefaultTextStyle(
style: textTheme.headlineMedium!,
child: Scaffold(
appBar: AppBar(
title: const Text('Actions Demo'),
),
appBar: AppBar(title: const Text('Actions Demo')),
body: Center(
child: Builder(builder: (BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(name: 'One'),
DemoButton(name: 'Two'),
DemoButton(name: 'Three'),
],
),
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(name: 'Four'),
DemoButton(name: 'Five'),
DemoButton(name: 'Six'),
],
),
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(name: 'Seven'),
DemoButton(name: 'Eight'),
DemoButton(name: 'Nine'),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: canUndo
? () {
Actions.invoke(context, const UndoIntent());
}
: null,
child: const Text('UNDO'),
child: Builder(
builder: (BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(name: 'One'),
DemoButton(name: 'Two'),
DemoButton(name: 'Three'),
],
),
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(name: 'Four'),
DemoButton(name: 'Five'),
DemoButton(name: 'Six'),
],
),
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(name: 'Seven'),
DemoButton(name: 'Eight'),
DemoButton(name: 'Nine'),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed:
canUndo
? () {
Actions.invoke(context, const UndoIntent());
}
: null,
child: const Text('UNDO'),
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: canRedo
? () {
Actions.invoke(context, const RedoIntent());
}
: null,
child: const Text('REDO'),
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed:
canRedo
? () {
Actions.invoke(context, const RedoIntent());
}
: null,
child: const Text('REDO'),
),
),
),
],
),
],
);
}),
],
),
],
);
},
),
),
),
),

View File

@@ -9,12 +9,7 @@ class AnimatedIconsTestApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Animated Icons Test',
home: Scaffold(
body: IconsList(),
),
);
return const MaterialApp(title: 'Animated Icons Test', home: Scaffold(body: IconsList()));
}
}
@@ -39,23 +34,26 @@ class IconSampleRow extends StatefulWidget {
}
class IconSampleRowState extends State<IconSampleRow> with SingleTickerProviderStateMixin {
late final AnimationController progress = AnimationController(vsync: this, duration: const Duration(milliseconds: 300));
late final AnimationController progress = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 300),
);
@override
Widget build(BuildContext context) {
return ListTile(
leading: InkWell(
onTap: () { progress.forward(from: 0.0); },
child: AnimatedIcon(
icon: widget.sample.icon,
progress: progress,
color: Colors.lightBlue,
),
onTap: () {
progress.forward(from: 0.0);
},
child: AnimatedIcon(icon: widget.sample.icon, progress: progress, color: Colors.lightBlue),
),
title: Text(widget.sample.description),
subtitle: Slider(
value: progress.value,
onChanged: (double v) { progress.animateTo(v, duration: Duration.zero); },
onChanged: (double v) {
progress.animateTo(v, duration: Duration.zero);
},
),
);
}
@@ -77,7 +75,7 @@ class IconSampleRowState extends State<IconSampleRow> with SingleTickerProviderS
}
}
const List<IconSample> samples = <IconSample> [
const List<IconSample> samples = <IconSample>[
IconSample(AnimatedIcons.arrow_menu, 'arrow_menu'),
IconSample(AnimatedIcons.menu_arrow, 'menu_arrow'),

View File

@@ -7,8 +7,7 @@ import 'dart:math';
import 'package:flutter/material.dart';
class CardModel {
CardModel(this.value, this.height) :
textController = TextEditingController(text: 'Item $value');
CardModel(this.value, this.height) : textController = TextEditingController(text: 'Item $value');
int value;
double height;
@@ -25,19 +24,46 @@ class CardCollection extends StatefulWidget {
}
class CardCollectionState extends State<CardCollection> {
static const TextStyle cardLabelStyle =
TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold);
static const TextStyle cardLabelStyle = TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
);
// TODO(hansmuller): need a local image asset
static const String _sunshineURL = 'http://www.walltor.com/images/wallpaper/good-morning-sunshine-58540.jpg';
static const String _sunshineURL =
'http://www.walltor.com/images/wallpaper/good-morning-sunshine-58540.jpg';
static const double kCardMargins = 8.0;
static const double kFixedCardHeight = 100.0;
static const List<double> _cardHeights = <double>[
48.0, 63.0, 85.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0, 63.0, 85.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0, 63.0, 85.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0,
63.0,
85.0,
146.0,
60.0,
55.0,
84.0,
96.0,
50.0,
48.0,
63.0,
85.0,
146.0,
60.0,
55.0,
84.0,
96.0,
50.0,
48.0,
63.0,
85.0,
146.0,
60.0,
55.0,
84.0,
96.0,
50.0,
];
MaterialColor _primaryColor = Colors.deepPurple;
@@ -53,13 +79,10 @@ class CardCollectionState extends State<CardCollection> {
if (_fixedSizeCards) {
return;
}
_cardModels = List<CardModel>.generate(
_cardModels.length,
(int i) {
_cardModels[i].height = _editable ? max(_cardHeights[i], 60.0) : _cardHeights[i];
return _cardModels[i];
},
);
_cardModels = List<CardModel>.generate(_cardModels.length, (int i) {
_cardModels[i].height = _editable ? max(_cardHeights[i], 60.0) : _cardHeights[i];
return _cardModels[i];
});
}
void _initVariableSizedCardModels() {
@@ -71,10 +94,7 @@ class CardCollectionState extends State<CardCollection> {
void _initFixedSizedCardModels() {
const int cardCount = 27;
_cardModels = List<CardModel>.generate(
cardCount,
(int i) => CardModel(i, kFixedCardHeight),
);
_cardModels = List<CardModel>.generate(cardCount, (int i) => CardModel(i, kFixedCardHeight));
}
void _initCardModels() {
@@ -109,24 +129,76 @@ class CardCollectionState extends State<CardCollection> {
buildDrawerCheckbox('Make card labels editable', _editable, _toggleEditable),
buildDrawerCheckbox('Fixed size cards', _fixedSizeCards, _toggleFixedSizeCards),
buildDrawerCheckbox('Let the sun shine', _sunshine, _toggleSunshine),
buildDrawerCheckbox('Vary font sizes', _varyFontSizes, _toggleVaryFontSizes, enabled: !_editable),
buildDrawerCheckbox(
'Vary font sizes',
_varyFontSizes,
_toggleVaryFontSizes,
enabled: !_editable,
),
const Divider(),
buildDrawerColorRadioItem('Deep Purple', Colors.deepPurple, _primaryColor, _selectColor),
buildDrawerColorRadioItem(
'Deep Purple',
Colors.deepPurple,
_primaryColor,
_selectColor,
),
buildDrawerColorRadioItem('Green', Colors.green, _primaryColor, _selectColor),
buildDrawerColorRadioItem('Amber', Colors.amber, _primaryColor, _selectColor),
buildDrawerColorRadioItem('Teal', Colors.teal, _primaryColor, _selectColor),
const Divider(),
buildDrawerDirectionRadioItem('Dismiss horizontally', DismissDirection.horizontal, _dismissDirection, _changeDismissDirection, icon: Icons.code),
buildDrawerDirectionRadioItem('Dismiss left', DismissDirection.endToStart, _dismissDirection, _changeDismissDirection, icon: Icons.arrow_back),
buildDrawerDirectionRadioItem('Dismiss right', DismissDirection.startToEnd, _dismissDirection, _changeDismissDirection, icon: Icons.arrow_forward),
buildDrawerDirectionRadioItem(
'Dismiss horizontally',
DismissDirection.horizontal,
_dismissDirection,
_changeDismissDirection,
icon: Icons.code,
),
buildDrawerDirectionRadioItem(
'Dismiss left',
DismissDirection.endToStart,
_dismissDirection,
_changeDismissDirection,
icon: Icons.arrow_back,
),
buildDrawerDirectionRadioItem(
'Dismiss right',
DismissDirection.startToEnd,
_dismissDirection,
_changeDismissDirection,
icon: Icons.arrow_forward,
),
const Divider(),
buildFontRadioItem('Left-align text', TextAlign.left, _textAlign, _changeTextAlign, icon: Icons.format_align_left, enabled: !_editable),
buildFontRadioItem('Center-align text', TextAlign.center, _textAlign, _changeTextAlign, icon: Icons.format_align_center, enabled: !_editable),
buildFontRadioItem('Right-align text', TextAlign.right, _textAlign, _changeTextAlign, icon: Icons.format_align_right, enabled: !_editable),
buildFontRadioItem(
'Left-align text',
TextAlign.left,
_textAlign,
_changeTextAlign,
icon: Icons.format_align_left,
enabled: !_editable,
),
buildFontRadioItem(
'Center-align text',
TextAlign.center,
_textAlign,
_changeTextAlign,
icon: Icons.format_align_center,
enabled: !_editable,
),
buildFontRadioItem(
'Right-align text',
TextAlign.right,
_textAlign,
_changeTextAlign,
icon: Icons.format_align_right,
enabled: !_editable,
),
const Divider(),
ListTile(
leading: const Icon(Icons.dvr),
onTap: () { debugDumpApp(); debugDumpRenderTree(); },
onTap: () {
debugDumpApp();
debugDumpRenderTree();
},
title: const Text('Dump App to Console'),
),
],
@@ -184,22 +256,44 @@ class CardCollectionState extends State<CardCollection> {
});
}
Widget buildDrawerCheckbox(String label, bool value, void Function() callback, { bool enabled = true }) {
Widget buildDrawerCheckbox(
String label,
bool value,
void Function() callback, {
bool enabled = true,
}) {
return ListTile(
onTap: enabled ? callback : null,
title: Text(label),
trailing: Checkbox(
value: value,
onChanged: enabled ? (_) { callback(); } : null,
onChanged:
enabled
? (_) {
callback();
}
: null,
),
);
}
Widget buildDrawerColorRadioItem(String label, MaterialColor itemValue, MaterialColor currentValue, ValueChanged<MaterialColor?> onChanged, { IconData? icon, bool enabled = true }) {
Widget buildDrawerColorRadioItem(
String label,
MaterialColor itemValue,
MaterialColor currentValue,
ValueChanged<MaterialColor?> onChanged, {
IconData? icon,
bool enabled = true,
}) {
return ListTile(
leading: Icon(icon),
title: Text(label),
onTap: enabled ? () { onChanged(itemValue); } : null,
onTap:
enabled
? () {
onChanged(itemValue);
}
: null,
trailing: Radio<MaterialColor>(
value: itemValue,
groupValue: currentValue,
@@ -208,11 +302,23 @@ class CardCollectionState extends State<CardCollection> {
);
}
Widget buildDrawerDirectionRadioItem(String label, DismissDirection itemValue, DismissDirection currentValue, ValueChanged<DismissDirection?> onChanged, { IconData? icon, bool enabled = true }) {
Widget buildDrawerDirectionRadioItem(
String label,
DismissDirection itemValue,
DismissDirection currentValue,
ValueChanged<DismissDirection?> onChanged, {
IconData? icon,
bool enabled = true,
}) {
return ListTile(
leading: Icon(icon),
title: Text(label),
onTap: enabled ? () { onChanged(itemValue); } : null,
onTap:
enabled
? () {
onChanged(itemValue);
}
: null,
trailing: Radio<DismissDirection>(
value: itemValue,
groupValue: currentValue,
@@ -221,11 +327,23 @@ class CardCollectionState extends State<CardCollection> {
);
}
Widget buildFontRadioItem(String label, TextAlign itemValue, TextAlign currentValue, ValueChanged<TextAlign?> onChanged, { IconData? icon, bool enabled = true }) {
Widget buildFontRadioItem(
String label,
TextAlign itemValue,
TextAlign currentValue,
ValueChanged<TextAlign?> onChanged, {
IconData? icon,
bool enabled = true,
}) {
return ListTile(
leading: Icon(icon),
title: Text(label),
onTap: enabled ? () { onChanged(itemValue); } : null,
onTap:
enabled
? () {
onChanged(itemValue);
}
: null,
trailing: Radio<TextAlign>(
value: itemValue,
groupValue: currentValue,
@@ -236,14 +354,15 @@ class CardCollectionState extends State<CardCollection> {
AppBar _buildAppBar(BuildContext context) {
return AppBar(
actions: <Widget>[
Text(_dismissDirectionText(_dismissDirection)),
],
actions: <Widget>[Text(_dismissDirectionText(_dismissDirection))],
flexibleSpace: Container(
padding: const EdgeInsets.only(left: 72.0),
height: 128.0,
alignment: const Alignment(-1.0, 0.5),
child: Text('Swipe Away: ${_cardModels.length}', style: Theme.of(context).primaryTextTheme.titleLarge),
child: Text(
'Swipe Away: ${_cardModels.length}',
style: Theme.of(context).primaryTextTheme.titleLarge,
),
),
);
}
@@ -253,31 +372,32 @@ class CardCollectionState extends State<CardCollection> {
final Widget card = Dismissible(
key: ObjectKey(cardModel),
direction: _dismissDirection,
onDismissed: (DismissDirection direction) { dismissCard(cardModel); },
onDismissed: (DismissDirection direction) {
dismissCard(cardModel);
},
child: Card(
color: _primaryColor[cardModel.color],
child: Container(
height: cardModel.height,
padding: const EdgeInsets.all(kCardMargins),
child: _editable ?
Center(
child: TextField(
key: GlobalObjectKey(cardModel),
controller: cardModel.textController,
),
)
: DefaultTextStyle.merge(
style: cardLabelStyle.copyWith(
fontSize: _varyFontSizes ? 5.0 + index : null
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(cardModel.textController.text, textAlign: _textAlign),
],
),
),
child:
_editable
? Center(
child: TextField(
key: GlobalObjectKey(cardModel),
controller: cardModel.textController,
),
)
: DefaultTextStyle.merge(
style: cardLabelStyle.copyWith(fontSize: _varyFontSizes ? 5.0 + index : null),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(cardModel.textController.text, textAlign: _textAlign),
],
),
),
),
),
);
@@ -328,7 +448,8 @@ class CardCollectionState extends State<CardCollection> {
children: <Widget>[
leftArrowIcon,
Expanded(
child: Text(backgroundMessage,
child: Text(
backgroundMessage,
style: backgroundTextStyle,
textAlign: TextAlign.center,
),
@@ -350,12 +471,11 @@ class CardCollectionState extends State<CardCollection> {
Shader _createShader(Rect bounds) {
return const LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: <Color>[Color(0x00FFFFFF), Color(0xFFFFFFFF)],
stops: <double>[0.1, 0.35],
)
.createShader(bounds);
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: <Color>[Color(0x00FFFFFF), Color(0xFFFFFFFF)],
stops: <double>[0.1, 0.35],
).createShader(bounds);
}
@override
@@ -382,21 +502,12 @@ class CardCollectionState extends State<CardCollection> {
);
return Theme(
data: ThemeData(
primarySwatch: _primaryColor,
),
child: Scaffold(
appBar: _buildAppBar(context),
drawer: _buildDrawer(),
body: body,
),
data: ThemeData(primarySwatch: _primaryColor),
child: Scaffold(appBar: _buildAppBar(context), drawer: _buildDrawer(), body: body),
);
}
}
void main() {
runApp(const MaterialApp(
title: 'Cards',
home: CardCollection(),
));
runApp(const MaterialApp(title: 'Cards', home: CardCollection()));
}

View File

@@ -14,9 +14,13 @@ class ColorDemoHome extends StatelessWidget {
body: ListView(
padding: const EdgeInsets.all(5.0),
children: <Widget>[
Image.network('https://flutter.github.io/assets-for-api-docs/assets/tests/colors/gbr.png'),
Image.network(
'https://flutter.github.io/assets-for-api-docs/assets/tests/colors/gbr.png',
),
Image.network('https://flutter.github.io/assets-for-api-docs/assets/tests/colors/tf.png'),
Image.network('https://flutter.github.io/assets-for-api-docs/assets/tests/colors/wide-gamut.png'),
Image.network(
'https://flutter.github.io/assets-for-api-docs/assets/tests/colors/wide-gamut.png',
),
const GradientRow(leftColor: Color(0xFFFF0000), rightColor: Color(0xFF00FF00)),
const GradientRow(leftColor: Color(0xFF0000FF), rightColor: Color(0xFFFFFF00)),
const GradientRow(leftColor: Color(0xFFFF0000), rightColor: Color(0xFF0000FF)),
@@ -43,7 +47,7 @@ class ColorDemoHome extends StatelessWidget {
}
class GradientRow extends StatelessWidget {
const GradientRow({ super.key, required this.rightColor, required this.leftColor });
const GradientRow({super.key, required this.rightColor, required this.leftColor});
final Color leftColor;
final Color rightColor;
@@ -56,7 +60,7 @@ class GradientRow extends StatelessWidget {
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: <Color>[ leftColor, rightColor ],
colors: <Color>[leftColor, rightColor],
),
),
);
@@ -64,22 +68,16 @@ class GradientRow extends StatelessWidget {
}
class ColorRow extends StatelessWidget {
const ColorRow({ super.key, required this.color });
const ColorRow({super.key, required this.color});
final Color color;
@override
Widget build(BuildContext context) {
return Container(
height: 100.0,
color: color,
);
return Container(height: 100.0, color: color);
}
}
void main() {
runApp(const MaterialApp(
title: 'Color Testing Demo',
home: ColorDemoHome(),
));
runApp(const MaterialApp(title: 'Color Testing Demo', home: ColorDemoHome()));
}

View File

@@ -28,10 +28,7 @@ class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyHomePage(),
);
return const MaterialApp(title: _title, home: MyHomePage());
}
}
@@ -114,13 +111,7 @@ class LabeledCheckbox extends StatelessWidget {
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Checkbox(
onChanged: onChanged,
value: value,
),
Text(label),
],
children: <Widget>[Checkbox(onChanged: onChanged, value: value), Text(label)],
);
}
}
@@ -164,8 +155,8 @@ class _OptionsState extends State<Options> {
String _densityToProfile(VisualDensity density) {
return switch (density) {
VisualDensity.standard => 'standard',
VisualDensity.compact => 'compact',
VisualDensity.standard => 'standard',
VisualDensity.compact => 'compact',
VisualDensity.comfortable => 'comfortable',
_ => 'custom',
};
@@ -173,9 +164,9 @@ class _OptionsState extends State<Options> {
VisualDensity _profileToDensity(String? profile) {
return switch (profile) {
'standard' => VisualDensity.standard,
'standard' => VisualDensity.standard,
'comfortable' => VisualDensity.comfortable,
'compact' => VisualDensity.compact,
'compact' => VisualDensity.compact,
'custom' || _ => widget.model.density,
};
}
@@ -191,160 +182,162 @@ class _OptionsState extends State<Options> {
return Padding(
padding: const EdgeInsets.fromLTRB(5.0, 0.0, 5.0, 10.0),
child: Builder(builder: (BuildContext context) {
return DefaultTextStyle(
style: TextStyle(color: Colors.grey[50]),
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
const Text('Text Scale'),
Expanded(
child: SliderTheme(
data: controlTheme,
child: Slider(
label: '${widget.model.size}',
min: 0.5,
max: 3.0,
onChanged: (double value) {
widget.model.size = value;
},
value: widget.model.size,
child: Builder(
builder: (BuildContext context) {
return DefaultTextStyle(
style: TextStyle(color: Colors.grey[50]),
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
const Text('Text Scale'),
Expanded(
child: SliderTheme(
data: controlTheme,
child: Slider(
label: '${widget.model.size}',
min: 0.5,
max: 3.0,
onChanged: (double value) {
widget.model.size = value;
},
value: widget.model.size,
),
),
),
),
Text(
widget.model.size.toStringAsFixed(3),
style: TextStyle(color: Colors.grey[50]),
),
],
Text(
widget.model.size.toStringAsFixed(3),
style: TextStyle(color: Colors.grey[50]),
),
],
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
const Text('X Density'),
Expanded(
child: SliderTheme(
data: controlTheme,
child: Slider(
label: widget.model.density.horizontal.toStringAsFixed(1),
min: VisualDensity.minimumDensity,
max: VisualDensity.maximumDensity,
onChanged: (double value) {
widget.model.density = widget.model.density.copyWith(
horizontal: value,
vertical: widget.model.density.vertical,
);
},
value: widget.model.density.horizontal,
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
const Text('X Density'),
Expanded(
child: SliderTheme(
data: controlTheme,
child: Slider(
label: widget.model.density.horizontal.toStringAsFixed(1),
min: VisualDensity.minimumDensity,
max: VisualDensity.maximumDensity,
onChanged: (double value) {
widget.model.density = widget.model.density.copyWith(
horizontal: value,
vertical: widget.model.density.vertical,
);
},
value: widget.model.density.horizontal,
),
),
),
),
Text(
widget.model.density.horizontal.toStringAsFixed(3),
style: TextStyle(color: Colors.grey[50]),
),
],
Text(
widget.model.density.horizontal.toStringAsFixed(3),
style: TextStyle(color: Colors.grey[50]),
),
],
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
const Text('Y Density'),
Expanded(
child: SliderTheme(
data: controlTheme,
child: Slider(
label: widget.model.density.vertical.toStringAsFixed(1),
min: VisualDensity.minimumDensity,
max: VisualDensity.maximumDensity,
onChanged: (double value) {
widget.model.density = widget.model.density.copyWith(
horizontal: widget.model.density.horizontal,
vertical: value,
);
},
value: widget.model.density.vertical,
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
const Text('Y Density'),
Expanded(
child: SliderTheme(
data: controlTheme,
child: Slider(
label: widget.model.density.vertical.toStringAsFixed(1),
min: VisualDensity.minimumDensity,
max: VisualDensity.maximumDensity,
onChanged: (double value) {
widget.model.density = widget.model.density.copyWith(
horizontal: widget.model.density.horizontal,
vertical: value,
);
},
value: widget.model.density.vertical,
),
),
),
),
Text(
widget.model.density.vertical.toStringAsFixed(3),
style: TextStyle(color: Colors.grey[50]),
),
],
Text(
widget.model.density.vertical.toStringAsFixed(3),
style: TextStyle(color: Colors.grey[50]),
),
],
),
),
),
Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
Theme(
data: Theme.of(context).copyWith(canvasColor: Colors.grey[600]),
child: DropdownButton<String>(
style: TextStyle(color: Colors.grey[50]),
isDense: true,
onChanged: (String? value) {
widget.model.density = _profileToDensity(value);
Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
Theme(
data: Theme.of(context).copyWith(canvasColor: Colors.grey[600]),
child: DropdownButton<String>(
style: TextStyle(color: Colors.grey[50]),
isDense: true,
onChanged: (String? value) {
widget.model.density = _profileToDensity(value);
},
items: const <DropdownMenuItem<String>>[
DropdownMenuItem<String>(value: 'standard', child: Text('Standard')),
DropdownMenuItem<String>(
value: 'comfortable',
child: Text('Comfortable'),
),
DropdownMenuItem<String>(value: 'compact', child: Text('Compact')),
DropdownMenuItem<String>(value: 'custom', child: Text('Custom')),
],
value: _densityToProfile(widget.model.density),
),
),
LabeledCheckbox(
label: 'Enabled',
onChanged: (bool? checked) {
widget.model.enable = checked ?? false;
},
items: const <DropdownMenuItem<String>>[
DropdownMenuItem<String>(
value: 'standard',
child: Text('Standard'),
),
DropdownMenuItem<String>(value: 'comfortable', child: Text('Comfortable')),
DropdownMenuItem<String>(value: 'compact', child: Text('Compact')),
DropdownMenuItem<String>(value: 'custom', child: Text('Custom')),
],
value: _densityToProfile(widget.model.density),
value: widget.model.enable,
),
),
LabeledCheckbox(
label: 'Enabled',
onChanged: (bool? checked) {
widget.model.enable = checked ?? false;
},
value: widget.model.enable,
),
LabeledCheckbox(
label: 'Slow',
onChanged: (bool? checked) {
widget.model.slowAnimations = checked ?? false;
Future<void>.delayed(const Duration(milliseconds: 150)).then((_) {
if (widget.model.slowAnimations) {
timeDilation = 20.0;
} else {
timeDilation = 1.0;
}
});
},
value: widget.model.slowAnimations,
),
LabeledCheckbox(
label: 'RTL',
onChanged: (bool? checked) {
widget.model.rtl = checked ?? false;
},
value: widget.model.rtl,
),
MaterialButton(
onPressed: () {
widget.model.reset();
sliderValue = 0.0;
},
child: Text('Reset', style: TextStyle(color: Colors.grey[50])),
),
],
),
],
),
);
}),
LabeledCheckbox(
label: 'Slow',
onChanged: (bool? checked) {
widget.model.slowAnimations = checked ?? false;
Future<void>.delayed(const Duration(milliseconds: 150)).then((_) {
if (widget.model.slowAnimations) {
timeDilation = 20.0;
} else {
timeDilation = 1.0;
}
});
},
value: widget.model.slowAnimations,
),
LabeledCheckbox(
label: 'RTL',
onChanged: (bool? checked) {
widget.model.rtl = checked ?? false;
},
value: widget.model.rtl,
),
MaterialButton(
onPressed: () {
widget.model.reset();
sliderValue = 0.0;
},
child: Text('Reset', style: TextStyle(color: Colors.grey[50])),
),
],
),
],
),
);
},
),
);
}
}
@@ -364,10 +357,7 @@ class _ControlTile extends StatelessWidget {
children: <Widget>[
Align(
alignment: AlignmentDirectional.topStart,
child: Text(
label,
textAlign: TextAlign.start,
),
child: Text(label, textAlign: TextAlign.start),
),
child,
],
@@ -406,13 +396,12 @@ class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
final ThemeData theme = ThemeData(
primarySwatch: m2Swatch,
);
final ThemeData theme = ThemeData(primarySwatch: m2Swatch);
final Widget label = Text(_model.rtl ? 'اضغط علي' : 'Press Me');
textController.text = _model.rtl
? 'يعتمد القرار الجيد على المعرفة وليس على الأرقام.'
: 'A good decision is based on knowledge and not on numbers.';
textController.text =
_model.rtl
? 'يعتمد القرار الجيد على المعرفة وليس على الأرقام.'
: 'A good decision is based on knowledge and not on numbers.';
final List<Widget> tiles = <Widget>[
_ControlTile(
@@ -423,28 +412,33 @@ class _MyHomePageState extends State<MyHomePage> {
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ListTile(
title: Text(_model.rtl ? 'هذا عنوان طويل نسبيا' : 'This is a relatively long title'),
title: Text(
_model.rtl ? 'هذا عنوان طويل نسبيا' : 'This is a relatively long title',
),
onTap: () {},
),
ListTile(
title: Text(_model.rtl ? 'هذا عنوان قصير' : 'This is a short title'),
subtitle:
Text(_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.'),
subtitle: Text(
_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.',
),
trailing: const Icon(Icons.check_box),
onTap: () {},
),
ListTile(
title: Text(_model.rtl ? 'هذا عنوان قصير' : 'This is a short title'),
subtitle:
Text(_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.'),
subtitle: Text(
_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.',
),
leading: const Icon(Icons.check_box),
dense: true,
onTap: () {},
),
ListTile(
title: Text(_model.rtl ? 'هذا عنوان قصير' : 'This is a short title'),
subtitle:
Text(_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.'),
subtitle: Text(
_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.',
),
dense: true,
leading: const Icon(Icons.add_box),
trailing: const Icon(Icons.check_box),
@@ -452,8 +446,9 @@ class _MyHomePageState extends State<MyHomePage> {
),
ListTile(
title: Text(_model.rtl ? 'هذا عنوان قصير' : 'This is a short title'),
subtitle:
Text(_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.'),
subtitle: Text(
_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.',
),
isThreeLine: true,
leading: const Icon(Icons.add_box),
trailing: const Icon(Icons.check_box),
@@ -479,13 +474,8 @@ class _MyHomePageState extends State<MyHomePage> {
border: OutlineInputBorder(),
),
),
TextField(
controller: textController,
),
TextField(
controller: textController,
maxLines: 3,
),
TextField(controller: textController),
TextField(controller: textController, maxLines: 3),
],
),
),
@@ -518,7 +508,7 @@ class _MyHomePageState extends State<MyHomePage> {
child: TextButton(
style: TextButton.styleFrom(
foregroundColor: Colors.white,
backgroundColor: m2Swatch[200]
backgroundColor: m2Swatch[200],
),
onPressed: _model.enable ? () {} : null,
child: label,
@@ -534,10 +524,7 @@ class _MyHomePageState extends State<MyHomePage> {
),
_ControlTile(
label: _model.rtl ? 'زر المخطط التفصيلي' : 'Outlined Button',
child: OutlinedButton(
onPressed: _model.enable ? () {} : null,
child: label,
),
child: OutlinedButton(onPressed: _model.enable ? () {} : null, child: label),
),
_ControlTile(
label: _model.rtl ? 'خانات الاختيار' : 'Checkboxes',
@@ -545,13 +532,14 @@ class _MyHomePageState extends State<MyHomePage> {
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(checkboxValues.length, (int index) {
return Checkbox(
onChanged: _model.enable
? (bool? value) {
setState(() {
checkboxValues[index] = value ?? false;
});
}
: null,
onChanged:
_model.enable
? (bool? value) {
setState(() {
checkboxValues[index] = value ?? false;
});
}
: null,
value: checkboxValues[index],
);
}),
@@ -563,13 +551,14 @@ class _MyHomePageState extends State<MyHomePage> {
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(4, (int index) {
return Radio<int>(
onChanged: _model.enable
? (int? value) {
setState(() {
radioValue = value!;
});
}
: null,
onChanged:
_model.enable
? (int? value) {
setState(() {
radioValue = value!;
});
}
: null,
groupValue: radioValue,
value: index,
);
@@ -614,17 +603,15 @@ class _MyHomePageState extends State<MyHomePage> {
data: Theme.of(context).copyWith(visualDensity: _model.density),
child: Directionality(
textDirection: _model.rtl ? TextDirection.rtl : TextDirection.ltr,
child: Builder(builder: (BuildContext context) {
final MediaQueryData mediaQueryData = MediaQuery.of(context);
return MediaQuery(
data: mediaQueryData.copyWith(textScaler: TextScaler.linear(_model.size)),
child: SizedBox.expand(
child: ListView(
children: tiles,
),
),
);
}),
child: Builder(
builder: (BuildContext context) {
final MediaQueryData mediaQueryData = MediaQuery.of(context);
return MediaQuery(
data: mediaQueryData.copyWith(textScaler: TextScaler.linear(_model.size)),
child: SizedBox.expand(child: ListView(children: tiles)),
);
},
),
),
),
),

View File

@@ -32,10 +32,7 @@ class ExampleDragTargetState extends State<ExampleDragTarget> {
margin: const EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: data.isEmpty ? _color : Colors.grey.shade200,
border: Border.all(
width: 3.0,
color: data.isEmpty ? Colors.white : Colors.blue,
),
border: Border.all(width: 3.0, color: data.isEmpty ? Colors.white : Colors.blue),
),
);
},
@@ -44,7 +41,7 @@ class ExampleDragTargetState extends State<ExampleDragTarget> {
}
class Dot extends StatefulWidget {
const Dot({ super.key, this.color, this.size, this.child, this.tappable = false });
const Dot({super.key, this.color, this.size, this.child, this.tappable = false});
final Color? color;
final double? size;
@@ -54,13 +51,21 @@ class Dot extends StatefulWidget {
@override
DotState createState() => DotState();
}
class DotState extends State<Dot> {
int taps = 0;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.tappable ? () { setState(() { taps += 1; }); } : null,
onTap:
widget.tappable
? () {
setState(() {
taps += 1;
});
}
: null,
child: Container(
width: widget.size,
height: widget.size,
@@ -103,24 +108,16 @@ class ExampleDragSource extends StatelessWidget {
final Widget contents = DefaultTextStyle(
style: Theme.of(context).textTheme.bodyMedium!,
textAlign: TextAlign.center,
child: Dot(
color: color,
size: size,
child: Center(child: child),
),
child: Dot(color: color, size: size, child: Center(child: child)),
);
Widget feedback = Opacity(
opacity: 0.75,
child: contents,
);
Widget feedback = Opacity(opacity: 0.75, child: contents);
Offset feedbackOffset;
DragAnchorStrategy dragAnchorStrategy;
if (!under) {
feedback = Transform(
transform: Matrix4.identity()
..translate(-size / 2.0, -(size / 2.0 + kFingerSize)),
transform: Matrix4.identity()..translate(-size / 2.0, -(size / 2.0 + kFingerSize)),
child: feedback,
);
feedbackOffset = const Offset(0.0, -kFingerSize);
@@ -161,10 +158,11 @@ class DashOutlineCirclePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final double radius = size.shortestSide / 2.0;
final Paint paint = Paint()
..color = const Color(0xFF000000)
..style = PaintingStyle.stroke
..strokeWidth = radius / 10.0;
final Paint paint =
Paint()
..color = const Color(0xFF000000)
..style = PaintingStyle.stroke
..strokeWidth = radius / 10.0;
final Path path = Path();
final Rect box = Offset.zero & size;
for (double theta = 0.0; theta < math.pi * 2.0; theta += deltaTheta) {
@@ -203,9 +201,7 @@ class MovableBall extends StatelessWidget {
const Widget dashedBall = SizedBox(
width: kBallSize,
height: kBallSize,
child: CustomPaint(
painter: DashOutlineCirclePainter()
),
child: CustomPaint(painter: DashOutlineCirclePainter()),
);
if (position == ballPosition) {
return Draggable<bool>(
@@ -217,7 +213,9 @@ class MovableBall extends StatelessWidget {
);
} else {
return DragTarget<bool>(
onAcceptWithDetails: (DragTargetDetails<bool> data) { callback(position); },
onAcceptWithDetails: (DragTargetDetails<bool> data) {
callback(position);
},
builder: (BuildContext context, List<bool?> accepted, List<dynamic> rejected) {
return dashedBall;
},
@@ -237,25 +235,22 @@ class DragAndDropAppState extends State<DragAndDropApp> {
int position = 1;
void moveBall(int newPosition) {
setState(() { position = newPosition; });
setState(() {
position = newPosition;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Drag and Drop Flutter Demo'),
),
appBar: AppBar(title: const Text('Drag and Drop Flutter Demo')),
body: Column(
children: <Widget>[
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ExampleDragSource(
color: Colors.yellow.shade300,
child: const Text('under'),
),
ExampleDragSource(color: Colors.yellow.shade300, child: const Text('under')),
ExampleDragSource(
color: Colors.green.shade300,
under: false,
@@ -297,8 +292,5 @@ class DragAndDropAppState extends State<DragAndDropApp> {
}
void main() {
runApp(const MaterialApp(
title: 'Drag and Drop Flutter Demo',
home: DragAndDropApp(),
));
runApp(const MaterialApp(title: 'Drag and Drop Flutter Demo', home: DragAndDropApp()));
}

View File

@@ -6,14 +6,16 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MaterialApp(
title: 'Focus Demo',
home: FocusDemo(),
));
runApp(const MaterialApp(title: 'Focus Demo', home: FocusDemo()));
}
class DemoButton extends StatefulWidget {
const DemoButton({super.key, required this.name, this.canRequestFocus = true, this.autofocus = false});
const DemoButton({
super.key,
required this.name,
this.canRequestFocus = true,
this.autofocus = false,
});
final String name;
final bool canRequestFocus;
@@ -25,8 +27,8 @@ class DemoButton extends StatefulWidget {
class _DemoButtonState extends State<DemoButton> {
late final FocusNode focusNode = FocusNode(
debugLabel: widget.name,
canRequestFocus: widget.canRequestFocus,
debugLabel: widget.name,
canRequestFocus: widget.canRequestFocus,
);
@override
@@ -97,8 +99,8 @@ class _FocusDemoState extends State<FocusDemo> {
print('Keys down: ${HardwareKeyboard.instance.logicalKeysPressed}');
if (event.logicalKey == LogicalKeyboardKey.tab) {
debugDumpFocusTree();
if (HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftLeft)
|| HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftRight)) {
if (HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftLeft) ||
HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftRight)) {
print('Moving to previous.');
node.previousFocus();
return KeyEventResult.handled;
@@ -109,10 +111,10 @@ class _FocusDemoState extends State<FocusDemo> {
}
}
final TraversalDirection? direction = switch (event.logicalKey) {
LogicalKeyboardKey.arrowLeft => TraversalDirection.left,
LogicalKeyboardKey.arrowLeft => TraversalDirection.left,
LogicalKeyboardKey.arrowRight => TraversalDirection.right,
LogicalKeyboardKey.arrowUp => TraversalDirection.up,
LogicalKeyboardKey.arrowDown => TraversalDirection.down,
LogicalKeyboardKey.arrowUp => TraversalDirection.up,
LogicalKeyboardKey.arrowDown => TraversalDirection.down,
_ => null,
};
if (direction != null) {
@@ -136,65 +138,57 @@ class _FocusDemoState extends State<FocusDemo> {
child: DefaultTextStyle(
style: textTheme.headlineMedium!,
child: Scaffold(
appBar: AppBar(
title: const Text('Focus Demo'),
),
floatingActionButton: FloatingActionButton(
child: const Text('+'),
onPressed: () {},
),
appBar: AppBar(title: const Text('Focus Demo')),
floatingActionButton: FloatingActionButton(child: const Text('+'), onPressed: () {}),
body: Center(
child: Builder(builder: (BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(
name: 'One',
autofocus: true,
),
],
),
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(name: 'Two'),
DemoButton(
name: 'Three',
canRequestFocus: false,
),
],
),
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(name: 'Four'),
DemoButton(name: 'Five'),
DemoButton(name: 'Six'),
],
),
OutlinedButton(onPressed: () => print('pressed'), child: const Text('PRESS ME')),
const Padding(
padding: EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(labelText: 'Enter Text', filled: true),
child: Builder(
builder: (BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[DemoButton(name: 'One', autofocus: true)],
),
),
const Padding(
padding: EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter Text',
filled: false,
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(name: 'Two'),
DemoButton(name: 'Three', canRequestFocus: false),
],
),
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DemoButton(name: 'Four'),
DemoButton(name: 'Five'),
DemoButton(name: 'Six'),
],
),
OutlinedButton(
onPressed: () => print('pressed'),
child: const Text('PRESS ME'),
),
const Padding(
padding: EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(labelText: 'Enter Text', filled: true),
),
),
),
],
);
}),
const Padding(
padding: EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter Text',
filled: false,
),
),
),
],
);
},
),
),
),
),

View File

@@ -6,17 +6,15 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MaterialApp(
title: 'Hardware Key Demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Hardware Key Demo'),
),
body: const Center(
child: HardwareKeyboardDemo(),
runApp(
MaterialApp(
title: 'Hardware Key Demo',
home: Scaffold(
appBar: AppBar(title: const Text('Hardware Key Demo')),
body: const Center(child: HardwareKeyboardDemo()),
),
),
));
);
}
class HardwareKeyboardDemo extends StatefulWidget {
@@ -68,7 +66,8 @@ class _HardwareKeyboardDemoState extends State<HardwareKeyboardDemo> {
final List<Widget> dataText = <Widget>[
Text('${_event.runtimeType}'),
if (_event?.character?.isNotEmpty ?? false) Text('character produced: "${_event?.character}"'),
if (_event?.character?.isNotEmpty ?? false)
Text('character produced: "${_event?.character}"'),
];
dataText.add(Text('logical: ${_event?.logicalKey}'));
dataText.add(Text('physical: ${_event?.physicalKey}'));
@@ -82,10 +81,7 @@ class _HardwareKeyboardDemoState extends State<HardwareKeyboardDemo> {
dataText.add(Text(pressed.join(' ')));
return DefaultTextStyle(
style: textTheme.titleMedium!,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: dataText,
),
child: Column(mainAxisAlignment: MainAxisAlignment.center, children: dataText),
);
},
),

View File

@@ -5,10 +5,7 @@
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(
title: 'Hover Demo',
home: HoverDemo(),
));
runApp(const MaterialApp(title: 'Hover Demo', home: HoverDemo()));
}
class HoverDemo extends StatefulWidget {
@@ -24,63 +21,62 @@ class _HoverDemoState extends State<HoverDemo> {
final TextTheme textTheme = Theme.of(context).textTheme;
final ButtonStyle overrideFocusColor = ButtonStyle(
overlayColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {
return states.contains(MaterialState.focused) ? Colors.deepOrangeAccent : Colors.transparent;
})
return states.contains(MaterialState.focused)
? Colors.deepOrangeAccent
: Colors.transparent;
}),
);
return DefaultTextStyle(
style: textTheme.headlineMedium!,
child: Scaffold(
appBar: AppBar(
title: const Text('Hover Demo'),
),
floatingActionButton: FloatingActionButton(
child: const Text('+'),
onPressed: () {},
),
appBar: AppBar(title: const Text('Hover Demo')),
floatingActionButton: FloatingActionButton(child: const Text('+'), onPressed: () {}),
body: Center(
child: Builder(builder: (BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
children: <Widget>[
ElevatedButton(
onPressed: () => print('Button pressed.'),
style: overrideFocusColor,
child: const Text('Button'),
),
TextButton(
onPressed: () => print('Button pressed.'),
style: overrideFocusColor,
child: const Text('Button'),
),
IconButton(
onPressed: () => print('Button pressed'),
icon: const Icon(Icons.access_alarm),
focusColor: Colors.deepOrangeAccent,
),
],
),
const Padding(
padding: EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(labelText: 'Enter Text', filled: true),
child: Builder(
builder: (BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
children: <Widget>[
ElevatedButton(
onPressed: () => print('Button pressed.'),
style: overrideFocusColor,
child: const Text('Button'),
),
TextButton(
onPressed: () => print('Button pressed.'),
style: overrideFocusColor,
child: const Text('Button'),
),
IconButton(
onPressed: () => print('Button pressed'),
icon: const Icon(Icons.access_alarm),
focusColor: Colors.deepOrangeAccent,
),
],
),
),
const Padding(
padding: EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter Text',
filled: false,
const Padding(
padding: EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(labelText: 'Enter Text', filled: true),
),
),
),
],
);
}),
const Padding(
padding: EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter Text',
filled: false,
),
),
),
],
);
},
),
),
),
);

View File

@@ -5,10 +5,10 @@
import 'package:flutter/widgets.dart';
void main() {
runApp(const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Text('flutter run -t xxx.dart'),
runApp(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(child: Text('flutter run -t xxx.dart')),
),
));
);
}

View File

@@ -5,10 +5,7 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
enum _DragTarget {
start,
end
}
enum _DragTarget { start, end }
// How close a drag's start position must be to the target point. This is
// a distance squared.
@@ -40,22 +37,21 @@ class _DragHandler extends Drag {
}
}
class _IgnoreDrag extends Drag {
}
class _IgnoreDrag extends Drag {}
class _PointDemoPainter extends CustomPainter {
_PointDemoPainter({
Animation<double>? repaint,
required this.arc,
}) : _repaint = repaint, super(repaint: repaint);
_PointDemoPainter({Animation<double>? repaint, required this.arc})
: _repaint = repaint,
super(repaint: repaint);
final MaterialPointArcTween arc;
final Animation<double>? _repaint;
void drawPoint(Canvas canvas, Offset point, Color color) {
final Paint paint = Paint()
..color = color.withOpacity(0.25)
..style = PaintingStyle.fill;
final Paint paint =
Paint()
..color = color.withOpacity(0.25)
..style = PaintingStyle.fill;
canvas.drawCircle(point, _kPointRadius, paint);
paint
..color = color
@@ -73,7 +69,8 @@ class _PointDemoPainter extends CustomPainter {
}
paint
..isAntiAlias = false // Work-around for github.com/flutter/flutter/issues/5720
..isAntiAlias =
false // Work-around for github.com/flutter/flutter/issues/5720
..color = Colors.green.withOpacity(0.25)
..strokeWidth = 4.0
..style = PaintingStyle.stroke;
@@ -94,8 +91,8 @@ class _PointDemoPainter extends CustomPainter {
@override
bool hitTest(Offset position) {
return (arc.begin! - position).distanceSquared < _kTargetSlop
|| (arc.end! - position).distanceSquared < _kTargetSlop;
return (arc.begin! - position).distanceSquared < _kTargetSlop ||
(arc.end! - position).distanceSquared < _kTargetSlop;
}
@override
@@ -103,7 +100,7 @@ class _PointDemoPainter extends CustomPainter {
}
class _PointDemo extends StatefulWidget {
const _PointDemo({ super.key, required this.controller });
const _PointDemo({super.key, required this.controller});
final AnimationController controller;
@@ -189,20 +186,18 @@ class _PointDemoState extends State<_PointDemo> {
return RawGestureDetector(
behavior: _dragTarget == null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque,
gestures: <Type, GestureRecognizerFactory>{
ImmediateMultiDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<ImmediateMultiDragGestureRecognizer>(
() => ImmediateMultiDragGestureRecognizer(),
(ImmediateMultiDragGestureRecognizer instance) {
instance.onStart = _handleOnStart;
},
),
ImmediateMultiDragGestureRecognizer:
GestureRecognizerFactoryWithHandlers<ImmediateMultiDragGestureRecognizer>(
() => ImmediateMultiDragGestureRecognizer(),
(ImmediateMultiDragGestureRecognizer instance) {
instance.onStart = _handleOnStart;
},
),
},
child: ClipRect(
child: CustomPaint(
key: _painterKey,
foregroundPainter: _PointDemoPainter(
repaint: _animation,
arc: arc,
),
foregroundPainter: _PointDemoPainter(repaint: _animation, arc: arc),
// Watch out: if this IgnorePointer is left out, then gestures that
// fail _PointDemoPainter.hitTest() will still be recognized because
// they do overlap this child, which is as big as the CustomPaint.
@@ -223,18 +218,18 @@ class _PointDemoState extends State<_PointDemo> {
}
class _RectangleDemoPainter extends CustomPainter {
_RectangleDemoPainter({
required Animation<double> repaint,
required this.arc,
}) : _repaint = repaint, super(repaint: repaint);
_RectangleDemoPainter({required Animation<double> repaint, required this.arc})
: _repaint = repaint,
super(repaint: repaint);
final MaterialRectArcTween arc;
final Animation<double> _repaint;
void drawPoint(Canvas canvas, Offset p, Color color) {
final Paint paint = Paint()
..color = color.withOpacity(0.25)
..style = PaintingStyle.fill;
final Paint paint =
Paint()
..color = color.withOpacity(0.25)
..style = PaintingStyle.fill;
canvas.drawCircle(p, _kPointRadius, paint);
paint
..color = color
@@ -244,10 +239,11 @@ class _RectangleDemoPainter extends CustomPainter {
}
void drawRect(Canvas canvas, Rect rect, Color color) {
final Paint paint = Paint()
..color = color.withOpacity(0.25)
..strokeWidth = 4.0
..style = PaintingStyle.stroke;
final Paint paint =
Paint()
..color = color.withOpacity(0.25)
..strokeWidth = 4.0
..style = PaintingStyle.stroke;
canvas.drawRect(rect, paint);
drawPoint(canvas, rect.center, color);
}
@@ -261,8 +257,8 @@ class _RectangleDemoPainter extends CustomPainter {
@override
bool hitTest(Offset position) {
return (arc.begin!.center - position).distanceSquared < _kTargetSlop
|| (arc.end!.center - position).distanceSquared < _kTargetSlop;
return (arc.begin!.center - position).distanceSquared < _kTargetSlop ||
(arc.end!.center - position).distanceSquared < _kTargetSlop;
}
@override
@@ -270,7 +266,7 @@ class _RectangleDemoPainter extends CustomPainter {
}
class _RectangleDemo extends StatefulWidget {
const _RectangleDemo({ super.key, required this.controller });
const _RectangleDemo({super.key, required this.controller});
final AnimationController controller;
@@ -281,7 +277,10 @@ class _RectangleDemo extends StatefulWidget {
class _RectangleDemoState extends State<_RectangleDemo> {
final GlobalKey _painterKey = GlobalKey();
late final CurvedAnimation _animation = CurvedAnimation(parent: widget.controller, curve: Curves.fastOutSlowIn);
late final CurvedAnimation _animation = CurvedAnimation(
parent: widget.controller,
curve: Curves.fastOutSlowIn,
);
_DragTarget? _dragTarget;
Size? _screenSize;
Rect? _begin;
@@ -342,12 +341,16 @@ class _RectangleDemoState extends State<_RectangleDemo> {
if (_screenSize == null || _screenSize != screenSize) {
_screenSize = screenSize;
_begin = Rect.fromLTWH(
screenSize.width * 0.5, screenSize.height * 0.2,
screenSize.width * 0.4, screenSize.height * 0.2,
screenSize.width * 0.5,
screenSize.height * 0.2,
screenSize.width * 0.4,
screenSize.height * 0.2,
);
_end = Rect.fromLTWH(
screenSize.width * 0.1, screenSize.height * 0.4,
screenSize.width * 0.3, screenSize.height * 0.3,
screenSize.width * 0.1,
screenSize.height * 0.4,
screenSize.width * 0.3,
screenSize.height * 0.3,
);
}
@@ -355,20 +358,18 @@ class _RectangleDemoState extends State<_RectangleDemo> {
return RawGestureDetector(
behavior: _dragTarget == null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque,
gestures: <Type, GestureRecognizerFactory>{
ImmediateMultiDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<ImmediateMultiDragGestureRecognizer>(
() => ImmediateMultiDragGestureRecognizer(),
(ImmediateMultiDragGestureRecognizer instance) {
instance.onStart = _handleOnStart;
},
),
ImmediateMultiDragGestureRecognizer:
GestureRecognizerFactoryWithHandlers<ImmediateMultiDragGestureRecognizer>(
() => ImmediateMultiDragGestureRecognizer(),
(ImmediateMultiDragGestureRecognizer instance) {
instance.onStart = _handleOnStart;
},
),
},
child: ClipRect(
child: CustomPaint(
key: _painterKey,
foregroundPainter: _RectangleDemoPainter(
repaint: _animation,
arc: arc,
),
foregroundPainter: _RectangleDemoPainter(repaint: _animation, arc: arc),
// Watch out: if this IgnorePointer is left out, then gestures that
// fail _RectDemoPainter.hitTest() will still be recognized because
// they do overlap this child, which is as big as the CustomPaint.
@@ -402,7 +403,7 @@ class _ArcDemo {
}
class AnimationDemo extends StatefulWidget {
const AnimationDemo({ super.key });
const AnimationDemo({super.key});
@override
State<AnimationDemo> createState() => _AnimationDemoState();
@@ -411,16 +412,10 @@ class AnimationDemo extends StatefulWidget {
class _AnimationDemoState extends State<AnimationDemo> with TickerProviderStateMixin {
late final List<_ArcDemo> _allDemos = <_ArcDemo>[
_ArcDemo('POINT', (_ArcDemo demo) {
return _PointDemo(
key: demo.key,
controller: demo.controller,
);
return _PointDemo(key: demo.key, controller: demo.controller);
}, this),
_ArcDemo('RECTANGLE', (_ArcDemo demo) {
return _RectangleDemo(
key: demo.key,
controller: demo.controller,
);
return _RectangleDemo(key: demo.key, controller: demo.controller);
}, this),
];
@@ -461,7 +456,5 @@ class _AnimationDemoState extends State<AnimationDemo> with TickerProviderStateM
}
void main() {
runApp(const MaterialApp(
home: AnimationDemo(),
));
runApp(const MaterialApp(home: AnimationDemo()));
}

View File

@@ -6,14 +6,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(
const MaterialApp(
title: 'Menu Tester',
home: Material(
child: Home(),
),
),
);
runApp(const MaterialApp(title: 'Menu Tester', home: Material(child: Home())));
}
class Home extends StatefulWidget {
@@ -43,17 +36,11 @@ class _HomeState extends State<Home> {
menuTheme = const MenuThemeData(
style: MenuStyle(
shape: MaterialStatePropertyAll<OutlinedBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(10),
),
),
RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
),
backgroundColor: MaterialStatePropertyAll<Color?>(Colors.blue),
elevation: MaterialStatePropertyAll<double?>(10),
padding: MaterialStatePropertyAll<EdgeInsetsDirectional>(
EdgeInsetsDirectional.all(20),
),
padding: MaterialStatePropertyAll<EdgeInsetsDirectional>(EdgeInsetsDirectional.all(20)),
),
);
menuButtonTheme = const MenuButtonThemeData(
@@ -68,9 +55,7 @@ class _HomeState extends State<Home> {
shape: MaterialStatePropertyAll<OutlinedBorder>(RoundedRectangleBorder()),
backgroundColor: MaterialStatePropertyAll<Color?>(Colors.blue),
elevation: MaterialStatePropertyAll<double?>(10),
padding: MaterialStatePropertyAll<EdgeInsetsDirectional>(
EdgeInsetsDirectional.all(20),
),
padding: MaterialStatePropertyAll<EdgeInsetsDirectional>(EdgeInsetsDirectional.all(20)),
),
);
}
@@ -82,16 +67,17 @@ class _HomeState extends State<Home> {
child: Theme(
data: theme.copyWith(
visualDensity: _density,
menuTheme: _transparent
? MenuThemeData(
style: MenuStyle(
backgroundColor: MaterialStatePropertyAll<Color>(
Colors.blue.withOpacity(0.12),
menuTheme:
_transparent
? MenuThemeData(
style: MenuStyle(
backgroundColor: MaterialStatePropertyAll<Color>(
Colors.blue.withOpacity(0.12),
),
elevation: const MaterialStatePropertyAll<double>(0),
),
elevation: const MaterialStatePropertyAll<double>(0),
),
)
: menuTheme,
)
: menuTheme,
menuBarTheme: menuBarTheme,
menuButtonTheme: menuButtonTheme,
),
@@ -273,10 +259,7 @@ class _ControlsState extends State<_Controls> {
divisions: 12,
onChanged: (double value) {
widget.onDensityChanged(
VisualDensity(
horizontal: value,
vertical: widget.density.vertical,
),
VisualDensity(horizontal: value, vertical: widget.density.vertical),
);
},
),
@@ -288,10 +271,7 @@ class _ControlsState extends State<_Controls> {
divisions: 12,
onChanged: (double value) {
widget.onDensityChanged(
VisualDensity(
horizontal: widget.density.horizontal,
vertical: value,
),
VisualDensity(horizontal: widget.density.horizontal, vertical: value),
);
},
),
@@ -314,7 +294,7 @@ class _ControlsState extends State<_Controls> {
}
},
),
const Text('RTL Text')
const Text('RTL Text'),
],
),
Row(
@@ -330,7 +310,7 @@ class _ControlsState extends State<_Controls> {
}
},
),
const Text('Add Item')
const Text('Add Item'),
],
),
Row(
@@ -346,7 +326,7 @@ class _ControlsState extends State<_Controls> {
}
},
),
const Text('Enable Accelerators')
const Text('Enable Accelerators'),
],
),
Row(
@@ -362,7 +342,7 @@ class _ControlsState extends State<_Controls> {
}
},
),
const Text('Transparent')
const Text('Transparent'),
],
),
Row(
@@ -378,7 +358,7 @@ class _ControlsState extends State<_Controls> {
}
},
),
const Text('Funky Theme')
const Text('Funky Theme'),
],
),
],
@@ -436,11 +416,7 @@ class _ControlSlider extends StatelessWidget {
}
class _TestMenus extends StatefulWidget {
const _TestMenus({
required this.menuController,
this.addItem = false,
this.accelerators = false,
});
const _TestMenus({required this.menuController, this.addItem = false, this.accelerators = false});
final MenuController menuController;
final bool addItem;
@@ -480,8 +456,8 @@ class _TestMenusState extends State<_TestMenus> {
setState(() {
checkboxState = switch (checkboxState) {
false => true,
true => null,
null => false,
true => null,
null => false,
};
});
}
@@ -575,10 +551,7 @@ List<Widget> createTestMenus({
bool includeExtraGroups = false,
bool accelerators = false,
}) {
Widget submenuButton(
TestMenu menu, {
required List<Widget> menuChildren,
}) {
Widget submenuButton(TestMenu menu, {required List<Widget> menuChildren}) {
return SubmenuButton(
onOpen: onOpen != null ? () => onOpen(menu) : null,
onClose: onClose != null ? () => onClose(menu) : null,
@@ -616,7 +589,10 @@ List<Widget> createTestMenus({
key: key,
value: checkboxValue,
tristate: tristate,
onChanged: enabled && onCheckboxChanged != null ? (bool? value) => onCheckboxChanged(menu, value) : null,
onChanged:
enabled && onCheckboxChanged != null
? (bool? value) => onCheckboxChanged(menu, value)
: null,
shortcut: menu.shortcut,
trailingIcon: trailingIcon,
child: accelerators ? MenuAcceleratorLabel(menu.acceleratorLabel) : Text(menu.label),
@@ -678,22 +654,25 @@ List<Widget> createTestMenus({
TestMenu.mainMenu2,
menuChildren: <Widget>[
MenuAcceleratorCallbackBinding(
onInvoke: onPressed != null
? () {
onPressed.call(TestMenu.testButton);
menuController?.close();
}
: null,
child: TextButton(
onPressed: onPressed != null
? () {
onInvoke:
onPressed != null
? () {
onPressed.call(TestMenu.testButton);
menuController?.close();
}
: null,
child: accelerators
? MenuAcceleratorLabel(TestMenu.testButton.acceleratorLabel)
: Text(TestMenu.testButton.label),
: null,
child: TextButton(
onPressed:
onPressed != null
? () {
onPressed.call(TestMenu.testButton);
menuController?.close();
}
: null,
child:
accelerators
? MenuAcceleratorLabel(TestMenu.testButton.acceleratorLabel)
: Text(TestMenu.testButton.label),
),
),
menuItemButton(TestMenu.subMenu3),
@@ -708,7 +687,7 @@ List<Widget> createTestMenus({
debugPrint('Focused Item: $primaryFocus');
},
child: const Text('Print Focused Item'),
)
),
],
),
submenuButton(
@@ -737,11 +716,8 @@ List<Widget> createTestMenus({
submenuButton(
TestMenu.subSubMenu3,
menuChildren: <Widget>[
for (int i=0; i < 100; ++i)
MenuItemButton(
onPressed: () {},
child: Text('Menu Item $i'),
),
for (int i = 0; i < 100; ++i)
MenuItemButton(onPressed: () {}, child: Text('Menu Item $i')),
],
),
],

View File

@@ -19,10 +19,7 @@ class CardModel {
enum MarkerType { topLeft, bottomRight, touch }
class _MarkerPainter extends CustomPainter {
const _MarkerPainter({
required this.size,
required this.type,
});
const _MarkerPainter({required this.size, required this.type});
final double size;
final MarkerType type;
@@ -52,18 +49,12 @@ class _MarkerPainter extends CustomPainter {
@override
bool shouldRepaint(_MarkerPainter oldPainter) {
return oldPainter.size != size
|| oldPainter.type != type;
return oldPainter.size != size || oldPainter.type != type;
}
}
class Marker extends StatelessWidget {
const Marker({
super.key,
this.type = MarkerType.touch,
this.position,
this.size = 40.0,
});
const Marker({super.key, this.type = MarkerType.touch, this.position, this.size = 40.0});
final Offset? position;
final double size;
@@ -76,14 +67,7 @@ class Marker extends StatelessWidget {
top: position!.dy - size / 2.0,
width: size,
height: size,
child: IgnorePointer(
child: CustomPaint(
painter: _MarkerPainter(
size: size,
type: type,
),
),
),
child: IgnorePointer(child: CustomPaint(painter: _MarkerPainter(size: size, type: type))),
);
}
}
@@ -98,13 +82,17 @@ class OverlayGeometryApp extends StatefulWidget {
typedef CardTapCallback = void Function(GlobalKey targetKey, Offset globalPosition);
class CardBuilder extends SliverChildDelegate {
CardBuilder({List<CardModel>? cardModels, this.onTapUp }) : cardModels = cardModels ?? <CardModel>[];
CardBuilder({List<CardModel>? cardModels, this.onTapUp})
: cardModels = cardModels ?? <CardModel>[];
final List<CardModel> cardModels;
final CardTapCallback? onTapUp;
static const TextStyle cardLabelStyle =
TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold);
static const TextStyle cardLabelStyle = TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
);
@override
Widget? build(BuildContext context, int index) {
@@ -114,7 +102,9 @@ class CardBuilder extends SliverChildDelegate {
final CardModel cardModel = cardModels[index];
return GestureDetector(
key: cardModel.key,
onTapUp: (TapUpDetails details) { onTapUp!(cardModel.targetKey, details.globalPosition); },
onTapUp: (TapUpDetails details) {
onTapUp!(cardModel.targetKey, details.globalPosition);
},
child: Card(
key: cardModel.targetKey,
color: cardModel.color,
@@ -145,12 +135,40 @@ class OverlayGeometryAppState extends State<OverlayGeometryApp> {
void initState() {
super.initState();
final List<double> cardHeights = <double>[
48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0,
63.0,
82.0,
146.0,
60.0,
55.0,
84.0,
96.0,
50.0,
48.0,
63.0,
82.0,
146.0,
60.0,
55.0,
84.0,
96.0,
50.0,
48.0,
63.0,
82.0,
146.0,
60.0,
55.0,
84.0,
96.0,
50.0,
];
cardModels = List<CardModel>.generate(cardHeights.length, (int i) {
final Color? color = Color.lerp(Colors.red.shade300, Colors.blue.shade900, i / cardHeights.length);
final Color? color = Color.lerp(
Colors.red.shade300,
Colors.blue.shade900,
i / cardHeights.length,
);
return CardModel(i, cardHeights[i], color!);
});
}
@@ -191,26 +209,17 @@ class OverlayGeometryAppState extends State<OverlayGeometryApp> {
child: NotificationListener<ScrollNotification>(
onNotification: handleScrollNotification,
child: ListView.custom(
childrenDelegate: CardBuilder(
cardModels: cardModels,
onTapUp: handleTapUp,
),
childrenDelegate: CardBuilder(cardModels: cardModels, onTapUp: handleTapUp),
),
),
),
),
for (final MarkerType type in markers.keys)
Marker(type: type, position: markers[type]),
for (final MarkerType type in markers.keys) Marker(type: type, position: markers[type]),
],
);
}
}
void main() {
runApp(
const MaterialApp(
title: 'Cards',
home: OverlayGeometryApp(),
),
);
runApp(const MaterialApp(title: 'Cards', home: OverlayGeometryApp()));
}

View File

@@ -33,13 +33,20 @@ class PageViewAppState extends State<PageViewApp> {
];
cardModels = List<CardModel>.generate(cardSizes.length, (int i) {
final Color? color = Color.lerp(Colors.red.shade300, Colors.blue.shade900, i / cardSizes.length);
final Color? color = Color.lerp(
Colors.red.shade300,
Colors.blue.shade900,
i / cardSizes.length,
);
return CardModel(i, cardSizes[i], color!);
});
}
static const TextStyle cardLabelStyle =
TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold);
static const TextStyle cardLabelStyle = TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
);
List<CardModel> cardModels = <CardModel>[];
Size pageSize = const Size(200.0, 200.0);
@@ -57,15 +64,12 @@ class PageViewAppState extends State<PageViewApp> {
),
);
final BoxConstraints constraints = (scrollDirection == Axis.vertical)
? BoxConstraints.tightFor(height: pageSize.height)
: BoxConstraints.tightFor(width: pageSize.width);
final BoxConstraints constraints =
(scrollDirection == Axis.vertical)
? BoxConstraints.tightFor(height: pageSize.height)
: BoxConstraints.tightFor(width: pageSize.width);
return Container(
key: cardModel.key,
constraints: constraints,
child: Center(child: card),
);
return Container(key: cardModel.key, constraints: constraints, child: Center(child: card));
}
void switchScrollDirection() {
@@ -109,10 +113,7 @@ class PageViewAppState extends State<PageViewApp> {
}
AppBar _buildAppBar() {
return AppBar(
title: const Text('PageView'),
actions: <Widget>[Text(scrollDirection.name)],
);
return AppBar(title: const Text('PageView'), actions: <Widget>[Text(scrollDirection.name)]);
}
Widget _buildBody(BuildContext context) {
@@ -127,20 +128,11 @@ class PageViewAppState extends State<PageViewApp> {
Widget build(BuildContext context) {
return IconTheme(
data: const IconThemeData(color: Colors.white),
child: Scaffold(
appBar: _buildAppBar(),
drawer: _buildDrawer(),
body: _buildBody(context),
),
child: Scaffold(appBar: _buildAppBar(), drawer: _buildDrawer(), body: _buildBody(context)),
);
}
}
void main() {
runApp(
const MaterialApp(
title: 'PageView',
home: PageViewApp(),
),
);
runApp(const MaterialApp(title: 'PageView', home: PageViewApp()));
}

View File

@@ -7,23 +7,14 @@ import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
enum LerpTarget {
circle,
roundedRect,
rect,
stadium,
polygon,
star,
}
enum LerpTarget { circle, roundedRect, rect, stadium, polygon, star }
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
return const MaterialApp(home: MyHomePage());
}
}
@@ -60,10 +51,7 @@ class _MyHomePageState extends State<MyHomePage> {
return SafeArea(
child: Scaffold(
key: scaffoldKey,
appBar: AppBar(
title: const Text('Star Border'),
backgroundColor: const Color(0xff323232),
),
appBar: AppBar(title: const Text('Star Border'), backgroundColor: const Color(0xff323232)),
body: Column(
children: <Widget>[
ColoredBox(color: Colors.grey.shade200, child: Options(_model)),
@@ -77,18 +65,22 @@ class _MyHomePageState extends State<MyHomePage> {
height: 200,
decoration: ShapeDecoration(
color: Colors.blue.shade100,
shape: lerpBorder(
StarBorder.polygon(
side: const BorderSide(strokeAlign: BorderSide.strokeAlignCenter, width: 2),
sides: _model.points,
pointRounding: _model.pointRounding,
rotation: _model.rotation,
squash: _model.squash,
),
_model._lerpTarget,
_model._lerpAmount,
to: _model.lerpTo,
)!,
shape:
lerpBorder(
StarBorder.polygon(
side: const BorderSide(
strokeAlign: BorderSide.strokeAlignCenter,
width: 2,
),
sides: _model.points,
pointRounding: _model.pointRounding,
rotation: _model.rotation,
squash: _model.squash,
),
_model._lerpTarget,
_model._lerpAmount,
to: _model.lerpTo,
)!,
),
child: const Text('Polygon'),
),
@@ -98,20 +90,24 @@ class _MyHomePageState extends State<MyHomePage> {
height: 200,
decoration: ShapeDecoration(
color: Colors.blue.shade100,
shape: lerpBorder(
StarBorder(
side: const BorderSide(strokeAlign: BorderSide.strokeAlignCenter, width: 2),
points: _model.points,
innerRadiusRatio: _model.innerRadiusRatio,
pointRounding: _model.pointRounding,
valleyRounding: _model.valleyRounding,
rotation: _model.rotation,
squash: _model.squash,
),
_model._lerpTarget,
_model._lerpAmount,
to: _model.lerpTo,
)!,
shape:
lerpBorder(
StarBorder(
side: const BorderSide(
strokeAlign: BorderSide.strokeAlignCenter,
width: 2,
),
points: _model.points,
innerRadiusRatio: _model.innerRadiusRatio,
pointRounding: _model.pointRounding,
valleyRounding: _model.valleyRounding,
rotation: _model.rotation,
squash: _model.squash,
),
_model._lerpTarget,
_model._lerpAmount,
to: _model.lerpTo,
)!,
),
child: const Text('Star'),
),
@@ -334,10 +330,11 @@ class _OptionsState extends State<Options> {
),
),
OutlinedButton(
child: const Text('Nearest'),
onPressed: () {
widget.model.points = widget.model.points.roundToDouble();
}),
child: const Text('Nearest'),
onPressed: () {
widget.model.points = widget.model.points.roundToDouble();
},
),
],
),
),
@@ -372,24 +369,30 @@ class _OptionsState extends State<Options> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(children: <Widget>[
Radio<bool>(
Row(
children: <Widget>[
Radio<bool>(
value: true,
groupValue: widget.model.lerpTo,
onChanged: (bool? value) {
widget.model.lerpTo = value!;
}),
const Text('To'),
]),
Row(children: <Widget>[
Radio<bool>(
},
),
const Text('To'),
],
),
Row(
children: <Widget>[
Radio<bool>(
value: false,
groupValue: widget.model.lerpTo,
onChanged: (bool? value) {
widget.model.lerpTo = value!;
}),
const Text('From'),
])
},
),
const Text('From'),
],
),
],
),
),
@@ -398,9 +401,15 @@ class _OptionsState extends State<Options> {
children: <Widget>[
Expanded(
child: DropdownButton<LerpTarget>(
items: LerpTarget.values.map<DropdownMenuItem<LerpTarget>>((LerpTarget target) {
return DropdownMenuItem<LerpTarget>(value: target, child: Text(target.name));
}).toList(),
items:
LerpTarget.values.map<DropdownMenuItem<LerpTarget>>((
LerpTarget target,
) {
return DropdownMenuItem<LerpTarget>(
value: target,
child: Text(target.name),
);
}).toList(),
value: widget.model.lerpTarget,
onChanged: (LerpTarget? value) {
if (value == null) {
@@ -461,9 +470,7 @@ class ControlSlider extends StatelessWidget {
value: value,
),
),
Text(
value.toStringAsFixed(3),
),
Text(value.toStringAsFixed(3)),
],
),
);
@@ -475,12 +482,15 @@ const BorderSide lerpToBorder = BorderSide(width: 5, color: lerpToColor);
ShapeBorder? lerpBorder(StarBorder border, LerpTarget target, double t, {bool to = true}) {
final OutlinedBorder targetBorder = switch (target) {
LerpTarget.circle => const CircleBorder(side: lerpToBorder, eccentricity: 0.5),
LerpTarget.rect => const RoundedRectangleBorder(side: lerpToBorder),
LerpTarget.stadium => const StadiumBorder(side: lerpToBorder),
LerpTarget.polygon => const StarBorder.polygon(side: lerpToBorder, sides: 4),
LerpTarget.star => const StarBorder(side: lerpToBorder, innerRadiusRatio: 0.5),
LerpTarget.roundedRect => RoundedRectangleBorder(side: lerpToBorder, borderRadius: BorderRadius.circular(10)),
LerpTarget.circle => const CircleBorder(side: lerpToBorder, eccentricity: 0.5),
LerpTarget.rect => const RoundedRectangleBorder(side: lerpToBorder),
LerpTarget.stadium => const StadiumBorder(side: lerpToBorder),
LerpTarget.polygon => const StarBorder.polygon(side: lerpToBorder, sides: 4),
LerpTarget.star => const StarBorder(side: lerpToBorder, innerRadiusRatio: 0.5),
LerpTarget.roundedRect => RoundedRectangleBorder(
side: lerpToBorder,
borderRadius: BorderRadius.circular(10),
),
};
return to ? border.lerpTo(targetBorder, t) : border.lerpFrom(targetBorder, t);
}

View File

@@ -11,22 +11,24 @@ import 'package:flutter/scheduler.dart';
int seed = 0;
void main() {
runApp(MaterialApp(
title: 'Text tester',
home: const Home(),
routes: <String, WidgetBuilder>{
'underlines': (BuildContext context) => const Underlines(),
'fallback': (BuildContext context) => const Fallback(),
'bidi': (BuildContext context) => const Bidi(),
'fuzzer': (BuildContext context) => Fuzzer(seed: seed),
'zalgo': (BuildContext context) => Zalgo(seed: seed),
'painting': (BuildContext context) => Painting(seed: seed),
},
));
runApp(
MaterialApp(
title: 'Text tester',
home: const Home(),
routes: <String, WidgetBuilder>{
'underlines': (BuildContext context) => const Underlines(),
'fallback': (BuildContext context) => const Fallback(),
'bidi': (BuildContext context) => const Bidi(),
'fuzzer': (BuildContext context) => Fuzzer(seed: seed),
'zalgo': (BuildContext context) => Zalgo(seed: seed),
'painting': (BuildContext context) => Painting(seed: seed),
},
),
);
}
class Home extends StatefulWidget {
const Home({ super.key });
const Home({super.key});
@override
State<Home> createState() => _HomeState();
@@ -47,7 +49,9 @@ class _HomeState extends State<Home> {
foregroundColor: Colors.white,
backgroundColor: Colors.red.shade800,
),
onPressed: () { Navigator.pushNamed(context, 'underlines'); },
onPressed: () {
Navigator.pushNamed(context, 'underlines');
},
child: const Text('Test Underlines'),
),
TextButton(
@@ -55,7 +59,9 @@ class _HomeState extends State<Home> {
foregroundColor: Colors.white,
backgroundColor: Colors.orange.shade700,
),
onPressed: () { Navigator.pushNamed(context, 'fallback'); },
onPressed: () {
Navigator.pushNamed(context, 'fallback');
},
child: const Text('Test Font Fallback'),
),
TextButton(
@@ -63,7 +69,9 @@ class _HomeState extends State<Home> {
foregroundColor: Colors.black,
backgroundColor: Colors.yellow.shade700,
),
onPressed: () { Navigator.pushNamed(context, 'bidi'); },
onPressed: () {
Navigator.pushNamed(context, 'bidi');
},
child: const Text('Test Bidi Formatting'),
),
TextButton(
@@ -71,7 +79,9 @@ class _HomeState extends State<Home> {
foregroundColor: Colors.black,
backgroundColor: Colors.green.shade400,
),
onPressed: () { Navigator.pushNamed(context, 'fuzzer'); },
onPressed: () {
Navigator.pushNamed(context, 'fuzzer');
},
child: const Text('TextSpan Fuzzer'),
),
TextButton(
@@ -79,7 +89,9 @@ class _HomeState extends State<Home> {
foregroundColor: Colors.white,
backgroundColor: Colors.blue.shade400,
),
onPressed: () { Navigator.pushNamed(context, 'zalgo'); },
onPressed: () {
Navigator.pushNamed(context, 'zalgo');
},
child: const Text('Diacritics Fuzzer'),
),
TextButton(
@@ -87,7 +99,9 @@ class _HomeState extends State<Home> {
foregroundColor: Colors.black,
backgroundColor: Colors.purple.shade200,
),
onPressed: () { Navigator.pushNamed(context, 'painting'); },
onPressed: () {
Navigator.pushNamed(context, 'painting');
},
child: const Text('Painting Fuzzer'),
),
],
@@ -118,7 +132,7 @@ class _HomeState extends State<Home> {
}
class Fuzzer extends StatefulWidget {
const Fuzzer({ super.key, required this.seed });
const Fuzzer({super.key, required this.seed});
final int seed;
@@ -129,7 +143,9 @@ class Fuzzer extends StatefulWidget {
class _FuzzerState extends State<Fuzzer> with SingleTickerProviderStateMixin {
TextSpan _textSpan = const TextSpan(text: 'Welcome to the Flutter text fuzzer.');
late final Ticker _ticker = createTicker(_updateTextSpan)..start();
late final math.Random _random = math.Random(widget.seed); // providing a seed is important for reproducibility;
late final math.Random _random = math.Random(
widget.seed,
); // providing a seed is important for reproducibility;
@override
void initState() {
@@ -153,7 +169,10 @@ class _FuzzerState extends State<Fuzzer> with SingleTickerProviderStateMixin {
return TextSpan(
text: _fiddleWithText(node.text),
style: _fiddleWithStyle(node.style),
children: _fiddleWithChildren(node.children?.map((InlineSpan child) => _fiddleWith(child as TextSpan)).toList() ?? <TextSpan>[]),
children: _fiddleWithChildren(
node.children?.map((InlineSpan child) => _fiddleWith(child as TextSpan)).toList() ??
<TextSpan>[],
),
);
}
@@ -198,7 +217,8 @@ class _FuzzerState extends State<Fuzzer> with SingleTickerProviderStateMixin {
switch (_random.nextInt(10)) {
case 0:
if (value == null) {
return pickFromList<MaterialColor>(_random, Colors.primaries)[(_random.nextInt(9) + 1) * 100];
return pickFromList<MaterialColor>(_random, Colors.primaries)[(_random.nextInt(9) + 1) *
100];
}
switch (_random.nextInt(4)) {
case 0:
@@ -234,13 +254,26 @@ class _FuzzerState extends State<Fuzzer> with SingleTickerProviderStateMixin {
case 30:
return TextDecoration.overline;
case 90:
return TextDecoration.combine(<TextDecoration>[TextDecoration.underline, TextDecoration.lineThrough]);
return TextDecoration.combine(<TextDecoration>[
TextDecoration.underline,
TextDecoration.lineThrough,
]);
case 91:
return TextDecoration.combine(<TextDecoration>[TextDecoration.underline, TextDecoration.overline]);
return TextDecoration.combine(<TextDecoration>[
TextDecoration.underline,
TextDecoration.overline,
]);
case 92:
return TextDecoration.combine(<TextDecoration>[TextDecoration.lineThrough, TextDecoration.overline]);
return TextDecoration.combine(<TextDecoration>[
TextDecoration.lineThrough,
TextDecoration.overline,
]);
case 93:
return TextDecoration.combine(<TextDecoration>[TextDecoration.underline, TextDecoration.lineThrough, TextDecoration.overline]);
return TextDecoration.combine(<TextDecoration>[
TextDecoration.underline,
TextDecoration.lineThrough,
TextDecoration.overline,
]);
}
return null;
}
@@ -352,9 +385,7 @@ class _FuzzerState extends State<Fuzzer> with SingleTickerProviderStateMixin {
}
TextSpan _createRandomTextSpan() {
return TextSpan(
text: _createRandomText(),
);
return TextSpan(text: _createRandomText());
}
String? _createRandomText() {
@@ -493,7 +524,9 @@ class _FuzzerState extends State<Fuzzer> with SingleTickerProviderStateMixin {
if (_random.nextInt(20) > 0) {
buffer.writeCharCode(randomCharacter(_random));
} else {
buffer.write(zalgo(_random, _random.nextInt(2) + 1, includeSpacingCombiningMarks: true));
buffer.write(
zalgo(_random, _random.nextInt(2) + 1, includeSpacingCombiningMarks: true),
);
}
}
return buffer.toString();
@@ -540,14 +573,13 @@ class _FuzzerState extends State<Fuzzer> with SingleTickerProviderStateMixin {
}
class Underlines extends StatefulWidget {
const Underlines({ super.key });
const Underlines({super.key});
@override
State<Underlines> createState() => _UnderlinesState();
}
class _UnderlinesState extends State<Underlines> {
String _text = 'i';
final TextStyle _style = TextStyle(
@@ -563,8 +595,17 @@ class _UnderlinesState extends State<Underlines> {
alignment: Alignment.centerLeft,
heightFactor: 1.0,
child: Container(
decoration: const BoxDecoration(color: Color(0xFF333333), border: Border(right: BorderSide(color: Colors.white, width: 0.0))),
child: Text(_text, style: style != null ? _style.copyWith(decoration: TextDecoration.underline, decorationStyle: style) : _style),
decoration: const BoxDecoration(
color: Color(0xFF333333),
border: Border(right: BorderSide(color: Colors.white, width: 0.0)),
),
child: Text(
_text,
style:
style != null
? _style.copyWith(decoration: TextDecoration.underline, decorationStyle: style)
: _style,
),
),
);
}
@@ -587,7 +628,8 @@ class _UnderlinesState extends State<Underlines> {
child: ListBody(
children: <Widget>[
_wrap(null),
for (final TextDecorationStyle style in TextDecorationStyle.values) _wrap(style),
for (final TextDecorationStyle style in TextDecorationStyle.values)
_wrap(style),
],
),
),
@@ -606,9 +648,7 @@ class _UnderlinesState extends State<Underlines> {
_text += 'i';
});
},
style: TextButton.styleFrom(
backgroundColor: Colors.yellow,
),
style: TextButton.styleFrom(backgroundColor: Colors.yellow),
child: const Text('ADD i'),
),
TextButton(
@@ -617,9 +657,7 @@ class _UnderlinesState extends State<Underlines> {
_text += 'w';
});
},
style: TextButton.styleFrom(
backgroundColor: Colors.yellow,
),
style: TextButton.styleFrom(backgroundColor: Colors.yellow),
child: const Text('ADD w'),
),
TextButton(
@@ -627,11 +665,14 @@ class _UnderlinesState extends State<Underlines> {
foregroundColor: Colors.white,
backgroundColor: Colors.red,
),
onPressed: _text == '' ? null : () {
setState(() {
_text = _text.substring(0, _text.length - 1);
});
},
onPressed:
_text == ''
? null
: () {
setState(() {
_text = _text.substring(0, _text.length - 1);
});
},
child: const Text('REMOVE'),
),
],
@@ -645,14 +686,15 @@ class _UnderlinesState extends State<Underlines> {
}
class Fallback extends StatefulWidget {
const Fallback({ super.key });
const Fallback({super.key});
@override
State<Fallback> createState() => _FallbackState();
}
class _FallbackState extends State<Fallback> {
static const String multiScript = 'A1!aÀàĀāƁƀḂⱠꜲꬰəͲἀἏЀЖԠꙐꙮՁخ‎ࡔࠇܦআਉઐଘஇఘಧൺඣᭆᯔᮯ᳇ꠈᜅᩌꪈ༇ꥄꡙꫤ᧰៘꧁꧂ᜰᨏᯤᢆᣭᗗꗃⵞ𐒎߷ጩꬤ𖠺‡₩℻Ⅷ↹⋇⏳ⓖ╋▒◛⚧⑆שׁ🅕㊼龜ポ䷤🂡';
static const String multiScript =
'A1!aÀàĀāƁƀḂⱠꜲꬰəͲἀἏЀЖԠꙐꙮՁخ‎ࡔࠇܦআਉઐଘஇఘಧൺඣᭆᯔᮯ᳇ꠈᜅᩌꪈ༇ꥄꡙꫤ᧰៘꧁꧂ᜰᨏᯤᢆᣭᗗꗃⵞ𐒎߷ጩꬤ𖠺‡₩℻Ⅷ↹⋇⏳ⓖ╋▒◛⚧⑆שׁ🅕㊼龜ポ䷤🂡';
static const List<String> androidFonts = <String>[
'sans-serif',
@@ -665,10 +707,7 @@ class _FallbackState extends State<Fallback> {
'sans-serif-smallcaps',
];
static const TextStyle style = TextStyle(
inherit: false,
color: Colors.white,
);
static const TextStyle style = TextStyle(inherit: false, color: Colors.white);
double _fontSize = 3.0;
@@ -694,10 +733,7 @@ class _FallbackState extends State<Fallback> {
for (final String font in androidFonts)
Text(
multiScript,
style: style.copyWith(
fontFamily: font,
fontSize: math.exp(_fontSize),
),
style: style.copyWith(fontFamily: font, fontSize: math.exp(_fontSize)),
),
],
),
@@ -712,10 +748,7 @@ class _FallbackState extends State<Fallback> {
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
const Padding(
padding: EdgeInsets.only(bottom: 10.0),
child: Text('Font size'),
),
const Padding(padding: EdgeInsets.only(bottom: 10.0), child: Text('Font size')),
Expanded(
child: Slider(
min: 2.0,
@@ -740,7 +773,7 @@ class _FallbackState extends State<Fallback> {
}
class Bidi extends StatefulWidget {
const Bidi({ super.key });
const Bidi({super.key});
@override
State<Bidi> createState() => _BidiState();
@@ -757,11 +790,46 @@ class _BidiState extends State<Bidi> {
RichText(
text: TextSpan(
children: <TextSpan>[
TextSpan(text: 'abc', style: TextStyle(fontWeight: FontWeight.w100, fontSize: 40.0, color: Colors.blue.shade100)),
TextSpan(text: 'ghi', style: TextStyle(fontWeight: FontWeight.w400, fontSize: 40.0, color: Colors.blue.shade500)),
TextSpan(text: 'mno', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 40.0, color: Colors.blue.shade900)),
TextSpan(text: 'LKJ', style: TextStyle(fontWeight: FontWeight.w500, fontSize: 40.0, color: Colors.blue.shade700)),
TextSpan(text: 'FED', style: TextStyle(fontWeight: FontWeight.w300, fontSize: 40.0, color: Colors.blue.shade300)),
TextSpan(
text: 'abc',
style: TextStyle(
fontWeight: FontWeight.w100,
fontSize: 40.0,
color: Colors.blue.shade100,
),
),
TextSpan(
text: 'ghi',
style: TextStyle(
fontWeight: FontWeight.w400,
fontSize: 40.0,
color: Colors.blue.shade500,
),
),
TextSpan(
text: 'mno',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 40.0,
color: Colors.blue.shade900,
),
),
TextSpan(
text: 'LKJ',
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 40.0,
color: Colors.blue.shade700,
),
),
TextSpan(
text: 'FED',
style: TextStyle(
fontWeight: FontWeight.w300,
fontSize: 40.0,
color: Colors.blue.shade300,
),
),
],
),
textAlign: TextAlign.center,
@@ -770,11 +838,46 @@ class _BidiState extends State<Bidi> {
RichText(
text: TextSpan(
children: <TextSpan>[
TextSpan(text: '${Unicode.LRO}abc', style: TextStyle(fontWeight: FontWeight.w100, fontSize: 40.0, color: Colors.blue.shade100)),
TextSpan(text: '${Unicode.RLO}DEF', style: TextStyle(fontWeight: FontWeight.w300, fontSize: 40.0, color: Colors.blue.shade300)),
TextSpan(text: '${Unicode.LRO}ghi', style: TextStyle(fontWeight: FontWeight.w400, fontSize: 40.0, color: Colors.blue.shade500)),
TextSpan(text: '${Unicode.RLO}JKL', style: TextStyle(fontWeight: FontWeight.w500, fontSize: 40.0, color: Colors.blue.shade700)),
TextSpan(text: '${Unicode.LRO}mno', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 40.0, color: Colors.blue.shade900)),
TextSpan(
text: '${Unicode.LRO}abc',
style: TextStyle(
fontWeight: FontWeight.w100,
fontSize: 40.0,
color: Colors.blue.shade100,
),
),
TextSpan(
text: '${Unicode.RLO}DEF',
style: TextStyle(
fontWeight: FontWeight.w300,
fontSize: 40.0,
color: Colors.blue.shade300,
),
),
TextSpan(
text: '${Unicode.LRO}ghi',
style: TextStyle(
fontWeight: FontWeight.w400,
fontSize: 40.0,
color: Colors.blue.shade500,
),
),
TextSpan(
text: '${Unicode.RLO}JKL',
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 40.0,
color: Colors.blue.shade700,
),
),
TextSpan(
text: '${Unicode.LRO}mno',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 40.0,
color: Colors.blue.shade900,
),
),
],
),
textAlign: TextAlign.center,
@@ -784,9 +887,30 @@ class _BidiState extends State<Bidi> {
RichText(
text: TextSpan(
children: <TextSpan>[
TextSpan(text: '${Unicode.LRO}abc${Unicode.RLO}D', style: TextStyle(fontWeight: FontWeight.w100, fontSize: 40.0, color: Colors.orange.shade100)),
TextSpan(text: 'EF${Unicode.LRO}gh', style: TextStyle(fontWeight: FontWeight.w500, fontSize: 50.0, color: Colors.orange.shade500)),
TextSpan(text: 'i${Unicode.RLO}JKL${Unicode.LRO}mno', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 60.0, color: Colors.orange.shade900)),
TextSpan(
text: '${Unicode.LRO}abc${Unicode.RLO}D',
style: TextStyle(
fontWeight: FontWeight.w100,
fontSize: 40.0,
color: Colors.orange.shade100,
),
),
TextSpan(
text: 'EF${Unicode.LRO}gh',
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 50.0,
color: Colors.orange.shade500,
),
),
TextSpan(
text: 'i${Unicode.RLO}JKL${Unicode.LRO}mno',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 60.0,
color: Colors.orange.shade900,
),
),
],
),
textAlign: TextAlign.center,
@@ -795,19 +919,65 @@ class _BidiState extends State<Bidi> {
RichText(
text: TextSpan(
children: <TextSpan>[
TextSpan(text: 'abc', style: TextStyle(fontWeight: FontWeight.w100, fontSize: 40.0, color: Colors.orange.shade100)),
TextSpan(text: 'gh', style: TextStyle(fontWeight: FontWeight.w500, fontSize: 50.0, color: Colors.orange.shade500)),
TextSpan(text: 'imno', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 60.0, color: Colors.orange.shade900)),
TextSpan(text: 'LKJ', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 60.0, color: Colors.orange.shade900)),
TextSpan(text: 'FE', style: TextStyle(fontWeight: FontWeight.w500, fontSize: 50.0, color: Colors.orange.shade500)),
TextSpan(text: 'D', style: TextStyle(fontWeight: FontWeight.w100, fontSize: 40.0, color: Colors.orange.shade100)),
TextSpan(
text: 'abc',
style: TextStyle(
fontWeight: FontWeight.w100,
fontSize: 40.0,
color: Colors.orange.shade100,
),
),
TextSpan(
text: 'gh',
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 50.0,
color: Colors.orange.shade500,
),
),
TextSpan(
text: 'imno',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 60.0,
color: Colors.orange.shade900,
),
),
TextSpan(
text: 'LKJ',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 60.0,
color: Colors.orange.shade900,
),
),
TextSpan(
text: 'FE',
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 50.0,
color: Colors.orange.shade500,
),
),
TextSpan(
text: 'D',
style: TextStyle(
fontWeight: FontWeight.w100,
fontSize: 40.0,
color: Colors.orange.shade100,
),
),
],
),
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
),
const SizedBox(height: 40.0),
const Text('The pairs of lines above should match exactly.', textAlign: TextAlign.center, style: TextStyle(inherit: false, fontSize: 14.0, color: Colors.white)),
const Text(
'The pairs of lines above should match exactly.',
textAlign: TextAlign.center,
style: TextStyle(inherit: false, fontSize: 14.0, color: Colors.white),
),
],
),
);
@@ -815,7 +985,7 @@ class _BidiState extends State<Bidi> {
}
class Zalgo extends StatefulWidget {
const Zalgo({ super.key, required this.seed });
const Zalgo({super.key, required this.seed});
final int seed;
@@ -866,11 +1036,7 @@ class _ZalgoState extends State<Zalgo> with SingleTickerProviderStateMixin {
child: RichText(
text: TextSpan(
text: _text,
style: TextStyle(
inherit: false,
fontSize: 96.0,
color: Colors.red.shade200,
),
style: TextStyle(inherit: false, fontSize: 96.0, color: Colors.red.shade200),
),
),
),
@@ -921,7 +1087,7 @@ class _ZalgoState extends State<Zalgo> with SingleTickerProviderStateMixin {
}
class Painting extends StatefulWidget {
const Painting({ super.key, required this.seed });
const Painting({super.key, required this.seed});
final int seed;
@@ -955,7 +1121,8 @@ class _PaintingState extends State<Painting> with SingleTickerProviderStateMixin
void _update(Duration? duration) {
setState(() {
final StringBuffer buffer = StringBuffer();
final int targetLength = _random.nextInt(20) + (_ellipsize ? MediaQuery.of(context).size.width.round() : 1);
final int targetLength =
_random.nextInt(20) + (_ellipsize ? MediaQuery.of(context).size.width.round() : 1);
for (int index = 0; index < targetLength; index += 1) {
if (_random.nextInt(5) > 0) {
buffer.writeCharCode(randomCharacter(_random));
@@ -966,13 +1133,18 @@ class _PaintingState extends State<Painting> with SingleTickerProviderStateMixin
_text = buffer.toString();
});
SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
if (mounted && intrinsicKey.currentContext?.size?.height != controlKey.currentContext?.size?.height) {
if (mounted &&
intrinsicKey.currentContext?.size?.height != controlKey.currentContext?.size?.height) {
debugPrint('Found some text that unexpectedly renders at different heights.');
debugPrint('Text: $_text');
debugPrint(_text?.runes.map<String>((int index) {
final String hexa = index.toRadixString(16).padLeft(4, '0');
return 'U+$hexa';
}).join(' '));
debugPrint(
_text?.runes
.map<String>((int index) {
final String hexa = index.toRadixString(16).padLeft(4, '0');
return 'U+$hexa';
})
.join(' '),
);
setState(() {
_ticker.stop();
});
@@ -1000,7 +1172,8 @@ class _PaintingState extends State<Painting> with SingleTickerProviderStateMixin
right: 0.0,
child: Align(
alignment: Alignment.topCenter,
child: IntrinsicWidth( // to test shrink-wrap vs rendering
child: IntrinsicWidth(
// to test shrink-wrap vs rendering
child: RichText(
key: intrinsicKey,
textAlign: TextAlign.center,
@@ -1027,11 +1200,7 @@ class _PaintingState extends State<Painting> with SingleTickerProviderStateMixin
overflow: _ellipsize ? TextOverflow.ellipsis : TextOverflow.clip,
text: TextSpan(
text: _text,
style: const TextStyle(
inherit: false,
fontSize: 28.0,
color: Colors.white,
),
style: const TextStyle(inherit: false, fontSize: 28.0, color: Colors.white),
),
),
),
@@ -1069,9 +1238,7 @@ class _PaintingState extends State<Painting> with SingleTickerProviderStateMixin
});
},
),
const ListTile(
title: Text('There should be no red visible.'),
),
const ListTile(title: Text('There should be no red visible.')),
Container(
alignment: AlignmentDirectional.centerEnd,
@@ -1084,10 +1251,20 @@ class _PaintingState extends State<Painting> with SingleTickerProviderStateMixin
child: const Text('ITERATE'),
),
TextButton(
onPressed: _ticker.isActive ? null : () {
print('The currently visible text is: $_text');
print(_text?.runes.map<String>((int value) => 'U+${value.toRadixString(16).padLeft(4, '0').toUpperCase()}').join(' '));
},
onPressed:
_ticker.isActive
? null
: () {
print('The currently visible text is: $_text');
print(
_text?.runes
.map<String>(
(int value) =>
'U+${value.toRadixString(16).padLeft(4, '0').toUpperCase()}',
)
.join(' '),
);
},
child: const Text('DUMP TEXT TO LOGS'),
),
],
@@ -1102,15 +1279,22 @@ class _PaintingState extends State<Painting> with SingleTickerProviderStateMixin
}
}
String zalgo(math.Random random, int targetLength, { bool includeSpacingCombiningMarks = false, String? base }) {
String zalgo(
math.Random random,
int targetLength, {
bool includeSpacingCombiningMarks = false,
String? base,
}) {
// The following three tables are derived from UnicodeData.txt:
// http://unicode.org/Public/UNIDATA/UnicodeData.txt
// There are three groups, character classes Mc, Me, and Mn.
const List<int> enclosingCombiningMarks = <int>[ // Me
const List<int> enclosingCombiningMarks = <int>[
// Me
0x00488, 0x00489, 0x01ABE, 0x020DD, 0x020DE, 0x020DF, 0x020E0,
0x020E2, 0x020E3, 0x020E4, 0x0A670, 0x0A671, 0x0A672,
];
const List<int> nonspacingCombiningMarks = <int>[ // Mn
const List<int> nonspacingCombiningMarks = <int>[
// Mn
0x00300, 0x00301, 0x00302, 0x00303, 0x00304, 0x00305, 0x00306,
0x00307, 0x00308, 0x00309, 0x0030A, 0x0030B, 0x0030C, 0x0030D,
0x0030E, 0x0030F, 0x00310, 0x00311, 0x00312, 0x00313, 0x00314,
@@ -1364,7 +1548,8 @@ String zalgo(math.Random random, int targetLength, { bool includeSpacingCombinin
0xE01E3, 0xE01E4, 0xE01E5, 0xE01E6, 0xE01E7, 0xE01E8, 0xE01E9,
0xE01EA, 0xE01EB, 0xE01EC, 0xE01ED, 0xE01EE, 0xE01EF,
];
const List<int> spacingCombiningMarks = <int>[ // Mc
const List<int> spacingCombiningMarks = <int>[
// Mc
0x00903, 0x0093B, 0x0093E, 0x0093F, 0x00940, 0x00949, 0x0094A,
0x0094B, 0x0094C, 0x0094E, 0x0094F, 0x00982, 0x00983, 0x009BE,
0x009BF, 0x009C0, 0x009C7, 0x009C8, 0x009CB, 0x009CC, 0x009D7,

View File

@@ -51,17 +51,20 @@ class FakeHttpClientResponse extends Fake implements HttpClientResponse {
final FakeHttpHeaders headers = FakeHttpHeaders();
@override
HttpClientResponseCompressionState get compressionState => HttpClientResponseCompressionState.notCompressed;
HttpClientResponseCompressionState get compressionState =>
HttpClientResponseCompressionState.notCompressed;
@override
StreamSubscription<List<int>> listen(void Function(List<int>)? onData, {
StreamSubscription<List<int>> listen(
void Function(List<int>)? onData, {
void Function()? onDone,
Function? onError,
bool? cancelOnError,
}) {
return Stream<List<int>>.fromIterable(<List<int>>[kTransparentImage])
.listen(onData, onDone: onDone, onError: onError, cancelOnError: cancelOnError);
return Stream<List<int>>.fromIterable(<List<int>>[
kTransparentImage,
]).listen(onData, onDone: onDone, onError: onError, cancelOnError: cancelOnError);
}
}
class FakeHttpHeaders extends Fake implements HttpHeaders { }
class FakeHttpHeaders extends Fake implements HttpHeaders {}