IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Flutter之常用组件的使用举例+实战(上) -> 正文阅读

[移动开发]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;
    });
  }

在这里插入图片描述

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-03-30 18:36:39  更:2022-03-30 18:41:01 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 19:31:00-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码