Daveman
Daveman

Reputation: 1096

Is it possible to include Code-Snippets in Dart?

im woking on some kind of (offine) text-to-html-converter. At the moment I have two files:

input.dart

/*gets modified by the user*/
String input = 
"""
Lorem Ipsum.
""";

main.dart

import 'dart:html';
import 'input.dart';

void main() {
  String crazyStuff = input;
}

My problem is, that I always have to worry about the code-parts arrount the text inside of the input.dart file.

What I would like to do is something like this:

input.dart

Lorem Ipsum.

main.dart

import 'dart:html';
import 'input.dart';

void main() {
  String crazyStuff = """
    import 'input.dart'
  """
}

Upvotes: 1

Views: 251

Answers (1)

Danny Tuppeny
Danny Tuppeny

Reputation: 42343

Not really; no.

For non-web-based Dart scripts (eg. executed from the commandline in the Dart VM), you can do it with the File APIs:

# input.txt
Lorem Ipsum.

# app.dart
main() {
  String crazyStuff = new File('input.txt').readAsStringSync();
}

However; based on your 'dart:html' import, I'm guessing you're using the web. You could either make it valid Dart code (as you are), or if you don't mind waiting for an HTTP Request, you could pull it from the server:

main() {
  HttpRequest.getString('input.txt')
    .then((String fileContents) {
      print('Got $fileContents');
    });
}

Note that this would involve a callback when the HTTP Request has completed, so you'd probably want to split the then stuff out into another function.

Upvotes: 1

Related Questions