OLD | NEW |
| (Empty) |
1 | |
2 library when.example.read_json_file; | |
3 | |
4 import 'dart:async'; | |
5 import 'dart:convert'; | |
6 import 'dart:io'; | |
7 | |
8 import 'package:when/when.dart'; | |
9 | |
10 /// Reads and decodes JSON from [path] asynchronously. | |
11 /// | |
12 /// If [path] does not exist, returns the result of calling [onAbsent]. | |
13 Future readJsonFile(String path, {onAbsent()}) => _readJsonFile( | |
14 path, onAbsent, (file) => file.exists(), (file) => file.readAsString()); | |
15 | |
16 /// Reads and decodes JSON from [path] synchronously. | |
17 /// | |
18 /// If [path] does not exist, returns the result of calling [onAbsent]. | |
19 readJsonFileSync(String path, {onAbsent()}) => _readJsonFile( | |
20 path, onAbsent, (file) => file.existsSync(), | |
21 (file) => file.readAsStringSync()); | |
22 | |
23 _readJsonFile(String path, onAbsent(), exists(File file), read(File file)) { | |
24 var file = new File(path); | |
25 return when( | |
26 () => exists(file), | |
27 onSuccess: (doesExist) => doesExist ? | |
28 when(() => read(file), onSuccess: JSON.decode) : | |
29 onAbsent()); | |
30 } | |
31 | |
32 main() { | |
33 var syncJson = readJsonFileSync('foo.json', onAbsent: () => {'foo': 'bar'}); | |
34 print('Sync json: $syncJson'); | |
35 readJsonFile('foo.json', onAbsent: () => {'foo': 'bar'}).then((asyncJson) { | |
36 print('Async json: $asyncJson'); | |
37 }); | |
38 } | |
OLD | NEW |