2Flutter的有状态组件
flutter 主要有分 有状态 组件 StatefulWidget 和 无状态组件 StatelessWidget
当我我们有需要对页面的内容进行动态修改的时候 ,如果我们使用无状态组件,页面上的内容就不会被跟新
主要代码
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home:Scaffold(
appBar: AppBar(
title: Text('Flutter Demo')
),
body: HomePage(),
)
);
}
}
一:错误眼神
class HomePage extends StatelessWidget {
int countNum=1;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
SizedBox(height: 20),
Text("${this.countNum}"),
SizedBox(height: 20),
RaisedButton(
child: Text("按钮"),
onPressed: (){
this.countNum++;
print(this.countNum);
},
)
],
);
}
}
正确的我们应该使用有状态组件
//有状态组件
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int cont = 0;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
SizedBox(height: 20),
Chip(
label: Text('${this.cont}'),
),
SizedBox(height: 20),
RaisedButton(
child: Text('按钮'),
onPressed: () {
setState(() {
this.cont++;
});
},
)
],
);
}
}
效果展示