demo.dart 7.33 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:flutter/cupertino.dart';
6
import 'package:flutter/material.dart';
7
import 'package:url_launcher/url_launcher.dart';
8

9
import 'demos.dart';
10
import 'example_code_parser.dart';
11
import 'syntax_highlighter.dart';
12

13
@immutable
14
class ComponentDemoTabData {
15
  const ComponentDemoTabData({
16
    this.demoWidget,
17
    this.exampleCodeTag,
18
    this.description,
19 20
    this.tabName,
    this.documentationUrl,
21 22
  });

23 24 25 26 27
  final Widget? demoWidget;
  final String? exampleCodeTag;
  final String? description;
  final String? tabName;
  final String? documentationUrl;
28 29 30 31 32

  @override
  bool operator==(Object other) {
    if (other.runtimeType != runtimeType)
      return false;
33 34 35 36
    return other is ComponentDemoTabData
        && other.tabName == tabName
        && other.description == description
        && other.documentationUrl == documentationUrl;
37 38 39
  }

  @override
40
  int get hashCode => Object.hash(tabName, description, documentationUrl);
41 42 43
}

class TabbedComponentDemoScaffold extends StatelessWidget {
44
  const TabbedComponentDemoScaffold({
45
    super.key,
46
    this.title,
47 48
    this.demos,
    this.actions,
49 50
    this.isScrollable = true,
    this.showExampleCodeAction = true,
51
  });
52

53 54 55
  final List<ComponentDemoTabData>? demos;
  final String? title;
  final List<Widget>? actions;
56 57
  final bool isScrollable;
  final bool showExampleCodeAction;
58

59
  void _showExampleCode(BuildContext context) {
60
    final String? tag = demos![DefaultTabController.of(context)!.index].exampleCodeTag;
61
    if (tag != null) {
62 63
      Navigator.push(context, MaterialPageRoute<FullScreenCodeDialog>(
        builder: (BuildContext context) => FullScreenCodeDialog(exampleCodeTag: tag)
64 65 66 67
      ));
    }
  }

68
  Future<void> _showApiDocumentation(BuildContext context) async {
69
    final String? url = demos![DefaultTabController.of(context)!.index].documentationUrl;
70 71 72
    if (url == null)
      return;

73 74 75
    final Uri uri = Uri.parse(url);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
76 77 78 79 80
    } else {
      showDialog<void>(
        context: context,
        builder: (BuildContext context) {
          return SimpleDialog(
81
            title: const Text("Couldn't display URL:"),
82 83 84 85 86 87 88 89 90
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(url),
              ),
            ],
          );
        },
      );
91 92 93
    }
  }

94 95
  @override
  Widget build(BuildContext context) {
96
    return DefaultTabController(
97
      length: demos!.length,
98 99
      child: Scaffold(
        appBar: AppBar(
100
          title: Text(title!),
101 102
          actions: <Widget>[
            ...?actions,
103 104 105 106 107 108 109 110
            Builder(
              builder: (BuildContext context) {
                return IconButton(
                  icon: const Icon(Icons.library_books, semanticLabel: 'Show documentation'),
                  onPressed: () => _showApiDocumentation(context),
                );
              },
            ),
111 112 113 114 115 116 117 118 119 120 121
            if (showExampleCodeAction)
              Builder(
                builder: (BuildContext context) {
                  return IconButton(
                    icon: const Icon(Icons.code),
                    tooltip: 'Show example code',
                    onPressed: () => _showExampleCode(context),
                  );
                },
              ),
          ],
122
          bottom: TabBar(
123
            isScrollable: isScrollable,
124
            tabs: demos!.map<Widget>((ComponentDemoTabData data) => Tab(text: data.tabName)).toList(),
Hans Muller's avatar
Hans Muller committed
125
          ),
126
        ),
127
        body: TabBarView(
128
          children: demos!.map<Widget>((ComponentDemoTabData demo) {
129
            return SafeArea(
130 131
              top: false,
              bottom: false,
132
              child: Column(
133
                children: <Widget>[
134
                  Padding(
135
                    padding: const EdgeInsets.all(16.0),
136
                    child: Text(demo.description!,
137
                      style: Theme.of(context).textTheme.subtitle1,
138
                    ),
139
                  ),
140
                  Expanded(child: demo.demoWidget!),
141 142
                ],
              ),
143
            );
Hans Muller's avatar
Hans Muller committed
144 145 146
          }).toList(),
        ),
      ),
147 148 149 150
    );
  }
}

