一个 Flutter 中可以有两个 Material 应用程序吗?

Asu*_*ubu 6 flutter

我向我的应用程序添加了两个材质应用程序,因为我的 futurebuilder 需要上下文,而我创建的其他类无法访问我的提供程序。这是一种可以接受的做法吗???

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(),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Bac*_*ach 6

MaterialApp小部件的目的是提供基于 Material 设计的通用主题设置,并为其所有子小部件配置根导航器。

为了避免冲突,您应该只有 1 个 MaterialApp。在您的情况下,您可以通过在方法内调用它来调用该openBox()方法而不使用:FutureBuildermain()

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());
        )
    );
Run Code Online (Sandbox Code Playgroud)

小提示:在 Dart 中创建新类或方法时,最佳实践是使用 CamelCase。因此form_entry()应该FormEntry()以类名或formEntry()方法名命名。同样适用于home_screen(). 您可以参考这里的造型指南