Flutter

Flutter第一个项目:计时器

2018-12-25  本文已影响212人  狂奔的胖蜗牛

最终效果图:


01.gif

1.编写界面布局

1.新建一个dart文件,取名为:HomePage.dart

image.png

2.在main.dart文件中导入HomePage.dart

import 'package:simple_clock/HomePage.dart';

3.创建出MaterialApp

main.dart代码如下:

import 'package:flutter/material.dart';
import 'package:simple_clock/HomePage.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Clock',
      theme: new ThemeData(
        primaryColor: Colors.blue
      ),
      home: HomePage(title: '计时器',),
    );
  }
}

其中,theme为APP指定主题颜色,home为主界面。

4.编写界面

在HomePage.dart中,先导入flutter框架。

import 'package:flutter/material.dart';

创建HomePage类

class HomePage extends StatefulWidget {
  HomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  State<StatefulWidget> createState() {
    return new _HomePage();
  }
}

创建出HomePage的State类

class _HomePage extends State<HomePage> {
  int time = 0;
  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height-kToolbarHeight-MediaQuery.of(context).padding.top;
    double width = MediaQuery.of(context).size.width;
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Container(
              child: new Text('$time',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 80,
                ),),
              color: Colors.yellow,
              height: height/2,
              alignment: Alignment.center,
              ),
            new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  child: new FlatButton(
                      color: Colors.blue,
                      textColor: Colors.white,
                      onPressed: (){
                      },
                      child: Text('结束')),
                  height: height/2,
                  width: width/2,
                ),
                Container(
                  child: new FlatButton(
                      color: Colors.green,
                      textColor: Colors.white,
                      onPressed: (){
                      },
                      child: Text('开始')),
                  height: height/2,
                  width: width/2,
                ),
                ],)
          ],
        ),),
    );
  }

5.为按钮添加控制逻辑

首先,编写两个按钮创建时的匿名函数onPressed的控制逻辑:
开始按钮调用startTimer方法。

startTime();

结束按钮调用stopTime方法。

stopTime();

6.完成startTime和stopTime方法控制逻辑

  void startTime() {
    if (_timer != null) {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (build){
          return AlertDialog(
            title: Text('注意'),
            titlePadding: EdgeInsets.only(left: 24, top: 20),
            content: Text('已经开始在计时了!'),
            actions: <Widget>[
              FlatButton(
                  onPressed: ()=>Navigator.of(context).pop(true),
                  child: Text('我知道了!')),
            ],
            //RounderRectangleBorder BeveledRectangleBorder StadiumBorder
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5)),);
        },);
      return;
    }
    _timer = new Timer.periodic(const Duration(seconds: 1), (timer){
      setState(() {
        time++;
      });
    });
  }

  void stopTime() {
    if (_timer != null) {
      _timer.cancel();
    }
    setState(() {
      time = 0;
    });
    _timer = null;
  }

2.最终HomePage代码:

import 'package:flutter/material.dart';
import 'dart:async';

class HomePage extends StatefulWidget {
  HomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  State<StatefulWidget> createState() {
    return new _HomePage();
  }
}

class _HomePage extends State<HomePage> {

  int time = 0;
  Timer _timer;

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height-kToolbarHeight-MediaQuery.of(context).padding.top;
    double width = MediaQuery.of(context).size.width;
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Container(
              child: new Text('$time',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 80,
                ),),
              color: Colors.yellow,
              height: height/2,
              alignment: Alignment.center,
              ),
            new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  child: new FlatButton(
                      color: Colors.blue,
                      textColor: Colors.white,
                      onPressed: (){
                        stopTime();
                      },
                      child: Text('结束')),
                  height: height/2,
                  width: width/2,
                ),
                Container(
                  child: new FlatButton(
                      color: Colors.green,
                      textColor: Colors.white,
                      onPressed: (){
                        startTime();
                      },
                      child: Text('开始')),
                  height: height/2,
                  width: width/2,
                ),
                ],)
          ],
        ),),
    );
  }

  void startTime() {
    if (_timer != null) {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (build){
          return AlertDialog(
            title: Text('注意'),
            titlePadding: EdgeInsets.only(left: 24, top: 20),
            content: Text('已经开始在计时了!'),
            actions: <Widget>[
              FlatButton(
                  onPressed: ()=>Navigator.of(context).pop(true),
                  child: Text('我知道了!')),
            ],
            //RounderRectangleBorder BeveledRectangleBorder StadiumBorder
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5)),);
        },);
      return;
    }
    _timer = new Timer.periodic(const Duration(seconds: 1), (timer){
      setState(() {
        time++;
      });
    });
  }

  void stopTime() {
    if (_timer != null) {
      _timer.cancel();
    }
    setState(() {
      time = 0;
    });
    _timer = null;
  }

}

3.欢迎关注

本文的代码已上传github:https://github.com/flywo/FlutterPractice,有需要的朋友可以去查看,后续还会在github上面更新更多的小代码,欢迎关注。

上一篇下一篇

猜你喜欢

热点阅读