Home > Software design >  Flutter ways to switch between material apps or reload main function
Flutter ways to switch between material apps or reload main function

Time:03-28

I would like to have a clear separation of concerns between user enroll flow and the rest of the app. To do that I have created a MaterialApp for Enroll flow and a MaterialApp for the main application. When the user is done signing up - they should be directed to the main app. So something like this:

void main() async {

    // ... init and stuff ... //

    if(isUserAccountExists){
    
        runApp(MultiProvider(
            providers: [
                Provider(create: (context) => DataStorage()),
                ChangeNotifierProvider.value(value: settingsController),
                ChangeNotifierProvider.value(value: oauthProvider),
                ChangeNotifierProvider.value(value: deviceProvider),
                ChangeNotifierProvider.value(value: messenger),
            ],
            child: MainApp(settingsController: settingsController),
        ),);
    
    } else runApp(EnrollApp());
}

My problem is when the user is done signing up, I have no ways to restart the application or reload the main() function. (I must restart due to initialization steps that precede the runApp call).

CodePudding user response:

You can use flutter_phoenix to restart your application.

flutter_phoenix configuration:

dependencies:
    flutter_phoenix: "^1.0.0"

import 'package:flutter_phoenix/flutter_phoenix.dart';

void main() {
  runApp(
    Phoenix(
      child: App(),
    ),
  );
}

Phoenix.rebirth(context);

You may follow these steps:

  1. After your sign up, call Phoenix.rebirth(context); method to restart the application
  2. In your splash screen or main widget check the database so that the user is already signed up or not then redirect the user to your ux/view.

CodePudding user response:

You can extract your signup logic in separate Class(Widget) to handle which screen to render based on signup status. Something like here:

class _SeparationClassState extends State<SeparationClass> {
  bool isUserAccountExists = false;

  @override
  Widget build(BuildContext context) {
    // update isUserAccountExists to trigger rebuild
    return Scaffold(
      body: isUserAccountExists
          ? MultiProvider(
              providers: [
                Provider(create: (context) => DataStorage()),
                ChangeNotifierProvider.value(value: settingsController),
                ChangeNotifierProvider.value(value: oauthProvider),
                ChangeNotifierProvider.value(value: deviceProvider),
                ChangeNotifierProvider.value(value: messenger),
              ],
              child: MainApp(settingsController: settingsController),
            )
          : EnrollApp(),
    );
  }
}

It doesn't needs to be a StatefulWidget, you can use Provider or Bloc pattern to handle signup logic and update your state (and ui) accordingly.

  • Related