fluttet中实现一个自定义的StatefulWidget组件,可以在数据变化后,把最新的页面效果展示给客户
实现效果
实现代码
pages文件夹下新加一个counter_page.dart文件
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
State<CounterPage> createState() => _CounterPageState();
}
_CounterPageState类的实现
class _CounterPageState extends State<CounterPage> {
int _counter = 0;
void _addCount() {
setState(() {
_counter++;
});
}
void _decCount() {
setState(() {
_counter--;
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('计数器'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('You have pushed the button this many times:'),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: _decCount,
// 减号图标Icons
style: const ButtonStyle(
backgroundColor: WidgetStatePropertyAll<Color>(Colors.red),
),
child: Text('-',style: TextStyle(color: Colors.white),),
),
Text('$_counter'),
ElevatedButton(
onPressed: _addCount,
child: Icon(Icons.add),
)
],
)
],
),
)
);
}
}
_counter
是内部的状态变量,_decCount
和_addCount
是对应按钮的点击事件
使用setState
来实现数据的变化,这里有点类似于react的class组件的实现
在main.dart中使用这个组件
import 'package:flutter/material.dart';
import 'package:flutter_app_01/pages/counter_page.dart';
// import 'package:flutter_app_01/pages/msg_page.dart';
void main() => runApp(const MyWidget());
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
Widget build(BuildContext context) {
return MaterialApp(
// debugShowCheckedModeBanner:false,
title:"个人中心",
// home: MyHomePage(),
// home:MessagePage()
home: CounterPage()
);
}
}
这样我们就实现了一个自定义组件