19.8.8 flutter 学习之创建第一个可变的Widget
创建一个很简单的可变的Widget
效果就是点击字的时候会变化
完整代码:
class CarPage extends StatefulWidget { @override _CarState createState() { return _CarState(); } } class _CarState extends State<CarPage> { String showTitle = '今天天机很热!'; // 点击时触发方法 void clickBtn() { setState(() { showTitle = '那是相当的热啊'; }); } @override Widget build(BuildContext context) { // TODO: implement build return Container( margin: EdgeInsets.fromLTRB(100, 200, 0, 0), child: GestureDetector( child: Text(showTitle), onTap: clickBtn, ), ); } }
下面的例子是你点击哪一行汉字的时候颜色会变深
class CarPage extends StatefulWidget { @override _CarState createState() { return _CarState(); } } class _CarState extends State<CarPage> { final List showTitleList = [ '原来如此', '投影', '不漏声色', '蜜蜂', '扎心', '画', '梦醒的夏天', 'Forever 21', '青柠', '昨日青空' ]; //记录选中的index int selecteIndex = -1; // 点击时触发方法 void clickBtn() { print('22222' + selecteIndex.toString()); setState(() {}); } @override Widget build(BuildContext context) { // TODO: implement build return ListView.builder( itemCount: showTitleList.length, itemBuilder: (context, index) { return Center( child: Container( margin: EdgeInsets.only(top: 20), child: GestureDetector( child: Text( showTitleList[index], style: TextStyle(fontSize: 20, color: index == selecteIndex ? Colors.red[400] : Colors.red[100]), textAlign: TextAlign.center, ), onTap: () { selecteIndex = index; print(index); clickBtn(); }, ), ), ); }); } }