Flutter笔记:Widgets Easier组件库使用加减器
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
void _decrementCounter() {
setState(() {
_counter--;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'_counter',
style: TextStyle(fontSize: 20),
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(Icons.remove),
onPressed: _decrementCounter,
),
SizedBox(width: 20),
IconButton(
icon: Icon(Icons.add),
onPressed: _incrementCounter,
),
],
),
],
),
),
);
}
}
这段代码使用了Flutter的IconButton
组件来创建加减按钮,并通过点击事件来更新计数器的值。这是学习Flutter的一个基本例子,展示了如何使用简单的状态管理来更新UI。
评论已关闭