Flutter之常用组件的使用举例+实战(上)

一、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,
        //点击时默认返回当前选定的item索引值
        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
  // TODO: implement preferredSize
  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(
              // widget.arguments['title'],
              "礼品商城",
              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: () {
              // Navigator.pushNamed(context, '/page/shop/order');
            },
            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),
                            ),
                            //选择规格productList.specifications
                          ],
                        )
                      ],
                    ),
                  ),
                  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),
                            ),
                            //选择规格productList.specifications
                          ],
                        )
                      ],
                    ),
                  ),
                  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.of(context).pop();隐藏侧边栏
                  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的savevalidatereset等方法,一般通过如下方法设置:

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,
                        // focusNode: phoneFocusNode,
                        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,
                        // focusNode: phoneFocusNode,
                        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) {
    //值不能为空并且长度要大于等于11
    if (value == null || value.length < 11) {
      return KString.ACCOUNT_RULE;
    }
    return null;
  }
  //验证密码
  String _validatorPassWord(String value) {
    //值不能为空并且长度要大于等于6
    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();
    //将用户的token值存在本地
    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,
            // onPressed: null,//禁用按钮
            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,
            // onPressed: null,//禁用按钮
            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, //groupValue一样时表示是一个按钮组
              ),
              SizedBox(
                width: 10,
              ),
              Text("女"),
              Radio(
                value: 2, //必须配置
                onChanged: (v) {
                  //必须配置
                  setState(() {
                    this.sex = v;
                  });
                },
                groupValue: this.sex, //groupValue一样时表示是一个按钮组//必须配置
              ),
              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 {
    //使用CityPickers组件弹出城市选择框
    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;
    });
  }

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可可鸭~

想吃糖~我会甜

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值