flutter计算器

环境

  • flutter 3.0.1
  • 开发android web windows版本

创建项目

  • 创建flutter_calculator项目

194

新建index.dart

import 'package:flutter/material.dart';

class IndexPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
     appBar: AppBar(
       title: Text("计算器"),
     ),
    );
  }
}

修改main.dart

删除MyHomePage和_MyHomePageState类,因为我们要使用index.dart作为主页。

import 'package:flutter/material.dart';
import 'package:flutter_calculator/index.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: IndexPage(),
    );
  }
}

运行

195

划分区域

标题居中

添加属性centerTitle: true

      appBar: AppBar(
        title: Text("计算器"),
        centerTitle: true,
      ),

使用Column划分

添加 body

      body: Container(
        child: Column(children: <Widget>[
          Text("显示区域"),
          Text("操作区域")
        ])
      ),

修改两个区域样式文字居中

修改body

      body: Container(
        child: Column(children: <Widget>[
          Center(child: Text("显示区域")),
          Container(color: Colors.orange,child: Center(child: Text("操作区域")))
        ])
      ),

196

使用expanded填充

Expanded组件用在Column组件下面,用来指定这个元素填充页面。

      body: Container(
        child: Column(children: <Widget>[
          Expanded(child:Center(child: Text("显示区域"))),
          Container(color: Colors.orange,child: Center(child: Text("操作区域")))
        ])
      ),

设置操作区域的高度,让两个区域大小相近

      body: Container(
        child: Column(children: <Widget>[
          Expanded(child:Center(child: Text("显示区域"))),
          Container(height:300,color: Colors.orange,child: Center(child: Text("操作区域")))
        ])

197

添加按钮

定义按钮背景颜色

static const int NUM_BIN_BG=0XFF323232;

用TextButton组件实现圆形按钮

FlatButton组件是透明背景的按钮组件,可以用FlatButton包裹Container来实现圆型按钮。使用下面代码替换掉操作区域container

import 'package:flutter/material.dart';

class IndexPage extends StatelessWidget {
  static const int NUM_BIN_BG=0XFF323232;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("计算器"),
        centerTitle: true,
      ),
      body: Container(
        child: Column(children: <Widget>[
          Expanded(child:Center(child: Text("显示区域"))),
          Container(
            child: Center(
              child: Row(
                children: [
                  TextButton(
                    onPressed: null,
                    child: Container(
                      decoration: BoxDecoration(
                        color: Color(NUM_BIN_BG),
                        shape: BoxShape.circle
                      ),
                      child: Text("1",style: TextStyle(fontSize: 28.0,color:Colors.white)),
                      padding: EdgeInsets.all(10),
                    ),
                  )
                ],
              ),
            ),
          )
        ])
      ),
    );
  }
}


198

封装TextButton为xzwButton

  Widget xzwButton({int flex =1}){
    return Expanded(
      flex: flex,
        child: TextButton(
          onPressed: null,
          child: Container(
            decoration: BoxDecoration(
                color: Color(NUM_BIN_BG),
                shape: flex>1?BoxShape.rectangle:BoxShape.circle
            ),
            child: Text("1",style: TextStyle(fontSize: 28.0,color:Colors.white)),
            padding: EdgeInsets.all(10),
          ),
        )
    );

  }

199

调整大小,修改形状

  Widget xzwButton({int flex =1}){
    return Expanded(
      flex: flex,
        child: TextButton(
          onPressed: null,
          child: Container(
            decoration: BoxDecoration(
                color: Color(NUM_BIN_BG),
                shape: flex>1?BoxShape.rectangle:BoxShape.circle,
                borderRadius: flex>1?BorderRadius.all(Radius.circular(1000.0)):null
            ),
            child: Center(
              child:Text("1",style: TextStyle(fontSize: 28.0,color:Colors.white)),
            ),
            padding: EdgeInsets.all(20),
          ),
        )
    );

  }

200

批量新增按钮

添加常量

  static const Nkeys=[
    'C','D','?','/',
    '9','8','7','*',
    '6','5','4','-',
    '3','2','1','+',
    " ",'0','.','='
  ];
  //按钮背景颜色
  static const  Color NUM_BTN_BG=Color(0xff323232);
  //页面背景颜色
  static const Color PAGE_COLOR=Colors.black;
  //顶部按钮颜色
  static const Color TOP_BTN_BG=Color(0xFFa6a6a6);

  //右侧按钮颜色
  static const Color Right_BTN_BG=Color(0xFFff9500);

  //顶部按钮
  static const Tkey=[
    'C','D','?'
  ];
  //右侧按钮
  static const Rkey=[
    '/','*','-',"+",'='
  ];

修改xzwFlatButton

  Widget xzwButton(String num, {int flex =1}){
    return Expanded(
      flex: flex,
        child: TextButton(
          onPressed: null,
          child: Container(
            decoration: BoxDecoration(
              //给各个按钮分配颜色
                color: Tkey.contains(num)?TOP_BTN_BG:Rkey.contains(num)?Right_BTN_BG:NUM_BTN_BG,
                shape: flex>1?BoxShape.rectangle:BoxShape.circle,
                borderRadius: flex>1?BorderRadius.all(Radius.circular(1000.0)):null
            ),
            child: Center(
              child:Text("$num",style: TextStyle(fontSize: 28.0,color:Colors.white)),
            ),
            padding: EdgeInsets.all(20),
          ),
        )
    );

  }

