Extract Sample code into examples/api (#87280)

This extracts the sample code out from the API doc comments, and places them in separate files on disk, allowing running of the examples locally, testing them, and building of slightly larger examples.
This commit is contained in:
Greg Spencer
2021-08-25 09:45:12 -07:00
committed by GitHub
parent 527d868391
commit 33403bd28e
458 changed files with 29206 additions and 11513 deletions

View File

@@ -0,0 +1,201 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Template: dev/snippets/config/templates/freeform.tmpl
//
// Comment lines marked with "▼▼▼" and "▲▲▲" are used for authoring
// of samples, and may be ignored if you are just exploring the sample.
// Flutter code sample for Action.Action.overridable
//
//***************************************************************************
//* ▼▼▼▼▼▼▼▼ description ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
// This sample implements a custom text input field that handles the
// [DeleteTextIntent] intent, as well as a US telephone number input widget
// that consists of multiple text fields for area code, prefix and line
// number. When the backspace key is pressed, the phone number input widget
// sends the focus to the preceding text field when the currently focused
// field becomes empty.
//* ▲▲▲▲▲▲▲▲ description ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//***************************************************************************
//****************************************************************************
//* ▼▼▼▼▼▼▼▼ code-imports ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
//* ▲▲▲▲▲▲▲▲ code-imports ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//****************************************************************************
//*************************************************************************
//* ▼▼▼▼▼▼▼▼ code-main ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
void main() {
runApp(
const MaterialApp(
home: Scaffold(
body: Center(child: SimpleUSPhoneNumberEntry()),
),
),
);
}
//* ▲▲▲▲▲▲▲▲ code-main ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//*************************************************************************
//********************************************************************
//* ▼▼▼▼▼▼▼▼ code ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
// This implements a custom phone number input field that handles the
// [DeleteTextIntent] intent.
class DigitInput extends StatefulWidget {
const DigitInput({
Key? key,
required this.controller,
required this.focusNode,
this.maxLength,
this.textInputAction = TextInputAction.next,
}) : super(key: key);
final int? maxLength;
final TextEditingController controller;
final TextInputAction textInputAction;
final FocusNode focusNode;
@override
DigitInputState createState() => DigitInputState();
}
class DigitInputState extends State<DigitInput> {
late final Action<DeleteTextIntent> _deleteTextAction =
CallbackAction<DeleteTextIntent>(
onInvoke: (DeleteTextIntent intent) {
// For simplicity we delete everything in the section.
widget.controller.clear();
},
);
@override
Widget build(BuildContext context) {
return Actions(
actions: <Type, Action<Intent>>{
// Make the default `DeleteTextIntent` handler overridable.
DeleteTextIntent: Action<DeleteTextIntent>.overridable(
defaultAction: _deleteTextAction, context: context),
},
child: TextField(
controller: widget.controller,
textInputAction: TextInputAction.next,
keyboardType: TextInputType.phone,
focusNode: widget.focusNode,
decoration: const InputDecoration(
border: OutlineInputBorder(),
),
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(widget.maxLength),
],
),
);
}
}
class SimpleUSPhoneNumberEntry extends StatefulWidget {
const SimpleUSPhoneNumberEntry({Key? key}) : super(key: key);
@override
State<SimpleUSPhoneNumberEntry> createState() =>
_SimpleUSPhoneNumberEntryState();
}
class _DeleteDigit extends Action<DeleteTextIntent> {
_DeleteDigit(this.state);
final _SimpleUSPhoneNumberEntryState state;
@override
Object? invoke(DeleteTextIntent intent) {
assert(callingAction != null);
callingAction?.invoke(intent);
if (state.lineNumberController.text.isEmpty &&
state.lineNumberFocusNode.hasFocus) {
state.prefixFocusNode.requestFocus();
}
if (state.prefixController.text.isEmpty && state.prefixFocusNode.hasFocus) {
state.areaCodeFocusNode.requestFocus();
}
}
// This action is only enabled when the `callingAction` exists and is
// enabled.
@override
bool get isActionEnabled => callingAction?.isActionEnabled ?? false;
}
class _SimpleUSPhoneNumberEntryState extends State<SimpleUSPhoneNumberEntry> {
final FocusNode areaCodeFocusNode = FocusNode();
final TextEditingController areaCodeController = TextEditingController();
final FocusNode prefixFocusNode = FocusNode();
final TextEditingController prefixController = TextEditingController();
final FocusNode lineNumberFocusNode = FocusNode();
final TextEditingController lineNumberController = TextEditingController();
@override
Widget build(BuildContext context) {
return Actions(
actions: <Type, Action<Intent>>{
DeleteTextIntent: _DeleteDigit(this),
},
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
const Expanded(
child: Text(
'(',
textAlign: TextAlign.center,
),
flex: 1),
Expanded(
child: DigitInput(
focusNode: areaCodeFocusNode,
controller: areaCodeController,
maxLength: 3),
flex: 3),
const Expanded(
child: Text(
')',
textAlign: TextAlign.center,
),
flex: 1),
Expanded(
child: DigitInput(
focusNode: prefixFocusNode,
controller: prefixController,
maxLength: 3),
flex: 3),
const Expanded(
child: Text(
'-',
textAlign: TextAlign.center,
),
flex: 1),
Expanded(
child: DigitInput(
focusNode: lineNumberFocusNode,
controller: lineNumberController,
textInputAction: TextInputAction.done,
maxLength: 4),
flex: 4),
],
),
);
}
}
//* ▲▲▲▲▲▲▲▲ code ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//********************************************************************

