aws-amplify / amplify-flutter

A declarative library with an easy-to-use interface for building Flutter applications on AWS.
https://docs.amplify.aws
Apache License 2.0
1.32k stars 248 forks source link

An unknown exception has happened. #2416

Closed YawarOsman closed 1 year ago

YawarOsman commented 1 year ago

Description

I've tried to query my data in DataStore at the beginning of the screen i mean inside inItState, and i configured Amplify inside main method, so my problem is here when i try to fetch the data it shows this error (this is the exact error when i get in catchError method) :

DataStoreException (message: An unknown exception has happened. Please take a look at I/flutter (12458): https://github.com/aws-amplify/amplify-flutter/issues to see if there are any existing issues that I/flutter (12458): match your scenario, and file an issue with the details of the bug if there isn't. I/flutter (12458): , recoverySuggestion: We currently don't have a recovery suggestion for this exception., underlyingException: PlatformException(error, Tried to get a plugin before it was configured. Make sure you call Amplify.configure() first., null, java.lang.IllegalStateException: Tried to get a plugin before it was configured. Make sure you call Amplify.configure() first.

I also checked if the amplify is configure or not before fetching the data, so it's not configured, because configuring Amplify takes some time and the program will pass fetching data method cause i've set a condition for it as shows down below.

Packages I've used:

amplify_flutter: ^0.6.8 amplify_auth_cognito: ^0.6.8 amplify_api: ^0.6.8 amplify_datastore: ^0.6.8 amplify_storage_s3: ^0.6.8

flutter --version:

Flutter 3.3.6 • channel stable • https://github.com/flutter/flutter.git Framework • revision 6928314d50 (4 weeks ago) • 2022-10-25 16:34:41 -0400 Engine • revision 3ad69d7be3 Tools • Dart 2.18.2 • DevTools 2.15.0

This is Main file code:


bool isFirstTime = true;
bool isDark = false;
bool isLoggedIn = false;

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
      overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom]);

  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    systemNavigationBarColor: Colors.transparent,
    statusBarColor: Colors.transparent,
  ));
  runApp(MultiProvider(providers: [
    ListenableProvider(create: (context) => Data()),
    ListenableProvider(create: (context) => Log()),
    ListenableProvider(create: (context) => Helper()),
    ListenableProvider(create: (context) => RoomStates()),
  ], child: const MainWidget()));
}

class MainWidget extends StatefulWidget {
  const MainWidget({Key? key}) : super(key: key);

  @override
  State<MainWidget> createState() => _MainWidgetState();
}

class _MainWidgetState extends State<MainWidget> {
  final Helper helper = Helper();

  @override
  void initState() {
    super.initState();

    helper.configureAmplify().then((value) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        context.read<Log>().setAmplifyConfigured = true;
      });
    });

    getLogData();
    envLoad();
  }

  void envLoad() async {
    await dotenv.load();
  }

  getLogData() async {
    if (!mounted) return;
    isDark = await context.read<Log>().getIsDark;
    isFirstTime = await context.read<Log>().getIsFirstTime;
    isLoggedIn = await context.read<Log>().getIsLoggedIn;

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
      home: Provider.of<Log>(context).isLoggedIn ? Home() : SignIn(),
    );
  }
}

This is helper.configureAmplify() method:

Future configureAmplify() async {
    if (Amplify.isConfigured) {
      return;
    }
    try {
      await Future.wait([
        Amplify.addPlugins([
          AmplifyAuthCognito(),
          AmplifyDataStore(modelProvider: ModelProvider.instance),
          AmplifyAPI(modelProvider: ModelProvider.instance),
          AmplifyStorageS3(),
        ])
      ]);
      await Amplify.configure(amplifyconfig)
          .then((value) => debugPrint('Amplify configured'));
    } on AmplifyAlreadyConfiguredException {
      debugPrint('amplify configuration error');
    }
  }

This my code where i retrieved the data:


class _HomeState extends State<Home> {

