
本文共 3108 字,大约阅读时间需要 10 分钟。
StatefulWidget常用教程组件总结
StatefulWidget是Flutter框架中非常重要的一个控件类型,它允许Flutter应用程序的UI在状态变化时重新建teşim。作为一名刚开始学习Flutter的开发者,我想通过总结这些常用的StatefulWidget组件,帮助自己巩固知识 points。
1. 页面切换 - BottomNavigationBar
BottomNavigationBar 是用于实现多页面切换的常用控件。在Android开发中类似于TabLayout,在iOS中类似于TabPageBarController。它支持通过点击按钮切换页面,适用于有多个视角可视的场景,比如首页标签切换。下面是一个简单的使用实例:
int currentIndex = 0; // 初始化为0bottomNavigationBar: BottomNavigationBar( currentIndex: currentIndex, onTap: (index) { setState(() { currentIndex = index; }); }, items: [ BottomNavigationBarItem( icon: Icon(Icons.home, color: Colors.grey), activeIcon: Icon(Icons.home, color: Colors.blue), title: Text('首页'), ), BottomNavigationBarItem( icon: Icon(Icons.list, color: Colors.grey), activeIcon: Icon(Icons.list, color: Colors.blue), title: Text('列表'), ), ], body: currentIndex == 0 ? Center( child: ListView( children: [ Text('首页相关内容'), ], ), ) : Text('列表内容'),), body: _currentIndex == 0 ? /* 内容 */ : AnotherPage(),
作用: 主要用于实现多页面切换,当用户点击底部按钮时,当前页面会切换到相应的页面。
2. 刷新指示器 - RefreshIndicator
RefreshIndicator 类似于Android中的PullRefreshLayout,用于在用户向下拽动时显示刷新状态,用以提示数据正在加载或重新刷新。以下是一个带有图片的刷新示例:
body: RefreshIndicator( child: ListView( children: [ Container( decoration: BoxDecoration(color: Colors.white), alignment: Alignment.center, child: Column( children: [ Image.network( '图片链接', width: 100, height: 200, ), ], ), ), ], onRefresh: _handleRefresh, ), future: null, // 实际上可以使用 async/await 返回 Future(null)),
Future_handleRefresh() async { await Future.delayed(Duration(milliseconds: 200)); return null;}
作用: 在用户拽动时显示刷新动画,通常用于数据异步加载或刷新操作。
3. 悬浮按钮 - FloatingActionButton
浮动按钮是一种常用的交互按钮,通常用于轻abetesic actions,比如支付、分享、添加等功能。以下是一个简要实例:
FloatingActionButton( onPressed: null, child: Icon( Icons.add, size: 20, ),),
作用: 用于在应用程序中添加一个悬浮的圆形按钮,对应特定操作。
4. 文本输入框 - TextField
TextField 是用于获取用户文本输入的重要控件,常见于表单、搜索框等场合。例如:
TextField( decoration: InputDecoration( contentPadding: EdgeInsets.fromLTRB(5, 0, 0, 0), hintText: '请输入', hintStyle: TextStyle( fontSize: 15, ), ),),
作用: 提供文本输入功能,适用于收集用户输入的场景。
5. 页面切换 - PageView
PageView 是一个用于实现垂直页面滑动切换的控件,常用于展示多个页面或内容片段。下面是一个简单的示例:
Container( height: 100, margin: EdgeInsets.only(top: 10), decoration: BoxDecoration( color: Colors.lightBlueAccent, ), child: PageView( children: [ _item('Page1', Colors.deepPurple), _item('Page2', Colors.green), _item('Page3', Colors.red), ], ),),
_item(String title, Color color) { return Container( alignment: Alignment.center, decoration: BoxDecoration(color: color), child: Text( title, style: TextStyle( fontSize: 22, color: Colors.white, ), ), );}
作用: 实现页面的滑动切换,用来展示多个视图内容片段。
这些组件是Flutter开发中的基础能手,它们在常规项目中 Usuallyesehen 组合使用,为开发者事半功倍。如果你正在学习Flutter,这些控件将成为你熟练掌握的基础。
发表评论
最新留言
关于作者