View File

@@ -0,0 +1,156 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Template: dev/snippets/config/templates/stateful_widget_scaffold_center.tmpl
//
// Comment lines marked with "▼▼▼" and "▲▲▲" are used for authoring
// of samples, and may be ignored if you are just exploring the sample.
// Flutter code sample for ActionListener
//
//***************************************************************************
//* ▼▼▼▼▼▼▼▼ description ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
// This example shows how ActionListener handles adding and removing of
// the [listener] in the widget lifecycle.
//* ▲▲▲▲▲▲▲▲ description ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//***************************************************************************
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatefulWidget(),
),
),
);
}
}
//*****************************************************************************
//* ▼▼▼▼▼▼▼▼ code-preamble ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
class ActionListenerExample extends StatefulWidget {
const ActionListenerExample({Key? key}) : super(key: key);
@override
State<ActionListenerExample> createState() => _ActionListenerExampleState();
}
class _ActionListenerExampleState extends State<ActionListenerExample> {
bool _on = false;
late final MyAction _myAction;
@override
void initState() {
super.initState();
_myAction = MyAction();
}
void _toggleState() {
setState(() {
_on = !_on;
});
}
@override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: OutlinedButton(
onPressed: _toggleState,
child: Text(_on ? 'Disable' : 'Enable'),
),
),
if (_on)
Padding(
padding: const EdgeInsets.all(8.0),
child: ActionListener(
listener: (Action<Intent> action) {
if (action.intentType == MyIntent) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Action Listener Called'),
));
}
},
action: _myAction,
child: ElevatedButton(
onPressed: () => const ActionDispatcher()
.invokeAction(_myAction, const MyIntent()),
child: const Text('Call Action Listener'),
),
),
),
if (!_on) Container(),
],
);
}
}
class MyAction extends Action<MyIntent> {
@override
void addActionListener(ActionListenerCallback listener) {
super.addActionListener(listener);
print('Action Listener was added');
}
@override
void removeActionListener(ActionListenerCallback listener) {
super.removeActionListener(listener);
print('Action Listener was removed');
}
@override
void invoke(covariant MyIntent intent) {
notifyActionListeners();
}
}
class MyIntent extends Intent {
const MyIntent();
}
//* ▲▲▲▲▲▲▲▲ code-preamble ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//*****************************************************************************
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
//********************************************************************
//* ▼▼▼▼▼▼▼▼ code ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
@override
Widget build(BuildContext context) {
return const ActionListenerExample();
}
//* ▲▲▲▲▲▲▲▲ code ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//********************************************************************
}

View File

