Flutter 编写 Splash 页面

25 min read
import 'package:flutter/material.dart';
import 'dart:async';
 
class Splash extends StatefulWidget {
  @override
  _SplashState createState() => _SplashState();
}
 
class _SplashState extends State<Splash>{
 
  @override
  Widget build(BuildContext context) {
    return new Material(
      child: new Scaffold(
        body: new Stack(
          children: <Widget>[
            new Container(
              child: new Image.asset(
                "images/launch.png",
                fit: BoxFit.fill,
              ),
            ),
            new Container(
              alignment: Alignment.topRight,
              padding: const EdgeInsets.fromLTRB(0.0, 45.0, 10.0, 0.0),
              child: OutlineButton(
                child: new Text(
                  "跳过",
                  textAlign: TextAlign.center,
                  style: new TextStyle(color: Colors.white),
                ),
                // StadiumBorder椭圆的形状
                shape: new StadiumBorder(),
                onPressed: () {
                  newHomePage();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
 
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    countDown();
  }
 
  // 倒计时
  void countDown() {
    var _duration = new Duration(seconds: 3);
    new Future.delayed(_duration, newHomePage);
  }
  void newHomePage() {
    Navigator.pushReplacementNamed(context, '/HomePage');
  }
}

Future.delayed Flutter 的 setTimeout

Creates a future that runs its computation (计算) after a delay.

The computation will be executed after the given duration has passed, and the future is completed with the result of the computation (计算) .

If computation returns a future, the future returned by this constructor will complete with the value or error of that future.

If the duration is 0 or less, it completes no sooner than in the next event-loop iteration (迭代) , after all microtasks have run.

If computation is omitted (省略) , it will be treated as if computation was () => null, and the future will eventually complete with the null value. In that case, T must be nullable.

If calling computation throws, the created future will complete with the error.

See also Completer for a way to create and complete a future at a later time that isn't necessarily after a known fixed duration.

Future.delayed(const Duration(seconds: 1), () {
  print('One second has passed.'); // Prints after 1 second.
});