首页 > 解决方案 > 一个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(),
    );
  }
}

标签: flutter

解决方案


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

为了避免冲突,您应该只有 1 个 MaterialApp。在您的情况下,您可以在openBox()不使用方法的情况下调用该方法,方法FutureBuilder是在方法中调用它main()

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());
        )
    );

小提示:在 Dart 中创建新类或方法时,最佳实践是使用 CamelCase。所以form_entry()应该命名FormEntry()为类名或formEntry()方法名。也一样home_screen()。您可以在此处参考样式指南


推荐阅读