如何从FutureBuilder返回不同的MaterialApp小部件

时间:2019-08-03 13:32:01

标签: flutter dart

我需要从localstorge提取数据,并根据数据值isLogin为true或false来确定isLogin值为true,然后返回不同的MaterialApp,如果为false则返回不同的MaterialApp。

Widget build(BuildContext context) {
    return FutureBuilder(
      future: storage.ready,
      builder: (BuildContext context, snapshots) {
        if (snapshots.hasData) {
          var isLogin = storage.getItem('isLogin');
          if (snapshots.data == true) {
            return MaterialApp(
              initialRoute: '/sample',
              onGenerateRoute: RouteGenerator.generateRoute,
            );
          } else {
            return MaterialApp(
              initialRoute: '/',
              onGenerateRoute: RouteGenerator.generateRoute,
            );
          }
        }
      },
    );
  }

2 个答案:

答案 0 :(得分:1)

找到了一个对我有用的解决方案,也许它可以帮助将来的某个人。

在它向我抛出没有任何意义的错误之前: `用于空值的空检查运算符。相关的导致错误的小部件是 MaterialApp。

但是,我的解决方案是将应用程序转换为 StatefulWidget,将 future 添加到 initState 方法(就像您通常在屏幕上所做的那样),然后为每个应用程序添加键。

class DEUSApp extends StatefulWidget {
  const DEUSApp({Key key}) : super(key: key);

  @override
  _DEUSAppState createState() => _DEUSAppState();
}

class _DEUSAppState extends State<DEUSApp> {
  Future<bool> initializeData;
  final GlobalKey _appKey = GlobalKey();
  final GlobalKey _loadingKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    initializeData = context.read<SplashCubit>().initializeData();
  }

  @override
  Widget build(BuildContext ctx) {
    return BlocBuilder<SplashCubit, SplashState>(builder: (context, state) {
      // at the beginning, show a splash screen, when the data hasn't been loaded yet.
      return FutureBuilder(
        future: initializeData,
        builder: (context, snapshot) {
          if (!snapshot.hasData || !(state is SplashSuccess))
            return MaterialApp(key: _loadingKey, theme: MyStyles.theme, home: SplashScreen());

          return MaterialApp(
            key: _appKey,
            title: 'Deus Finance',
            debugShowCheckedModeBanner: false,
            theme: MyStyles.theme,
            routes: generateRoutes(context),
            initialRoute: kInitialRoute,
          );
        },
      );
    });
  }
}

答案 1 :(得分:0)

这就是我的工作方式,我不确定这是否是最佳解决方案,但它是否有效。

 main() async {
  String isToNavigate = await MainAppService().getPrefValue('isToRemember');
  String typeOfUser = await MainAppService().getPrefValue('typeOfUser');
  if (isToNavigate != null) {
    if (typeOfUser == 'admin') {
      WidgetsFlutterBinding.ensureInitialized();

      runApp(AdminMyApp());
    }
    if (typeOfUser == 'client') {
      WidgetsFlutterBinding.ensureInitialized();

      runApp(MyAppClient());
    }
    if (typeOfUser == 'professional') {
      WidgetsFlutterBinding.ensureInitialized();

      runApp(MyProfessionalsApp());
    }
  } else {
    print('null is found /');
    WidgetsFlutterBinding.ensureInitialized();

    runApp(MyApp());
  }
}