  @override
  void initState() {
    super.initState();

    getRooms();
    }

  void getRooms() async {
    try {
      await Amplify.DataStore.query(Rooms.classType).then((value) {
        context.read<Data>().setRooms(value);
      }).catchError((error) {
        print('$error');
        showDialog(
            context: context,
            builder: (context) => AlertDialog(
                  title:
                      const Text('An error occured, please open the app again'),
                  content: Text(err.toString()),
                  actions: [
                    TextButton(
                        onPressed: () {
                          Navigator.pop(context);
                          SystemNavigator.pop();
                        },
                        child: const Text('Ok'))
                  ],
                ));
      });

    } catch (e) {
      debugPrint(e.toString());
    }
  }
@override
  Widget build(BuildContext context) {
   }
}
This is exactly what is happens when i print 'error' in catchError() > DataStoreException(message: An unknown exception has happened. Please take a look at > I/flutter (12458): https://github.com/aws-amplify/amplify-flutter/issues to see if there are any existing issues that > I/flutter (12458): match your scenario, and file an issue with the details of the bug if there isn't. > I/flutter (12458): , recoverySuggestion: We currently don't have a recovery suggestion for this exception., underlyingException: PlatformException(error, Tried to get a plugin before it was configured. Make sure you call Amplify.configure() first., null, java.lang.IllegalStateException: Tried to get a plugin before it was configured. Make sure you call Amplify.configure() first.

Categories

Steps to Reproduce

  1. First i configure Amplify in main method
  2. Then i go to Home page and i fetch Rooms table Data
  3. Then it shows me the error

Screenshots

No response

Platforms

Android Device/Emulator API Level

API 31

Environment

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.3.6, on macOS 11.7.1 20G918 darwin-x64, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 13.0)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.2)
[✓] VS Code (version 1.73.1)
[✓] Connected device (4 available)
[✓] HTTP Host Availability

• No issues found!

Device

google pixel 3(emulator), iphone 13 pro mac(simulator), google pixel 4xl (real device)

OS

iOS 15.1, android 12,13

Deployment Method

Amplify CLI + Custom Pipeline

CLI Version

10.5.1

Additional Context

No response

