diff --git a/packages/flutter_tools/lib/src/commands/create.dart b/packages/flutter_tools/lib/src/commands/create.dart index 6bb780e89b..6a97448f25 100644 --- a/packages/flutter_tools/lib/src/commands/create.dart +++ b/packages/flutter_tools/lib/src/commands/create.dart @@ -239,13 +239,21 @@ class CreateCommand extends FlutterCommand { } final Uri snippetsUri = Uri.https(_snippetsHost, 'snippets/$sampleId.dart'); - return utf8.decode(await _net.fetchUrl(snippetsUri)); + final List data = await _net.fetchUrl(snippetsUri); + if (data == null || data.isEmpty) { + return null; + } + return utf8.decode(data); } /// Fetches the samples index file from the Flutter docs website. Future _fetchSamplesIndexFromServer() async { final Uri snippetsUri = Uri.https(_snippetsHost, 'snippets/index.json'); - return utf8.decode(await _net.fetchUrl(snippetsUri, maxAttempts: 2)); + final List data = await _net.fetchUrl(snippetsUri, maxAttempts: 2); + if (data == null || data.isEmpty) { + return null; + } + return utf8.decode(data); } /// Fetches the samples index file from the server and writes it to @@ -259,8 +267,7 @@ class CreateCommand extends FlutterCommand { final String samplesJson = await _fetchSamplesIndexFromServer(); if (samplesJson == null) { throwToolExit('Unable to download samples', exitCode: 2); - } - else { + } else { outputFile.writeAsStringSync(samplesJson); globals.printStatus('Wrote samples JSON to "$outputFilePath"'); } diff --git a/packages/flutter_tools/test/commands.shard/permeable/create_test.dart b/packages/flutter_tools/test/commands.shard/permeable/create_test.dart index 6cd682d932..62afce0348 100644 --- a/packages/flutter_tools/test/commands.shard/permeable/create_test.dart +++ b/packages/flutter_tools/test/commands.shard/permeable/create_test.dart @@ -1283,6 +1283,28 @@ void main() { HttpClientFactory: () => () => MockHttpClient(200, result: samplesIndexJson), }); + + testUsingContext('Throws tool exit on empty samples index', () async { + final String outputFile = globals.fs.path.join(tempDir.path, 'flutter_samples.json'); + final CreateCommand command = CreateCommand(); + final CommandRunner runner = createTestCommandRunner(command); + final List args = [ + 'create', + '--list-samples', + outputFile, + ]; + + await expectLater( + runner.run(args), + throwsToolExit( + exitCode: 2, + message: 'Unable to download samples', + )); + }, overrides: { + HttpClientFactory: () => + () => MockHttpClient(200, result: ''), + }); + testUsingContext('provides an error to the user if samples json download fails', () async { final String outputFile = globals.fs.path.join(tempDir.path, 'flutter_samples.json'); final CreateCommand command = CreateCommand();