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 14
  if (_exampleCode == null)
    await _parseExampleCode(bundle);
15
  return _exampleCode![tag];
16 17
}

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

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

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

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