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