/**
* Flutter StatefulWidget有状态组件、页面上绑定数据、改变页面数据
* 在Flutter中自定义组件其实就是一个类,这个类需要继承StatelessWidget/StatefulWidget
* StatelessWidget是无状态组件,状态不可变得widget
* StatefulWidget是有状态组件,持有的状态可能在widget生命周期改变。如果我们想
* 改变页面中的数据化的这个时候就需要用到StatefulWidget
*/
import 'package:flutter/material.dart'; void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('自定义组件'),
),
body: HomeContent(),
),
);
}
} class HomeContent extends StatelessWidget {
@override
Widget build(BuildContext context) {
//Stack结合align实现布局:
return HomePage();
}
} //自定义有状态组件:
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key); _HomePageState createState() => _HomePageState();
} class _HomePageState extends State<HomePage> {
int countNum=;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
SizedBox(height: ),
Chip(label: Text('${this.countNum}')),
SizedBox(height: ),
RaisedButton(
child: Text('按钮'),
onPressed: (){
setState(() { //只有有状态的组件里面才有
this.countNum++;
});
},
)
],
);
}
}
demo2
main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('自定义组件'),
),
body: HomeContent(),
),
);
}
} class HomeContent extends StatelessWidget {
@override
Widget build(BuildContext context) {
//Stack结合align实现布局:
return HomePage();
}
} //自定义有状态组件:
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key); _HomePageState createState() => _HomePageState();
} class _HomePageState extends State<HomePage> {
List list=new List();
@override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
Column(
children:this.list.map((value){
return ListTile(
title: Text(value),
);
}).toList()
),
RaisedButton(
child: Text('按钮'),
onPressed: (){
setState(() {
this.list.add('新增数据1');
this.list.add('新增数据2');
});
},
)
],
);
}
}