is it okay to have two material apps in one flutter?

Viewed 2579

I added two material app to my app because my futurebuilder needed a context and my provider was not accessible to the other classes i created. is it an acceptable practice???

runApp(
        MaterialApp(
            title: 'register app',
            home: FutureBuilder(
              future: Hive.openBox('store'),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  if (snapshot.hasError)
                    return Text(snapshot.error.toString());
                  else
                    return MultiProvider(providers: [
                      ChangeNotifierProvider.value(
                        value: form_entry(),
                      )
                    ], child: MyApp());
                } else
                  return Scaffold(
                      body: Center(
                    child: Text('error error ooops error'),
                  ));
              },
            )),
      );[enter image description here][1]

// my app class has another material app

 class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: home_screen(),
    );
  }
}
2 Answers

The purpose of a MaterialApp widget is to provide a common theme setting based on Material design and configures the root navigator for all of its children widgets.

In order to avoid conflicting, you should only have 1 MaterialApp. In your case, you can call the openBox() method without using the FutureBuilder by calling it within the main() method:

void main() async {
  // Include this line to make sure WidgetsFlutterBinding is initialized, since
  // we're using main() asynchronously
  WidgetsFlutterBinding.ensureInitialized();

  // Open the Hive box here
  var box = await Hive.openBox('store');

  // Then run the app
  runApp(
        MaterialApp(
            title: 'register app',
            home: MultiProvider(providers: [
              ChangeNotifierProvider.value(
                value: form_entry(),
              )
            ], child: home_screen());
        )
    );

Small note: When creating new class or method in Dart, best practice is to use CamelCase. So form_entry() should be named FormEntry() for Class name or formEntry() for Method name. Same goes with home_screen(). You can refer to the styling guide here

It's bad to have two MaterialApp() widgets, at least one in other.

I did that by mistake, I thought I do not have one and added an extra one. Then the app randomly crashed on hot restart, sit one whole day to debug everything and haven't found what crashed my app, then I started to refactor code and found I have two MaterialAapp, one in StatelessWidget and one in home widget that was on different file. After removing it my app stopped randomly crashing.

Never use two, atleast not one in other.

Related