Book Image

DART Cookbook

By : Ivo Balbaert
Book Image

DART Cookbook

By: Ivo Balbaert

Overview of this book

Table of Contents (18 chapters)
Dart Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Writing to a file


In this recipe, we demonstrate the three most important ways to write to a file. You can find the code in the project writing_files.

How to do it...

The three ways to write to a file are discussed as follows:

  1. First, we import the packages io and convert as shown in the following code:

    import 'dart:io';
    import 'dart:convert';
    
    void main() {
  2. We can write to a file using writeAsString as shown in the following code:

      final filename = 'outString.txt';
      new File(filename).writeAsString('Dart is an elegant language').then((File file) {
      // do something with the file.
    });
  3. We can write to a file using writeAsBytes as shown in the following code:

      final string = '你好世界';
      // Encode to UTF8.
      var encodedData = UTF8.encode(string);
      new File('outUTF8.txt').writeAsBytes(encodedData).then((file)
      => file.readAsBytes()).then((data) {
      // Decode to a string, and print.
      print(data); 
      // [228, 189, 160, 229, 165, 189, 228, 184, 150, 231, 149, 140]
      print(UTF8.decode(data)); // prints...