151
class FullScreenCodeDialog extends StatefulWidget {
152
  const FullScreenCodeDialog({ super.key, this.exampleCodeTag });
153

154
  final String? exampleCodeTag;
155 156

  @override
157
  FullScreenCodeDialogState createState() => FullScreenCodeDialogState();
158 159 160
}

class FullScreenCodeDialogState extends State<FullScreenCodeDialog> {
161

162
  String? _exampleCode;
163 164

  @override
165
  void didChangeDependencies() {
166
    getExampleCode(widget.exampleCodeTag, DefaultAssetBundle.of(context)).then((String? code) {
167 168
      if (mounted) {
        setState(() {
169
          _exampleCode = code ?? 'Example code not found';
170 171
        });
      }
172
    });
173
    super.didChangeDependencies();
174
  }
175 176 177

  @override
  Widget build(BuildContext context) {
178 179 180 181
    final SyntaxHighlighterStyle style = Theme.of(context).brightness == Brightness.dark
      ? SyntaxHighlighterStyle.darkThemeStyle()
      : SyntaxHighlighterStyle.lightThemeStyle();

182 183
    Widget body;
    if (_exampleCode == null) {
184
      body = const Center(
185
        child: CircularProgressIndicator(),
186 187
      );
    } else {
188 189
      body = SingleChildScrollView(
        child: Padding(
190
          padding: const EdgeInsets.all(16.0),
191 192
          child: RichText(
            text: TextSpan(
193
              style: const TextStyle(fontFamily: 'monospace', fontSize: 10.0),
194
              children: <TextSpan>[
195 196 197 198 199
                DartSyntaxHighlighter(style).format(_exampleCode),
              ],
            ),
          ),
        ),
200 201 202
      );
    }

203 204 205
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
206 207 208 209
          icon: const Icon(
            Icons.clear,
            semanticLabel: 'Close',
          ),
210
          onPressed: () { Navigator.pop(context); },
211
        ),
212
        title: const Text('Example code'),
213
      ),
214
      body: body,
215 216 217
    );
  }
}
218 219

class MaterialDemoDocumentationButton extends StatelessWidget {
220
  MaterialDemoDocumentationButton(String routeName, { super.key })
221 222 223 224
    : documentationUrl = kDemoDocumentationUrl[routeName],
      assert(
        kDemoDocumentationUrl[routeName] != null,
        'A documentation URL was not specified for demo route $routeName in kAllGalleryDemos',
225
      );
226

227
  final String? documentationUrl;
228 229 230 231 232

  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: const Icon(Icons.library_books),
233
      tooltip: 'API documentation',
234
      onPressed: () => launchUrl(Uri.parse(documentationUrl!), mode: LaunchMode.inAppWebView),
235 236 237 238 239
    );
  }
}

class CupertinoDemoDocumentationButton extends StatelessWidget {
240
  CupertinoDemoDocumentationButton(String routeName, { super.key })
241 242 243 244
    : documentationUrl = kDemoDocumentationUrl[routeName],
      assert(
        kDemoDocumentationUrl[routeName] != null,
        'A documentation URL was not specified for demo route $routeName in kAllGalleryDemos',
245
      );
246

247
  final String? documentationUrl;
248 249 250 251 252

  @override
  Widget build(BuildContext context) {
    return CupertinoButton(
      padding: EdgeInsets.zero,
253 254 255 256
      child: Semantics(
        label: 'API documentation',
        child: const Icon(CupertinoIcons.book),
      ),
257
      onPressed: () => launchUrl(Uri.parse(documentationUrl!), mode: LaunchMode.inAppWebView),
258 259 260
    );
  }
}