在其他Dart文件中颤振更改布尔值(使用setState)

时间:2019-08-18 15:12:16

标签: flutter dart

我正在尝试使用堆栈创建启动画面。一切加载完成后,我想将bool splashScreenIsLoading更改为false。

这是我在main.dart中的代码

bool splashScreenIsLoading = true;

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Stack(
        children: <Widget>[
          loginScreen(),
          showRightSplash(),
        ],
      ),
    );
  }
}

class showRightSplash extends StatefulWidget {
  @override
  _showRightSplashState createState() => _showRightSplashState();
}

class _showRightSplashState extends State<showRightSplash> {
  @override
  Widget build(BuildContext context) {
    return splashScreenIsLoading == true ? splashScreen() : splashScreen2();
  }
}

splashScreen() {
  return Text(
    "SHOW SPLASH SCREEN",
    style: TextStyle(fontSize: 50, color: Colors.red),
  );
}

splashScreen2() {
  return Text(
    "HIDE SPLASH SCREEN",
    style: TextStyle(fontSize: 50, color: Colors.red),
  );
}

在我的文件(另一个.dart文件)loginScreen()中,我在initState中有这个

void initState() {
    super.initState();
    pageController = PageController(initialPage: 0);
    doTasks()
    setState(() {
      splashScreenIsLoading = false;
    });
  }

这是行不通的,只有当所有内容加载完毕后我才重新热装。有解决方案吗?

1 个答案:

答案 0 :(得分:0)

由于您的doTasks()是异步函数,因此请像这样编辑initState:

void initState() {
    super.initState();
    pageController = PageController(initialPage: 0);
    doTasks().then((_){
      setState(() {
        splashScreenIsLoading = false;
      });
    });
  }

您还可以像这样简化代码:

splashScreenIsLoading ? splashScreen() : splashScreen2()