Home > OS >  setState is not updating the UI even though state is updating
setState is not updating the UI even though state is updating

Time:09-24

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,
    );
  }
}

CodePudding user response:

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.

CodePudding user response:

try to call funcation after super.initState();. like this

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