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

import 'package:flutter/services.dart';

const String _kStartTag = '// START ';
const String _kEndTag = '// END';

10
Map<String?, String>? _exampleCode;
11

12
Future<String?> getExampleCode(String? tag, AssetBundle bundle) async {
13
  if (_exampleCode == null) {
14
    await _parseExampleCode(bundle);
15
  }
16
  return _exampleCode![tag];
17 18
}

19
Future<void> _parseExampleCode(AssetBundle bundle) async {
20 21
  final String code = await bundle.loadString('lib/gallery/example_code.dart');
  _exampleCode = <String?, String>{};
22 23 24

  final List<String> lines = code.split('\n');

25 26
  List<String>? codeBlock;
  String? codeTag;
27

28
  for (final String line in lines) {
29 30 31 32 33
    if (codeBlock == null) {
      // Outside a block.
      if (line.startsWith(_kStartTag)) {
        // Starting a new code block.
        codeBlock = <String>[];
34
        codeTag = line.substring(_kStartTag.length).trim();
35 36 37 38 39 40 41
      } else {
        // Just skipping the line.
      }
    } else {
      // Inside a block.
      if (line.startsWith(_kEndTag)) {
        // Add the block.
42
        _exampleCode![codeTag] = codeBlock.join('\n');
43 44 45 46
        codeBlock = null;
        codeTag = null;
      } else {
        // Add to the current block
47 48 49
        // trimRight() to remove any \r on Windows
        // without removing any useful indentation
        codeBlock.add(line.trimRight());
50 51 52 53
      }
    }
  }
}