批量创建按钮

// 批量创建按钮
  Widget buildButtons(){
    List<Widget> rows = [];
    List<Widget> btns = [];
    int flex=1;
    for(int i=0;i<Nkeys.length;i++){
      String key = Nkeys[i];
      if(key==" "){
        flex++;
        continue;
      }else{
        Widget b = xzwButton(key,flex: flex);
        btns.add(b);
        flex =1;
      }
      //四个按钮为一行
      if ((i + 1) % 4 == 0) {
        rows.add(Row(
          children: btns,
        ));
        btns = [];
      }
    }
    //当不足三个时候,也就是最后一行
    if(btns.length>0)
    {
      rows.add(Row(
        children: btns,
      ));
    }


    return Column(
      children: rows,

    );

  }

201

编辑显示区域

修改整个容器的颜色

color: Colors.black,

编辑显示区域

          Expanded(child:SingleChildScrollView(
            child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20.0,vertical: 10.0),
              child: Align(
                alignment: Alignment.bottomRight,
                child: Text(
                    "显示区域顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶111111111111111111111111xzwxzxw",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 32.0,
                  ),
                ),
              ),
            ),
          )),

202

操作部分

点击事件

修改为有状态 StatefulWidget

import 'package:flutter/material.dart';



//class IndexPage extends StatelessWidget {
class IndexPage extends StatefulWidget  {
  static const Nkeys=[
    'C','D','?','/',
    '9','8','7','*',
    '6','5','4','-',
    '3','2','1','+',
    " ",'0','.','='
  ];
  //按钮背景颜色
  static const  Color NUM_BTN_BG=Color(0xff323232);
  //页面背景颜色
  static const Color PAGE_COLOR=Colors.black;
  //顶部按钮颜色
  static const Color TOP_BTN_BG=Color(0xFFa6a6a6);

  //右侧按钮颜色
  static const Color Right_BTN_BG=Color(0xFFff9500);

  //顶部按钮
  static const Tkey=[
    'C','D','?'
  ];
  //右侧按钮
  static const Rkey=[
    '/','*','-',"+",'='
  ];

  @override
  _IndexPageState createState() => _IndexPageState();
}


class _IndexPageState extends State<IndexPage>{
  String _num="";



  //点击
  void clickKey(String key){
    setState(() {
      _num += key;
    });

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("计算器"),
        centerTitle: true,
      ),
      body: Container(
          color: Colors.black,
          child: Column(children: <Widget>[
            Expanded(child:SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20.0,vertical: 10.0),
                child: Align(
                  alignment: Alignment.bottomRight,
                  child: Text(
                    "$_num",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 32.0,
                    ),
                  ),
                ),
              ),
            )),

            Container(
              child: Center(
                  child:buildButtons()
                /*Row(
                children: [
                  xzwButton("1"),xzwButton("2",flex: 2),
                ],
              ),*/
              ),
            )
          ])
      ),
    );
  }

  Widget xzwButton(String num, {int flex =1}){
    return Expanded(
        flex: flex,
        child: TextButton(
          onPressed: (){
            clickKey(num);
          },
          child: Container(
            decoration: BoxDecoration(
              //给各个按钮分配颜色
                color: IndexPage.Tkey.contains(num)?IndexPage.TOP_BTN_BG:IndexPage.Rkey.contains(num)?IndexPage.Right_BTN_BG:IndexPage.NUM_BTN_BG,
                shape: flex>1?BoxShape.rectangle:BoxShape.circle,
                borderRadius: flex>1?BorderRadius.all(Radius.circular(1000.0)):null
            ),
            child: Center(
              child:Text("$num",style: TextStyle(fontSize: 28.0,color:Colors.white)),
            ),
            padding: EdgeInsets.all(20),
          ),
        )
    );

  }

  // 批量创建按钮
  Widget buildButtons(){
    List<Widget> rows = [];
    List<Widget> btns = [];
    int flex=1;
    for(int i=0;i<IndexPage.Nkeys.length;i++){
      String key = IndexPage.Nkeys[i];
      if(key==" "){
        flex++;
        continue;
      }else{
        Widget b = xzwButton(key,flex: flex);
        btns.add(b);
        flex =1;
      }
      //四个按钮为一行
      if ((i + 1) % 4 == 0) {
        rows.add(Row(
          children: btns,
        ));
        btns = [];
      }
    }
    //当不足三个时候,也就是最后一行
    if(btns.length>0)
    {
      rows.add(Row(
        children: btns,
      ));
    }


    return Column(
      children: rows,

    );

  }

}
  • 修改StatelessWidget 为StatefulWidget
  • 新增_IndexPageState
  • 修改xzwButton的点击事件
  • 修改显示部分

203

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×