一、Widget架构
StatelessWidget
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context){
return Container();
}
}
StatefulWidget
class MyHomePage extends StatefulWidget{
@overrider
_MyHomePageState createState()=>_MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{
@override
Widget build(BuildContext context){
return Container();
}
}
二、bottomNavigationBar
基础应用 1.最简单
class MyHomePage extends StatefulWidget {
const MyHomePage({ Key key }) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("监听练习"),
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon:Icon( Icons.shop_2_sharp),
title: Text("购物车")
),
BottomNavigationBarItem(
icon: Icon(Icons.favorite),
title: Text("收藏"),
),
],
),
body: Container(),
);
}
2.加入点击事件和部分属性 举例1
import 'package:flutter/material.dart';
import 'package:item_1/page/CartPage/CartPage.dart';
import 'package:item_1/page/CartPage/HomePage.dart';
import 'package:item_1/page/CategoryPage/CategoryPage.dart';
import 'package:item_1/page/MinePage/MinePage.dart';
main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectIndex = 0;
List<Widget> _list;
@override
void initState() {
super.initState();
_list
..add(HomePage())
..add(CategoryPage())
..add(CartPage())
..add(MinePage());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("监听练习"),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectIndex,
selectedItemColor: Colors.orange,
unselectedItemColor: Colors.black,
onTap: (index) {
setState(() {
_selectIndex = index;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text("首页"),
),
BottomNavigationBarItem(
icon: Icon(Icons.category),
title: Text("分类"),
),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart),
title: Text("购物车"),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text("我的"),
),
],
),
body: IndexedStack(
index: _selectIndex,
children: _list,
),
);
}
}
举例2
import 'package:flutter/material.dart';
import '../page/Home.dart';
import '../page/Category.dart';
import '../page/Setting.dart';
class Tabs extends StatefulWidget {
const Tabs({Key key}) : super(key: key);
@override
_TabsState createState() => _TabsState();
}
class _TabsState extends State<Tabs> {
int _currentIndex = 0;
List _listpage = [
Homepage(),
Categorypage(),
Settingpage(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Demo"),
),
body: _listpage[this._currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: this._currentIndex,
onTap: ((int index) {
setState(() {
this._currentIndex = index;
});
}),
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text("首页")),
BottomNavigationBarItem(
icon: Icon(Icons.category), title: Text("分类")),
BottomNavigationBarItem(icon: Icon(Icons.settings), title: Text("设置"))
]),
drawer: Drawer(
child: Text("data"),
),
endDrawer: Drawer(
child: Text("右侧侧边栏"),
),
);
}
}
实战
import 'package:flutter/material.dart';
import 'package:myshop_flutter/config/index.dart';
import '../CartPage/CartPage.dart';
import '../CategoryPage/CategoryPage.dart';
import 'package:myshop_flutter/page/home/HomePage.dart';
import '../Mine/MinePage.dart';
class HomeIndexPage extends StatefulWidget {
const HomeIndexPage({Key key}) : super(key: key);
@override
_HomeIndexPageState createState() => _HomeIndexPageState();
}
class _HomeIndexPageState extends State<HomeIndexPage> {
int _selectedIndex = 0;
List<Widget> _list = List();
@override
void initState() {
super.initState();
_list
..add(HomePage())
..add(CategoryPage())
..add(CartPage())
..add(MinePage());
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _selectedIndex,
children: _list,
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedItemColor: KColor.indexTabSelectedColor,
unselectedItemColor: KColor.indexTabUnSelectedColor,
currentIndex: _selectedIndex,
onTap: _onItemTapped,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text(KString.HOME),
),
BottomNavigationBarItem(
icon: Icon(Icons.category),
title: Text(KString.CATEGORY),
),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart),
title: Text(KString.SHOP_CAR),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text(KString.MINE),
),
],
),
);
}
_onItemTapped(int index) {
setState(() {
this._selectedIndex = index;
});
}
}
三、Appbar
自定义appbar 需要重写PreferredSizeWidget 否则就会报错can’t be assigned to the parameter type ‘PreferredSizeWidget’
import 'package:flutter/material.dart';
class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
final String title;
double height;
MyAppBar(this.title,{this.height =60});
@override
Widget build(BuildContext context){
return AppBar(
centerTitle: true,
elevation: 0,
title: Text(this.title),
);
}
@override
Size get preferredSize => getSize();
Size getSize() {
return Size.fromHeight(height);
}
}
四、Stack
Stack
1.Stack组件可以将子组件叠加显示,根据子组件的顺利依次向上叠加 2.fit和alignment参数控制的都是未定位的子组件,使用Positioned包裹的子组件就是定位的子组件 3.Positioned组件可以指定距Stack各边的距离
IndexedStack
IndexedStack是Stack的子类,Stack是将所有的子组件叠加显示,而IndexedStack只显示指定的子组件 自定义导航和返回按钮
Container(
height: 56.0,
width: double.infinity,
child: Stack(
children: [
Align(
alignment: Alignment.center,
child: Text(
"礼品商城",
style: white16Style,
),
),
Align(
alignment: Alignment.centerLeft,
child: GestureDetector(
onTap: () {
Navigator.of(context).pop();
},
child: Container(
height: 56.0,
padding: EdgeInsets.symmetric(horizontal: 15, vertical: 5),
color: Colors.transparent,
child: Icon(
Icons.arrow_back_ios,
color: Colors.white,
size: 20,
),
),
),
),
Align(
alignment: Alignment.centerRight,
child: GestureDetector(
onTap: () {
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 15, vertical: 5),
color: Colors.transparent,
child: Text(
'我的订单',
style: white12Style,
),
),
),
)
],
),
)
五、showModalBottomSheet
原码 举例
openBottomSheet(context) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (BuildContext context) {
return SafeArea(
child: SizedBox(
width: double.infinity,
height: 430,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: EdgeInsets.all(20),
child: Row(
children: [
Image.network(
"https://tse1-mm.cn.bing.net/th/id/R-C.65398d6ad86129f9628c0ad80da4040c?rik=C3qNS9mZOQk%2b5A&riu=http%3a%2f%2fwww.shijuepi.com%2fuploads%2fallimg%2f200918%2f1-20091Q10420.jpg&ehk=QBNuJIbVP1qo%2bwUD3YzXcvL4H5iHivOHXUnzzRw%2bWfU%3d&risl=&pid=ImgRaw&r=0",
height: 90,
width: 90,
fit: BoxFit.cover,
),
SizedBox(
width: 20,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"174¥",
style: TextStyle(
color: Colors.black54, fontSize: 16),
),
Padding(
padding: EdgeInsets.only(top: 10),
),
],
)
],
),
),
Padding(
padding: EdgeInsets.only(left: 20,bottom: 20
),
child: Text("规格"),
),
Padding(
padding: EdgeInsets.only(left: 20),
child: Wrap(
runSpacing: 10,
spacing: 20,
children: _buildspeclist(),
),
)
],
),
),
);
});
}
完整代码
import 'package:flutter/material.dart';
import 'package:item_1/widget/MyappBar.dart';
class CartPage extends StatefulWidget {
const CartPage({Key key}) : super(key: key);
@override
_CartPageState createState() => _CartPageState();
}
class _CartPageState extends State<CartPage> {
bool _isAllCheck = false;
String spec;
List list = ["标准", "大码"];
int specIndex;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar("购物车"),
bottomNavigationBar: BottomAppBar(
child: Container(
height: 60,
decoration: BoxDecoration(color: Colors.white),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Checkbox(
value: _isAllCheck,
activeColor: Colors.lightBlue,
onChanged: (value) {
setState(() {
_isAllCheck = value;
});
},
),
Text("全选"),
Expanded(
child: Container(
alignment: Alignment.centerRight,
margin: EdgeInsets.only(right: 20),
child: Text("17¥"),
)),
InkWell(
onTap: () {
openBottomSheet(context);
},
child: Container(
width: 100,
alignment: Alignment.center,
child: Text("加入购物车"),
decoration: BoxDecoration(color: Colors.green),
),
),
InkWell(
onTap: () {},
child: Container(
width: 100,
alignment: Alignment.center,
child: Text("直接购买"),
decoration: BoxDecoration(color: Colors.red),
),
),
],
),
),
),
body: Stack(
alignment: Alignment.bottomCenter,
children: [
ListView(
children: [
],
)
],
),
);
}
openBottomSheet(context) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (BuildContext context) {
return SafeArea(
child: SizedBox(
width: double.infinity,
height: 430,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: EdgeInsets.all(20),
child: Row(
children: [
Image.network(
"https://tse1-mm.cn.bing.net/th/id/R-C.65398d6ad86129f9628c0ad80da4040c?rik=C3qNS9mZOQk%2b5A&riu=http%3a%2f%2fwww.shijuepi.com%2fuploads%2fallimg%2f200918%2f1-20091Q10420.jpg&ehk=QBNuJIbVP1qo%2bwUD3YzXcvL4H5iHivOHXUnzzRw%2bWfU%3d&risl=&pid=ImgRaw&r=0",
height: 90,
width: 90,
fit: BoxFit.cover,
),
SizedBox(
width: 20,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"174¥",
style: TextStyle(
color: Colors.black54, fontSize: 16),
),
Padding(
padding: EdgeInsets.only(top: 10),
),
],
)
],
),
),
Padding(
padding: EdgeInsets.only(left: 20,bottom: 20
),
child: Text("规格"),
),
Padding(
padding: EdgeInsets.only(left: 20),
child: Wrap(
runSpacing: 10,
spacing: 20,
children: _buildspeclist(),
),
)
],
),
),
);
});
}
List<Widget> _buildspeclist() {
List<Widget> spectlistWidget = [];
for (int i = 0; i < list.length; i++) {
spectlistWidget.add(GestureDetector(
onTap: () {
setState(() {
specIndex = i;
});
},
child: Container(
alignment: Alignment.center,
width: 60,
height: 35,
child: Text(
list[i],
style: TextStyle(color: specIndex==i?Colors.white:Colors.black),
),
decoration: BoxDecoration(color:specIndex==i? Colors.cyan:Colors.grey[200],borderRadius: BorderRadius.circular(6)),
),
));
}
return spectlistWidget;
}
}
实战
六、ListTile使用
ListTile是遵循Material Design 规范且固定高度的组件,让开发者快速的构建精美的布局,通常用于ListView的子控件,当然也可以单独使用。 添加标题和子标题
import 'package:flutter/material.dart';
import 'package:item_1/widget/MyappBar.dart';
class MinePage extends StatefulWidget {
const MinePage({Key key}) : super(key: key);
@override
_MinePageState createState() => _MinePageState();
}
class _MinePageState extends State<MinePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar("我的页面"),
body: Container(
child: ListView(
children: [
ListTile(
leading: Container(
width: 45,
height: 45,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: NetworkImage(
"https://img-blog.csdnimg.cn/e30f9c6d115e4c809368ec99c0abc16f.png"))),
),
title: Text("我的信息"),
trailing: Icon(Icons.sort),
subtitle: Text("红尘初妆,山河无疆。最初的面庞,碾碎梦魇无常,命格无双",
softWrap: false, overflow: TextOverflow.ellipsis),
),
ListTile(
onTap: () {
print('onTap');
},
onLongPress: () {
print('onLongPress');
},
subtitle: Text("月账"),
leading: CircleAvatar(
child: Icon(Icons.money),
),
title: Text("我的小资"),
),
],
),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:item_1/widget/MyappBar.dart';
class MinePage extends StatefulWidget {
const MinePage({Key key}) : super(key: key);
@override
_MinePageState createState() => _MinePageState();
}
class _MinePageState extends State<MinePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar("我的页面"),
body: Container(
child: Column(
children: [
Container(
width: double.infinity,
height: 80,
child: Padding(
padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
child: Row(
children: [
Container(
width: 45,
height: 45,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
image: DecorationImage(
image: NetworkImage(
"https://img-blog.csdnimg.cn/e30f9c6d115e4c809368ec99c0abc16f.png",
),
fit: BoxFit.cover,
)),
),
Expanded(
child: ListTile(
title: Text("可可"),
subtitle: Text("1761621891"),
),
),
IconButton(
icon: Icon(Icons.outlet),
)
],
),
)
)
],
),
),
);
}
}
class Tabs extends StatefulWidget {
const Tabs({Key key}) : super(key: key);
@override
_TabsState createState() => _TabsState();
}
class _TabsState extends State<Tabs> {
int _currentIndex = 0;
List _listpage = [
Homepage(),
Categorypage(),
Settingpage(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Demo"),
),
body: _listpage[this._currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: this._currentIndex,
onTap: ((int index) {
setState(() {
this._currentIndex = index;
});
}),
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text("首页")),
BottomNavigationBarItem(
icon: Icon(Icons.category), title: Text("分类")),
BottomNavigationBarItem(icon: Icon(Icons.settings), title: Text("设置"))
]),
drawer: Drawer(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: UserAccountsDrawerHeader(
accountName: Text("用户名"),
accountEmail: Text("用户邮箱"),
currentAccountPicture: CircleAvatar(
backgroundImage: NetworkImage("https://img-blog.csdnimg.cn/e30f9c6d115e4c809368ec99c0abc16f.png"),
),
decoration: BoxDecoration(
color: Colors.yellow,
image: DecorationImage(
image: NetworkImage("https://img-blog.csdnimg.cn/7169ebc246784dd092e3b5040649b5e4.png"),
fit: BoxFit.cover
)
),
),
)
],
),
ListTile(
leading: CircleAvatar(
child: Icon(Icons.home),
),
title: Text("我的空间"),
onTap: (){
Navigator.pushNamed(context, '/Userinfopage');
},
),
Divider(),
ListTile(
leading: CircleAvatar(
child: Icon(Icons.people),
),
title: Text("用户中心"),
)
],
),
),
endDrawer: Drawer(
child: Text("右侧侧边栏"),
),
);
}
}
七、Form表单
Form、FormField、TextFormField是表单相关控件,类似于H5中form。Form组件是一个容器类控件,可以包含多个FormField表单控件,这样的好处是统一管理。在使用Form的时候需要设置其key,通过key获取当前的FormState,然后可以调用FormState的save 、validate 、reset 等方法,一般通过如下方法设置:
import 'package:flutter/material.dart';
import 'package:item_1/widget/MyappBar.dart';
class CategoryPage extends StatefulWidget {
const CategoryPage({Key key}) : super(key: key);
@override
_CategoryPageState createState() => _CategoryPageState();
}
class _CategoryPageState extends State<CategoryPage> {
var _account = '';
var _pwd = '';
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar("登录页面"),
body: Container(
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(hintText: '输入账号'),
validator: (String value) {
return value.length >= 6 ? null : '账号最少6个字符';
},
onSaved: (value) {
_account = value;
},
),
TextFormField(
decoration: InputDecoration(hintText: '输入密码'),
obscureText: true,
validator: (String value) {
return value.length >= 6 ? null : '账号最少6个字符';
},
onSaved: (value) {
_pwd = value;
},
),
RaisedButton(
child: Text('登录'),
onPressed: () {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
}
},
)
],
),
),
),
);
}
}
实战
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:myshop_flutter/components/gradient_button.dart';
import 'package:myshop_flutter/config/index.dart';
import 'package:myshop_flutter/event/login_event.dart';
import 'package:myshop_flutter/model/user_model.dart';
import 'package:myshop_flutter/service/user_service.dart';
import 'package:myshop_flutter/utils/navigator_util.dart';
import 'package:myshop_flutter/utils/shared_preferences_util.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LoginPage extends StatefulWidget {
const LoginPage({Key key}) : super(key: key);
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
TextEditingController _accountTextControl = TextEditingController();
TextEditingController _passwordTextControl = TextEditingController();
UserService userService = UserService();
UserModel userModel;
bool _autovalidator = false;
final registerFormKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: SafeArea(
child: Container(
alignment: Alignment.topCenter,
child: SingleChildScrollView(
child: Container(
padding: EdgeInsets.only(top: 50, left: 24, right: 24),
child: Form(
key: registerFormKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Image.asset("images/logn.png",
width: double.infinity, height: 140),
SizedBox(height: 22),
Center(
child: Text("易购",
style: TextStyle(
color: Color(0xFF323232), fontSize: 30))),
Container(
height: 50,
margin: EdgeInsets.only(top: 43),
child: TextFormField(
autocorrect: _autovalidator,
validator: _validatorAccount,
keyboardType: TextInputType.phone,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(11)
],
controller: _accountTextControl,
keyboardAppearance: Brightness.light,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xFFF0F0F0),
contentPadding: EdgeInsets.symmetric(
horizontal: 14.0, vertical: 0),
hintText: "请输入账号",
hintStyle:
TextStyle(color: Color(0xFFA7A5A5), fontSize: 14),
),
),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(6)),
color: Color(0xFFF0F0F0)),
),
Container(
height: 50,
margin: EdgeInsets.only(top: 23),
child: TextFormField(
obscureText: true,
autocorrect: _autovalidator,
validator: _validatorPassWord,
keyboardType: TextInputType.visiblePassword,
controller: _passwordTextControl,
keyboardAppearance: Brightness.light,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xFFF0F0F0),
contentPadding: EdgeInsets.symmetric(
horizontal: 14.0, vertical: 0),
hintText: "请输入密码",
hintStyle:
TextStyle(color: Color(0xFFA7A5A5), fontSize: 14),
),
),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(6)),
color: Color(0xFFF0F0F0)),
),
SizedBox(height: 32),
GradientButton("登录", 0xFFFF9E00, 0xFFFF4800, () {
_login();
}, textSize: 18, textColor: 0xFFFEFEFE),
SizedBox(height: 12),
Container(
margin: EdgeInsets.all(20),
alignment: Alignment.centerRight,
child: InkWell(
onTap: () => _register(),
child: Text(
KString.NOW_REGISTER,
style: TextStyle(
color: KColor.registerTextColor, fontSize: 16),
),
),
)
],
)),
),
)),
),
);
}
_register(){
NavigatorUtil.goRegister(context);
}
String _validatorAccount(String value) {
if (value == null || value.length < 11) {
return KString.ACCOUNT_RULE;
}
return null;
}
String _validatorPassWord(String value) {
if (value == null || value.length < 6) {
return KString.PASSWORD_HINT;
}
return null;
}
_login() {
if (registerFormKey.currentState.validate()) {
registerFormKey.currentState.save();
Map<String, dynamic> map = Map();
map.putIfAbsent("username", () => _accountTextControl.text.toString());
map.putIfAbsent("password", () => _passwordTextControl.text.toString());
userService.login(map, (success) {
print(success);
userModel = success;
_saveUserInfo();
_showToast(KString.LOGIN_SUCESS);
loginEventBus.fire(LoginEvent(true,url: userModel.userInfo.avatarUrl,nickName: userModel.userInfo.nickName));
Navigator.pop(context);
}, (onFail) {
print(onFail);
_showToast(onFail);
});
} else {
setState(() {
_autovalidator = true;
});
}
}
_saveUserInfo() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
SharedPreferencesUtil.token = userModel.token;
await sharedPreferences.setString(KString.TOKEN, userModel.token);
await sharedPreferences.setString(KString.HEAD_URL, userModel.userInfo.avatarUrl);
await sharedPreferences.setString(KString.NICK_NAME, userModel.userInfo.nickName);
await sharedPreferences.setBool("isLogin",true );
}
_showToast(message) {
Fluttertoast.showToast(
msg: message,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1,
backgroundColor: KColor.toastBgColor,
textColor: KColor.toastTextColor,
fontSize: 20);
}
}
八、按钮
import 'package:flutter/material.dart';
class Settingpage extends StatefulWidget {
const Settingpage({Key key}) : super(key: key);
@override
_SettingpageState createState() => _SettingpageState();
}
class _SettingpageState extends State<Settingpage> {
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
RaisedButton(
child: Text("跳转到登录页面"),
color: Colors.red,
textColor: Colors.white,
elevation: 20,
onPressed: () {
Navigator.pushNamed(context, '/Loginpage');
},
),
RaisedButton.icon(
icon: Icon(Icons.search),
label: Text("图标按钮"),
color: Colors.blue,
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)
),
onPressed: (){
},
)
],
),
);
}
}
import 'package:flutter/material.dart';
class Settingpage extends StatefulWidget {
const Settingpage({Key key}) : super(key: key);
@override
_SettingpageState createState() => _SettingpageState();
}
class _SettingpageState extends State<Settingpage> {
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
RaisedButton(
child: Text("跳转到登录页面"),
color: Colors.red,
textColor: Colors.white,
elevation: 20,
onPressed: () {
Navigator.pushNamed(context, '/Loginpage');
},
),
RaisedButton.icon(
icon: Icon(Icons.search),
label: Text("图标按钮"),
color: Colors.blue,
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
onPressed: () {},
),
Container(
height: 60,
child: RaisedButton(
child: Text("圆形按钮"),
color: Colors.blue,
textColor: Colors.white,
elevation: 20,
shape: CircleBorder(side: BorderSide(color: Colors.white)),
),
),
FlatButton(
child: Text("flat按钮"),
color: Colors.blue,
textColor: Colors.white,
),
OutlineButton(
child: Text("带边框按钮"),
onPressed: () {},
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Container(
height: 50,
child: OutlineButton(
child: Text("注册"),
onPressed: () {},
),
),
)
],
),
Row(
children: <Widget>[
ButtonBar(
children: <Widget>[
OutlineButton(
child: Text("buttonbar按钮"),
onPressed: () {},
)
],
)
],
)
],
),
);
}
}
九、文本框TextField
import 'package:flutter/material.dart';
import '../page/Tabs.dart';
class Homepage extends StatefulWidget {
const Homepage({Key key}) : super(key: key);
@override
_HomepageState createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
SizedBox(
height: 20,
),
TextField(
decoration: InputDecoration(
hintText: "请输入搜索内容", border: OutlineInputBorder()),
),
SizedBox(
height: 20,
),
TextField(
maxLines: 4,
decoration: InputDecoration(
hintText: "多行文本框", border: OutlineInputBorder()),
),
SizedBox(
height: 20,
),
TextField(
obscureText: true,
decoration: InputDecoration(
hintText: "password", border: OutlineInputBorder()),
),
SizedBox(
height: 20,
),
TextField(
decoration:
InputDecoration(labelText: "用户名", border: OutlineInputBorder()),
),
SizedBox(
height: 20,
),
TextField(
decoration: InputDecoration(
icon: Icon(Icons.people),
hintText: "请输入用户名",
),
)
],
),
);
}
}
十、单选复选
import 'package:flutter/material.dart';
import '../page/Tabs.dart';
class Homepage extends StatefulWidget {
const Homepage({Key key}) : super(key: key);
@override
_HomepageState createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
var _username = new TextEditingController();
var flag = false;
@override
void initState() {
super.initState();
_username.text = '初始值';
}
var name;
void _changenameFn(v) {
setState(() {
this.name = v;
});
}
void _changesexFn(v) {
setState(() {
this.sex = v;
});
}
int sex = 1;
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
SizedBox(
height: 20,
),
TextField(
decoration: InputDecoration(
hintText: "请输入搜索内容", border: OutlineInputBorder()),
controller: _username,
onChanged: (value) {
_username.text = value;
},
),
Container(
width: double.infinity,
height: 40,
child: RaisedButton(
color: Colors.blue,
textColor: Colors.white,
child: Text("登录"),
onPressed: () {},
),
),
Checkbox(
value: this.flag,
onChanged: (v) {
setState(() {
this.flag = v;
});
},
),
CheckboxListTile(
value: this.flag,
selected: this.flag,
onChanged: (v) {
setState(() {
this.flag = v;
});
},
title: Text("标题"),
subtitle: Text("这是二级标题"),
secondary: Icon(Icons.payment),
),
Row(
children: <Widget>[
Text("男"),
Radio(
value: 1,
onChanged: (v) {
setState(() {
this.sex = v;
});
},
groupValue: this.sex,
),
SizedBox(
width: 10,
),
Text("女"),
Radio(
value: 2,
onChanged: (v) {
setState(() {
this.sex = v;
});
},
groupValue: this.sex,
),
Switch(
value: this.flag,
onChanged: (v) {
this.flag = v;
},
),
TextField(
onChanged: this._changenameFn,
decoration: InputDecoration(
hintText: "用户名", border: OutlineInputBorder()),
),
Row(
children: <Widget>[
Text("男"),
Radio(
value: "男",
onChanged: this._changesexFn,
groupValue: this.sex,
),
Text("女"),
Radio(
value: "女",
onChanged: this._changesexFn,
groupValue: this.sex,
),
],
)
],
)
],
),
);
}
}
复选框及单元框
import 'package:flutter/material.dart';
import '../page/Tabs.dart';
class Homepage extends StatefulWidget {
const Homepage({Key key}) : super(key: key);
@override
_HomepageState createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
var _username = new TextEditingController();
var flag = false;
@override
void initState() {
super.initState();
_username.text = '初始值';
}
var name;
void _changenameFn(v) {
setState(() {
this.name = v;
print(this.name);
});
}
var sex = "男";
List hobby = [{"checked": true, "title": "睡觉"},{"checked": false, "title": "吃饭"},{"checked": true, "title": "打豆豆"},
];
List<Widget> _getHobby() {
List<Widget> tempList = [];
for (var i = 0; i < this.hobby.length; i++) {
tempList.add(Row(
children: <Widget>[
Text(this.hobby[i]["title"]+":"),
Checkbox(
value: this.hobby[i]["checked"],
onChanged: (v) {
setState(() {
this.hobby[i]["checked"] = v;
});
},
)
],
));
} return tempList;
}
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
TextField(
onChanged: this._changenameFn,
decoration:
InputDecoration(hintText: "用户名", border: OutlineInputBorder()),
),
Row(
children: <Widget>[
Text("男"),
Radio(
value: "男",
onChanged: (v) {
setState(() {
this.sex = v;
});
},
groupValue: this.sex,
),
Text("女"),
Radio(
value: "女",
onChanged: (v) {
setState(() {
this.sex = v;
});
},
groupValue: this.sex,
),
],
),
Column(
children: <Widget>[],
),
Column(
children: this._getHobby(),
)
],
),
);
}
}
十一、 city_pickers
dependencies:
city_pickers: ^1.0.1
import 'package:city_pickers/city_pickers.dart';
show(context) async {
Result temp = await CityPickers.showCityPicker(
context: context,
itemExtent: 50,
itemBuilder: (item, list, index) {
return Center(
child: Text(
item,
maxLines: 1,
style: TextStyle(fontSize: 16
)
),
);
},
height: 350,
);
print(temp);
setState(() {
_cityText = temp.provinceName + temp.cityName + temp.areaName;
_areaId = temp.areaId;
_provinceName = temp.provinceName;
_cityName = temp.cityName;
_countryName = temp.areaName;
});
}
|