Dependencies ```bash Dart SDK 2.18.2 Flutter SDK 3.3.6 socialnetwork 1.0.0+1 dependencies: - amplify_api 0.6.9 [amplify_api_android amplify_api_ios amplify_core amplify_flutter aws_common collection flutter meta plugin_platform_interface] - amplify_auth_cognito 0.6.9 [amplify_auth_cognito_android amplify_auth_cognito_ios amplify_core aws_common collection flutter meta plugin_platform_interface] - amplify_datastore 0.6.9 [flutter amplify_datastore_plugin_interface amplify_core plugin_platform_interface meta collection async] - amplify_flutter 0.6.9 [amplify_core amplify_datastore_plugin_interface amplify_flutter_android amplify_flutter_ios aws_common collection flutter meta plugin_platform_interface] - amplify_storage_s3 0.6.9 [amplify_storage_s3_android amplify_storage_s3_ios amplify_core aws_common flutter meta plugin_platform_interface path_provider path] - async 2.9.0 [collection meta] - cached_network_image 3.2.2 [flutter flutter_cache_manager octo_image cached_network_image_platform_interface cached_network_image_web] - connectivity_plus 2.3.9 [flutter connectivity_plus_platform_interface connectivity_plus_linux connectivity_plus_macos connectivity_plus_web connectivity_plus_windows] - cupertino_icons 1.0.5 - device_info_plus 5.0.5 [flutter device_info_plus_platform_interface device_info_plus_macos device_info_plus_linux device_info_plus_web device_info_plus_windows] - flashy_tab_bar2 0.0.4 [flutter] - flutter 0.0.0 [characters collection material_color_utilities meta vector_math sky_engine] - flutter_dotenv 5.0.2 [flutter] - flutter_switch 0.3.2 [flutter] - font_awesome_flutter 10.2.1 [flutter] - http 0.13.5 [async http_parser meta path] - image_picker 0.8.6 [flutter image_picker_android image_picker_for_web image_picker_ios image_picker_platform_interface] - intl_phone_field 3.1.0 [flutter] - provider 6.0.4 [collection flutter nested] - shared_preferences 2.0.15 [flutter shared_preferences_android shared_preferences_ios shared_preferences_linux shared_preferences_macos shared_preferences_platform_interface shared_preferences_web shared_preferences_windows] - url_launcher 6.1.6 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows] - uuid 3.0.6 [crypto] - videosdk 1.0.7 [flutter random_string flutter_webrtc events2 collection sdp_transform h264_profile_level_id flutter_foreground_task synchronized http encrypt] transitive dependencies: - amplify_api_android 0.6.9 [flutter] - amplify_api_ios 0.6.9 [amplify_core flutter] - amplify_auth_cognito_android 0.6.9 [flutter] - amplify_auth_cognito_ios 0.6.9 [amplify_core flutter] - amplify_core 0.6.9 [aws_common collection flutter intl json_annotation meta plugin_platform_interface uuid] - amplify_datastore_plugin_interface 0.6.9 [amplify_core collection flutter meta] - amplify_flutter_android 0.6.9 [flutter] - amplify_flutter_ios 0.6.9 [amplify_core flutter] - amplify_storage_s3_android 0.6.9 [flutter] - amplify_storage_s3_ios 0.6.9 [flutter] - args 2.3.1 - asn1lib 1.2.2 - aws_common 0.1.1 [async collection http meta stream_transform uuid] - cached_network_image_platform_interface 2.0.0 [flutter flutter_cache_manager] - cached_network_image_web 1.0.2 [flutter flutter_cache_manager cached_network_image_platform_interface] - characters 1.2.1 - clock 1.1.1 - collection 1.16.0 - connectivity_plus_linux 1.3.1 [flutter connectivity_plus_platform_interface meta nm] - connectivity_plus_macos 1.2.6 [connectivity_plus_platform_interface flutter] - connectivity_plus_platform_interface 1.2.3 [flutter meta plugin_platform_interface] - connectivity_plus_web 1.2.5 [connectivity_plus_platform_interface flutter_web_plugins flutter js] - connectivity_plus_windows 1.2.2 [connectivity_plus_platform_interface flutter] - convert 3.1.1 [typed_data] - cross_file 0.3.3+2 [js meta] - crypto 3.0.2 [typed_data] - dart_webrtc 1.0.9 [webrtc_interface] - dbus 0.7.8 [args ffi meta xml] - device_info_plus_linux 4.0.2 [device_info_plus_platform_interface file flutter meta] - device_info_plus_macos 4.0.2 [device_info_plus_platform_interface flutter] - device_info_plus_platform_interface 4.0.1 [flutter meta plugin_platform_interface] - device_info_plus_web 4.0.2 [device_info_plus_platform_interface flutter_web_plugins flutter] - device_info_plus_windows 5.0.2 [device_info_plus_platform_interface ffi flutter win32 meta] - encrypt 5.0.1 [args asn1lib clock collection crypto pointycastle] - events2 1.0.0 - ffi 2.0.1 - file 6.1.4 [meta path] - flutter_blurhash 0.7.0 [flutter] - flutter_cache_manager 3.3.0 [clock collection file flutter http path path_provider pedantic rxdart sqflite uuid] - flutter_foreground_task 3.10.0 [flutter plugin_platform_interface platform shared_preferences shared_preferences_android shared_preferences_ios] - flutter_plugin_android_lifecycle 2.0.7 [flutter] - flutter_web_plugins 0.0.0 [flutter js characters collection material_color_utilities meta vector_math] - flutter_webrtc 0.9.11 [dart_webrtc flutter path_provider webrtc_interface] - h264_profile_level_id 0.2.0 [flutter] - http_parser 4.0.2 [collection source_span string_scanner typed_data] - image_picker_android 0.8.5+3 [flutter flutter_plugin_android_lifecycle image_picker_platform_interface] - image_picker_for_web 2.1.10 [flutter flutter_web_plugins image_picker_platform_interface] - image_picker_ios 0.8.6+1 [flutter image_picker_platform_interface] - image_picker_platform_interface 2.6.2 [cross_file flutter http plugin_platform_interface] - intl 0.17.0 [clock path] - js 0.6.4 - json_annotation 4.7.0 [meta] - material_color_utilities 0.1.5 - meta 1.8.0 - nested 1.0.0 [flutter] - nm 0.5.0 [dbus] - octo_image 1.0.2 [flutter flutter_blurhash] - path 1.8.2 - path_provider 2.0.11 [flutter path_provider_android path_provider_ios path_provider_linux path_provider_macos path_provider_platform_interface path_provider_windows] - path_provider_android 2.0.20 [flutter path_provider_platform_interface] - path_provider_ios 2.0.11 [flutter path_provider_platform_interface] - path_provider_linux 2.1.7 [ffi flutter path path_provider_platform_interface xdg_directories] - path_provider_macos 2.0.6 [flutter path_provider_platform_interface] - path_provider_platform_interface 2.0.5 [flutter platform plugin_platform_interface] - path_provider_windows 2.1.3 [ffi flutter path path_provider_platform_interface win32] - pedantic 1.11.1 - petitparser 5.1.0 [meta] - platform 3.1.0 - plugin_platform_interface 2.1.3 [meta] - pointycastle 3.6.2 [collection convert js] - process 4.2.4 [file path platform] - random_string 2.3.1 - rxdart 0.27.5 - sdp_transform 0.3.2 - shared_preferences_android 2.0.14 [flutter shared_preferences_platform_interface] - shared_preferences_ios 2.1.1 [flutter shared_preferences_platform_interface] - shared_preferences_linux 2.1.1 [file flutter path path_provider_linux path_provider_platform_interface shared_preferences_platform_interface] - shared_preferences_macos 2.0.4 [flutter shared_preferences_platform_interface] - shared_preferences_platform_interface 2.1.0 [flutter plugin_platform_interface] - shared_preferences_web 2.0.4 [flutter flutter_web_plugins shared_preferences_platform_interface] - shared_preferences_windows 2.1.1 [file flutter path path_provider_platform_interface path_provider_windows shared_preferences_platform_interface] - sky_engine 0.0.99 - source_span 1.9.0 [collection path term_glyph] - sqflite 2.2.0+2 [flutter sqflite_common path] - sqflite_common 2.4.0+2 [synchronized path meta] - stream_transform 2.0.1 - string_scanner 1.1.1 [source_span] - synchronized 3.0.0+3 - term_glyph 1.2.1 - typed_data 1.3.1 [collection] - url_launcher_android 6.0.20 [flutter url_launcher_platform_interface] - url_launcher_ios 6.0.17 [flutter url_launcher_platform_interface] - url_launcher_linux 3.0.1 [flutter url_launcher_platform_interface] - url_launcher_macos 3.0.1 [flutter url_launcher_platform_interface] - url_launcher_platform_interface 2.1.1 [flutter plugin_platform_interface] - url_launcher_web 2.0.13 [flutter flutter_web_plugins url_launcher_platform_interface] - url_launcher_windows 3.0.1 [flutter url_launcher_platform_interface] - vector_math 2.1.2 - webrtc_interface 1.0.8 - win32 3.0.1 [ffi] - xdg_directories 0.2.0+2 [meta path process] - xml 6.1.0 [collection meta petitparser] ```
Amplify Config ``` const amplifyconfig = ''' { "UserAgent": "aws-amplify-cli/2.0", "Version": "1.0", "api": { "plugins": { "awsAPIPlugin": { "socialnetwork": { "endpointType": "GraphQL", "endpoint": "https://zinxjcu3ubaixddwrh2cycz6ei.appsync-api.us-east-1.amazonaws.com/graphql", "region": "us-east-1", "authorizationType": "API_KEY", "apiKey": "XXXXXXXXXX" } } } }, "auth": { "plugins": { "awsCognitoAuthPlugin": { "UserAgent": "aws-amplify-cli/0.1.0", "Version": "0.1.0", "IdentityManager": { "Default": {} }, "AppSync": { "Default": { "ApiUrl": "https://zinxjcu3ubaixddwrh2cycz6ei.appsync-api.us-east-1.amazonaws.com/graphql", "Region": "us-east-1", "AuthMode": "API_KEY", "ApiKey": "XXXXXXXXXX", "ClientDatabasePrefix": "socialnetwork_API_KEY" }, "socialnetwork_AWS_IAM": { "ApiUrl": "https://zinxjcu3ubaixddwrh2cycz6ei.appsync-api.us-east-1.amazonaws.com/graphql", "Region": "us-east-1", "AuthMode": "AWS_IAM", "ClientDatabasePrefix": "socialnetwork_AWS_IAM" } }, "CredentialsProvider": { "CognitoIdentity": { "Default": { "PoolId": "XXXXXXXXXX", "Region": "us-east-1" } } }, "CognitoUserPool": { "Default": { "PoolId": "us-east-1_KSg1Yq6Mk", "AppClientId": "XXXXXXXXXX", "Region": "us-east-1" } }, "Auth": { "Default": { "OAuth": { "WebDomain": "socialnetwork-socialenv.auth.us-east-1.amazoncognito.com", "AppClientId": "XXXXXXXXXX", "SignInRedirectURI": "https://google.com/", "SignOutRedirectURI": "https://youtube.com/", "Scopes": [ "phone", "email", "openid", "profile", "aws.cognito.signin.user.admin" ] }, "authenticationFlowType": "USER_SRP_AUTH", "socialProviders": [], "usernameAttributes": [ "EMAIL" ], "signupAttributes": [ "EMAIL" ], "passwordProtectionSettings": { "passwordPolicyMinLength": 8, "passwordPolicyCharacters": [] }, "mfaConfiguration": "OFF", "mfaTypes": [ "SMS" ], "verificationMechanisms": [ "EMAIL" ] } }, "S3TransferUtility": { "Default": { "Bucket": "socialnetworkbucket204550-socialenv", "Region": "us-east-1" } } } } }, "storage": { "plugins": { "awsS3StoragePlugin": { "bucket": "socialnetworkbucket204550-socialenv", "region": "us-east-1", "defaultAccessLevel": "guest" } } } }'''; ```
Lorenzohidalgo commented 1 year ago

