flutter how to check sync if asset exists
- User
flutter how to check sync if asset exists
- Assistant
To check if an asset exists in Flutter, you can use the
rootBundleobject that is part of the Flutter framework.rootBundleprovides a way to read files from the app's asset bundle.To check if an asset exists, you can use the
rootBundle.loadmethod which returns aFuture<ByteData>object. If the asset exists, the returnedFuturewill complete successfully with the data from the asset. If the asset does not exist, theFuturewill complete with an error.Here's an example function that checks if an asset file exists:
codeimport 'dart:async' show Future; import 'package:flutter/services.dart' show rootBundle; Future<bool> assetExists(String assetName) async { try { await rootBundle.load(assetName); return true; } catch (e) { return false; } }This function takes an
assetNameparameter and returns aFuture<bool>object indicating whether the asset exists. If the asset exists, theFuturecompletes with a value oftrue. If the asset does not exist, the completes with a value of . - User
i asked for sync solution
- Assistant
To check if an asset exists synchronously, you can use the
rootBundleobject'scontainsmethod. Thecontainsmethod returns a boolean value indicating whether the asset exists in the app's asset bundle or not.Here's an example of how to check if an asset exists synchronously:
codeimport 'package:flutter/services.dart' show rootBundle; bool assetExists(String assetName) { return rootBundle.contains(assetName); }This function takes an
assetNameparameter and returns a boolean value indicating whether the asset exists synchronously. If the asset exists, the function returnstrue. If the asset does not exist, the function returnsfalse. - User
give a reference to rootBunde.contains
- Assistant
Sure, here's a reference to the
containsmethod of therootBundleobject in Flutter:code