首页 > 其他 > 详细

[flutter-12] StatefulWidget-Counter2

时间:2021-06-02 15:33:20      阅读:19      评论:0      收藏:0      [点我收藏+]

1. StatefulWidget-Counter2

  • Center -> Column -> Row + Text
  • _incrase() 增加计数;
  • _decrease() 减少计数;
  • setState( () {} );
import ‘package:flutter/material.dart‘;

void main(List<String> args) {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(‘首页‘),
        ),
        body: HomeContent(),
      ),
    );
  }
}

class HomeContent extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => HomeContentState();
}

class HomeContentState extends State<HomeContent> {
  var _counter = 0;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              RaisedButton(
                color: Colors.redAccent,
                child: Text(
                  ‘+1‘,
                  style: TextStyle(
                    fontSize: 20,
                    color: Colors.white,
                  ),
                ),
                onPressed: () {
                  print(‘+1‘);
                  _increase();
                },
              ),
              RaisedButton(
                color: Colors.orangeAccent,
                child: Text(
                  ‘-1‘,
                  style: TextStyle(
                    fontSize: 20,
                    color: Colors.white,
                  ),
                ),
                onPressed: () {
                  print(‘-1‘);
                  _decrease();
                },
              ),
            ],
          ),
          Text(
            ‘当前计数: $_counter‘,
            style: TextStyle(
              fontSize: 20,
              color: Colors.black,
              fontWeight: FontWeight.bold,
            ),
          )
        ],
      ),
    );
  }

  // 增加计数
  void _increase() {
    setState(() {
      _counter++;
    });
  }

  // 减少计数
  void _decrease() {
    setState(() {
      _counter--;
    });
  }
}

技术分享图片

[flutter-12] StatefulWidget-Counter2

原文:https://www.cnblogs.com/comefromchina/p/flutter-statefulwidget-counter2.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!