0

I am trying to wait till amplify configuration is done then load the login screen. Even though state seems to be getting updated I am still getting the loadinscreen. Why is that?

I am not sure if setState is proper method on the init : Importance of Calling SetState inside initState

As per the doc : https://docs.amplify.aws/start/getting-started/integrate/q/integration/flutter/#configure-amplify

Future<void> main() async {
  runApp(MyApp());
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _isAmplifyConfigured = false;
  late AmplifyAuthCognito auth;

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

  Future<void> _initializeApp() async {
    await _configureAmplify();
    setState(() {
      _isAmplifyConfigured = true;
    });
  }

  Future<void> _configureAmplify() async {
    auth = AmplifyAuthCognito();
    try {
      await Amplify.addPlugin(auth);
      await Amplify.configure(amplifyconfig);
    } on AmplifyAlreadyConfiguredException {
      print(
          'Amplify was already configured. Looks like app restarted on android.');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      onGenerateRoute: AppRoutes.onGenerateRoute,
      initialRoute: _isAmplifyConfigured
          ? LoginScreen.routeName
          : LoadingScreen.routeName,
    );
  }
}

1 Answers1

0

I think the issue is with you trying to reassign your initialRoute. I'm not super familiar with this property, but given the name I assume this is set once and is not rebuilt, not even when the state changes. It would make sense, also, because the rest of your code sounds like it should work.

Before trying anything else, I'd recommend you move your logic to initialize Amplify to the LoginScreen, and having its body depend on the _isAmplifyConfigured boolean value. So show spinner if it's false, and show Login fields when it's true.

Even better would be to create a HomeScreen, so you can keep this Amplify initialization at the bottom of your app's stack. And then have your HomeScreen either show the Login widgets, the home screen of your app, or a loading state.

Tim Jacobs
  • 1,023
  • 1
  • 8
  • 14
  • Thanks. Ah I see. That's strange. So I think , I really need to change the implementation method. –  Sep 23 '21 at 13:29
  • Your answer helped me to find an alternative solution, and it works. I used `home` and it works fine. I will just wait till to if some one can share more info on have it work above way. –  Sep 23 '21 at 13:54