颤振延迟函数调用两次

时间:2019-06-18 15:51:22

标签: flutter flutter-navigation

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

 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屏幕出现了两次。

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

1 个答案:

答案 0 :(得分:3)

build方法可以被多次调用,因此它不是调用初始化过程的正确位置。您应该将小部件转换为StatefulWidget(在Android Studio上为Alt + Enter),然后从Future.delayed调用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));
  }
}