2

我有一个启动器屏幕,我可以在其中检查我是否有特定数据。根据结果​​,我显示不同的屏幕

 void main() => runApp(MyApp());


 class MyApp extends StatelessWidget {
   @override
    Widget build(BuildContext context) {
    return MaterialApp(
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
    home: LauncherScreen()
  );
 }
}


 class LauncherScreen extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
 print("build, build");
 Future.delayed(new Duration(milliseconds: 2000), () {
  LocalData localData = LocalData();
  localData.getCity().then((city) {
    if (city != null) {
      Const.city = city;
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => Home()),
      );
    } else {
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => SelectCities()),
      );
    }
  });
});
return Container(
    width: double.infinity,
    height: double.infinity,
     color: Color(GoEngColors.violet));
 }
}

LauncherScreen叫了两次,结果我看到我的HomeSelect city屏幕出现了两次。

这种行为的原因是什么以及如何解决?谢谢。

4

1 回答 1

6

build方法可以被多次调用,因此它不是调用初始化过程的正确位置。您应该将您的小部件转换为StatefulWidget(Android Studio 上的 Alt + Enter)并调用您的Future.delayedfrom initState()。像这样:

class LauncherScreen extends StatefulWidget {
  @override
  _LauncherScreenState createState() => _LauncherScreenState();
}

class _LauncherScreenState extends State<LauncherScreen> {

  @override
  void initState() {
    super.initState();
    print("build, build");
    Future.delayed(new Duration(milliseconds: 2000), () {
      LocalData localData = LocalData();
      localData.getCity().then((city) {
        if (city != null) {
          Const.city = city;
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => Home()),
          );
        } else {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => SelectCities()),
          );
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {    
    return Container(width: double.infinity, height: double.infinity, color: Color(GoEngColors.violet));
  }
}
于 2019-06-18T16:03:49.933 回答