Hi @YawarOsman , could you share more code?

The error states that the plugin was not correctly configured, you should be looking out for the following things before querying data:

YawarOsman commented 1 year ago

Hi @YawarOsman , could you share more code?

The error states that the plugin was not correctly configured, you should be looking out for the following things before querying data:

  • All Amplify plugins are correctly configured (you should wait until it's configured before continuing)
  • Data store is ready (listen to Data store events and wait until the "ready" event is sent before querying)

I updated the code , just look at it

dnys1 commented 1 year ago

Hi @YawarOsman - what @Lorenzohidalgo is recommending is correct. In your code, you are tracking the variable setAmplifyConfigured when configuration completes, but you are not using this variable to delay progression to a new screen. An easy way to get around this is to configure Amplify in your main function like so:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await configureAmplify();

  // ... other initialization code

  runApp( ... );
}

@Lorenzohidalgo also mentioned waiting for the DataStore ready event before querying. This can be done using the DataStore Hub events as documented here.

Can you please make these changes and let us know if the issue persists?

HuiSF commented 1 year ago

Hi @YawarOsman we had a conversation on Discord, where we determined a cause that your App is not working correctly with Amplify, you also mentioned that the exception described in this issue was fixed. I'm going to optimistically close this issue now, please feel free to reopen and follow up if you need further assistance. Thanks!