@@ -0,0 +1,219 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Template: dev/snippets/config/templates/stateful_widget_scaffold_center.tmpl
//
// Comment lines marked with "▼▼▼" and "▲▲▲" are used for authoring
// of samples, and may be ignored if you are just exploring the sample.
// Flutter code sample for Actions
//
//***************************************************************************
//* ▼▼▼▼▼▼▼▼ description ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
// This example creates a custom [Action] subclass `ModifyAction` for modifying
// a model, and another, `SaveAction` for saving it.
//
// This example demonstrates passing arguments to the [Intent] to be carried to
// the [Action]. Actions can get data either from their own construction (like
// the `model` in this example), or from the intent passed to them when invoked
// (like the increment `amount` in this example).
//
// This example also demonstrates how to use Intents to limit a widget's
// dependencies on its surroundings. The `SaveButton` widget defined in this
// example can invoke actions defined in its ancestor widgets, which can be
// customized to match the part of the widget tree that it is in. It doesn't
// need to know about the `SaveAction` class, only the `SaveIntent`, and it
// only needs to know about a value notifier, not the entire model.
//* ▲▲▲▲▲▲▲▲ description ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//***************************************************************************
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatefulWidget(),
),
),
);
}
}
//*****************************************************************************
//* ▼▼▼▼▼▼▼▼ code-preamble ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
// A simple model class that notifies listeners when it changes.
class Model {
ValueNotifier<bool> isDirty = ValueNotifier<bool>(false);
ValueNotifier<int> data = ValueNotifier<int>(0);
int save() {
if (isDirty.value) {
print('Saved Data: ${data.value}');
isDirty.value = false;
}
return data.value;
}
void setValue(int newValue) {
isDirty.value = data.value != newValue;
data.value = newValue;
}
}
class ModifyIntent extends Intent {
const ModifyIntent(this.value);
final int value;
}
// An Action that modifies the model by setting it to the value that it gets
// from the Intent passed to it when invoked.
class ModifyAction extends Action<ModifyIntent> {
ModifyAction(this.model);
final Model model;
@override
void invoke(covariant ModifyIntent intent) {
model.setValue(intent.value);
}
}
// An intent for saving data.
class SaveIntent extends Intent {
const SaveIntent();
}
// An Action that saves the data in the model it is created with.
class SaveAction extends Action<SaveIntent> {
SaveAction(this.model);
final Model model;
@override
int invoke(covariant SaveIntent intent) => model.save();
}
class SaveButton extends StatefulWidget {
const SaveButton(this.valueNotifier, {Key? key}) : super(key: key);
final ValueNotifier<bool> valueNotifier;
@override
State<SaveButton> createState() => _SaveButtonState();
}
class _SaveButtonState extends State<SaveButton> {
int savedValue = 0;
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: widget.valueNotifier,
builder: (BuildContext context, Widget? child) {
return TextButton.icon(
icon: const Icon(Icons.save),
label: Text('$savedValue'),
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(
widget.valueNotifier.value ? Colors.red : Colors.green,
),
),
onPressed: () {
setState(() {
savedValue = Actions.invoke(context, const SaveIntent())! as int;
});
},
);
},
);
}
}
//* ▲▲▲▲▲▲▲▲ code-preamble ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//*****************************************************************************
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
//********************************************************************
//* ▼▼▼▼▼▼▼▼ code ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
Model model = Model();
int count = 0;
@override
Widget build(BuildContext context) {
return Actions(
actions: <Type, Action<Intent>>{
ModifyIntent: ModifyAction(model),
SaveIntent: SaveAction(model),
},
child: Builder(
builder: (BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
const Spacer(),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: const Icon(Icons.exposure_plus_1),
onPressed: () {
Actions.invoke(context, ModifyIntent(++count));
},
),
AnimatedBuilder(
animation: model.data,
builder: (BuildContext context, Widget? child) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text('${model.data.value}',
style: Theme.of(context).textTheme.headline4),
);
}),
IconButton(
icon: const Icon(Icons.exposure_minus_1),
onPressed: () {
Actions.invoke(context, ModifyIntent(--count));
},
),
],
),
SaveButton(model.isDirty),
const Spacer(),
],
);
},
),
);
}
//* ▲▲▲▲▲▲▲▲ code ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//********************************************************************
}

