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

import 'dart:async';
6

7 8 9 10 11 12 13 14 15 16 17 18 19
import 'package:flutter/services.dart';

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

Map<String, String> _exampleCode;

Future<String> getExampleCode(String tag, AssetBundle bundle) async {
  if (_exampleCode == null)
    await _parseExampleCode(bundle);
  return _exampleCode[tag];
}

20
Future<void> _parseExampleCode(AssetBundle bundle) async {
21 22
  final String code = await bundle.loadString('lib/gallery/example_code.dart') ??
    '// lib/gallery/example_code.dart not found\n';
23 24 25 26 27 28 29
  _exampleCode = <String, String>{};

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

  List<String> codeBlock;
  String codeTag;

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