View File

@@ -0,0 +1,194 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Template: dev/snippets/config/templates/stateful_widget_material.tmpl
//
// Comment lines marked with "▼▼▼" and "▲▲▲" are used for authoring
// of samples, and may be ignored if you are just exploring the sample.
// Flutter code sample for FocusableActionDetector
//
//***************************************************************************
//* ▼▼▼▼▼▼▼▼ description ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
// This example shows how keyboard interaction can be added to a custom control
// that changes color when hovered and focused, and can toggle a light when
// activated, either by touch or by hitting the `X` key on the keyboard when
// the "And Me" button has the keyboard focus (be sure to use TAB to move the
// focus to the "And Me" button before trying it out).
//
// This example defines its own key binding for the `X` key, but in this case,
// there is also a default key binding for [ActivateAction] in the default key
// bindings created by [WidgetsApp] (the parent for [MaterialApp], and
// [CupertinoApp]), so the `ENTER` key will also activate the buttons.
//* ▲▲▲▲▲▲▲▲ description ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//***************************************************************************
import 'package:flutter/material.dart';
//****************************************************************************
//* ▼▼▼▼▼▼▼▼ code-imports ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
import 'package:flutter/services.dart';
//* ▲▲▲▲▲▲▲▲ code-imports ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//****************************************************************************
void main() => runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
//*****************************************************************************
//* ▼▼▼▼▼▼▼▼ code-preamble ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
class FadButton extends StatefulWidget {
const FadButton({
Key? key,
required this.onPressed,
required this.child,
}) : super(key: key);
final VoidCallback onPressed;
final Widget child;
@override
State<FadButton> createState() => _FadButtonState();
}
class _FadButtonState extends State<FadButton> {
bool _focused = false;
bool _hovering = false;
bool _on = false;
late final Map<Type, Action<Intent>> _actionMap;
final Map<ShortcutActivator, Intent> _shortcutMap =
const <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.keyX): ActivateIntent(),
};
@override
void initState() {
super.initState();
_actionMap = <Type, Action<Intent>>{
ActivateIntent: CallbackAction<Intent>(
onInvoke: (Intent intent) => _toggleState(),
),
};
}
Color get color {
Color baseColor = Colors.lightBlue;
if (_focused) {
baseColor = Color.alphaBlend(Colors.black.withOpacity(0.25), baseColor);
}
if (_hovering) {
baseColor = Color.alphaBlend(Colors.black.withOpacity(0.1), baseColor);
}
return baseColor;
}
void _toggleState() {
setState(() {
_on = !_on;
});
}
void _handleFocusHighlight(bool value) {
setState(() {
_focused = value;
});
}
void _handleHoveHighlight(bool value) {
setState(() {
_hovering = value;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _toggleState,
child: FocusableActionDetector(
actions: _actionMap,
shortcuts: _shortcutMap,
onShowFocusHighlight: _handleFocusHighlight,
onShowHoverHighlight: _handleHoveHighlight,
child: Row(
children: <Widget>[
Container(
padding: const EdgeInsets.all(10.0),
color: color,
child: widget.child,
),
Container(
width: 30,
height: 30,
margin: const EdgeInsets.all(10.0),
color: _on ? Colors.red : Colors.transparent,
),
],
),
),
);
}
}
//* ▲▲▲▲▲▲▲▲ code-preamble ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//*****************************************************************************
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
//********************************************************************
//* ▼▼▼▼▼▼▼▼ code ▼▼▼▼▼▼▼▼ (do not modify or remove section marker)
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('FocusableActionDetector Example'),
),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child:
TextButton(onPressed: () {}, child: const Text('Press Me')),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: FadButton(onPressed: () {}, child: const Text('And Me')),
),
],
),
),
);
}
//* ▲▲▲▲▲▲▲▲ code ▲▲▲▲▲▲▲▲ (do not modify or remove section marker)
//********************************************************************
}