flutter3.0开发——02.Flutter一些相关组件的使

2022-12-24  本文已影响0人  码农界四爷__King

在flutter中所有的组件都应该在放在MaterialApp—>Scaffold中 这是固定写法

import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,//去掉模拟器左上角bug
    home: Scaffold(
      appBar: AppBar(//设置标题
        title: const Text('你好flutter'),
      ),
      body: const MyApp(),
    ),
  ));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Text(
        "你好 flutter11",
        textDirection: TextDirection.rtl,
      ),
    );
  }
}


运行之后如下图所示


image.png

1.Container和 Text容器组件

import 'package:flutter/material.dart';

void main(){
  runApp(
    MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text("你好Flutter")),
        body:Column(
          children:const [
             MyApp(),
             MyButton(),
             MyText()
          ]
        )
      ),
    )
  );
}


class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
          child:Container(
            margin: const EdgeInsets.fromLTRB(0, 60, 0, 0),
            alignment: Alignment.center,  //配置Container容器内元素的方位
            width: 200,
            height: 200,
            // transform:Matrix4.translationValues(0, -40, 0),// 位移
            // transform:Matrix4.rotationZ(0.2),// 旋转
            transform:Matrix4.skewY(.2),
            decoration:BoxDecoration(
              color: Colors.yellow,  //背景颜色
              border: Border.all(   //边框
                color: Colors.red,
                width: 2
              ),
              borderRadius:BorderRadius.circular(10),  //配置圆角 也可以实现圆形
              boxShadow: const[   //配置阴影效果
                BoxShadow(
                  color:Colors.blue,
                  blurRadius:20.0
                )
              ],
              // LinearGradient 背景线性渐变 RadialGradient径向渐变
              gradient:const LinearGradient(
                colors:[
                  Colors.red,Colors.yellow
                ]
              )

            ) ,
            child: const Text("你好Flutter",style: TextStyle(
              color: Colors.black,
              fontSize: 20
            ),),
          ) ,
     );
  }
}


class MyButton extends StatelessWidget {
  const MyButton({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      width: 200,
      height: 40,
      // margin: const EdgeInsets.all(10),   //四周margin
      margin: const EdgeInsets.fromLTRB(0, 40, 0, 0),
      // padding: const EdgeInsets.fromLTRB(40, 0, 0, 0),
      decoration: BoxDecoration(
        color: Colors.blue,
        borderRadius:BorderRadius.circular(20)
      ),
      child: const Text("按钮",style: TextStyle(
        color: Colors.white,
        fontSize: 20
      )),
    );
  }
}




class MyText extends StatelessWidget {
  const MyText({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 200,
      height: 200,
      margin: const EdgeInsets.fromLTRB(0, 40, 0, 0),
      decoration: const BoxDecoration(
        color: Colors.yellow
      ),
      child: const Text(
        "你好我是Flutter你好我是Flutter你好我是Flutter你好我是Flutter你好我是Flutter",
        textAlign: TextAlign.left,
        overflow: TextOverflow.ellipsis,   //溢出显示几个点
        maxLines: 1,
        style: TextStyle(
          fontSize: 20,
          fontWeight:FontWeight.w900,
          color: Colors.red,
          fontStyle:FontStyle.italic,
          letterSpacing:2,
          decoration:TextDecoration.underline,
          decorationColor: Colors.black,
          decorationStyle: TextDecorationStyle.dashed

        ),

      ),
    );
  }
}

2.圆形图片

第一种

   ClipOval(
        child: Image.network("",
            width: 150.0,
            height: 150.0,
            fit: BoxFit.cover),
      ),

第二种

 CircleAvatar(
        radius: 200,
        backgroundImage:
            NetworkImage(""),
      ),

3.ListView 用法 list是数组 itemCount的值是数组的长度 itemBuilder相当于 for循环赋值

    Widget build(BuildContext context) {
            return ListView.builder(
                itemCount: list.length,
                itemBuilder: (context, index) {
                    return ListTile(
                        title: Text("${list[index]}"),
                    );
                });
        }

4.GridView用法 list是数组 itemCount的值是数组的长度 itemBuilder相当于 for循环赋值

    Widget build(BuildContext context) {
            return GridView.builder(
                //注意
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisSpacing: 10.0, //水平子 Widget 之间间距
                        mainAxisSpacing: 10.0, //垂直子 Widget 之间间距
                        crossAxisCount: 2, //一行的 Widget 数量
                    ),
                    itemCount: listData.length,
                    itemBuilder: _getListData,
            );
        }

5.Stack和Positioned定位用法

 Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8)),
          color: Color.fromARGB(255, 255, 255, 255)),
      // child: const Amap(),
      child: Container(
        width: double.infinity,//宽度占满
        height: 240,
        color: Colors.red,
        child: Stack(//外面要包裹个Container  这样就是基于Container来定位
          children: const [
            Positioned(
              left: 0,
              top: 0,
              child: Text('ceshi'),
            ),
            Positioned(
              right: 0,
              bottom: 0,
              child: Text(
                'youxia',
                style: TextStyle(fontSize: 24),
              ),
            )
          ],
        ),
      ),
    );
  }

6.button按钮

image.png
 @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        Column(
          children: [
            ElevatedButton(
              style: ButtonStyle(
                  backgroundColor:
                      MaterialStateProperty.all(Colors.red), //修改按钮背景颜色
                  foregroundColor:
                      MaterialStateProperty.all(Colors.black), //修改按钮文字颜色
                  elevation: MaterialStateProperty.all(20), //添加阴影
                  shape: MaterialStateProperty.all(
                    RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)), //圆角
                  )),
              onPressed: () {
                print('------');
              },
              child: const Text('普通按钮'),
            ),
            ElevatedButton(
              style: ButtonStyle(
                  //添加阴影
                  shape: MaterialStateProperty.all(
                const CircleBorder(
                  side: BorderSide(color: Colors.yellow, width: 10),
                ), //圆角
              )),
              onPressed: () {
                print('------');
              },
              child: const Text('圆形按钮'),
            ),
            TextButton(
              onPressed: () {
                print("-----");
              },
              child: const Text('文本按钮'),
            ),
            OutlinedButton(
              onPressed: () {
                print('带边框的按钮');
              },
              child: const Text('带边框按钮'),
            ),
            IconButton(
              onPressed: () {
                print('----');
              },
              icon: const Icon(Icons.tab),
            ),
            ElevatedButton.icon(
              onPressed: () {
                print('---');
              },
              icon: const Icon(Icons.safety_check),
              label: const Text('带图标按钮'),
            ),
            TextButton.icon(
              onPressed: () {
                print('---');
              },
              icon: const Icon(Icons.safety_check),
              label: const Text('带图标按钮'),
            ),
            OutlinedButton.icon(
              onPressed: () {
                print('---');
              },
              icon: const Icon(Icons.safety_check),
              label: const Text('带图标按钮'),
            ),
            Container(
              width: 240,
              height: 60,
              child: ElevatedButton(
                  onPressed: () {
                    print('----');
                  },
                  child: const Text("自定义按钮大小")),
            ),
            Row(
              children: [
                Expanded(
                  flex: 1,
                  child: SizedBox(
                    child: ElevatedButton(
                      onPressed: () {
                        print('----');
                      },
                      child: const Text("占满宽度的按钮"),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ],
    );
  }

7.Warp组件

  Wrap(
          spacing: 10,
          runSpacing: 10,
          children: [
            Button("女装", onPressed: () {}),
            Button("笔记本", onPressed: () {}),
            Button("玩具", onPressed: () {}),
            Button("文学", onPressed: () {}),
            Button("女装", onPressed: () {}),
            Button("时尚", onPressed: () {}),
            Button("男装", onPressed: () {}),
            Button("xxxx", onPressed: () {}),
            Button("手机", onPressed: () {})
          ],
        ),

8.咸鱼中间突起按钮

image.png
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Flutter App")),
      body: _pages[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
          fixedColor: Colors.red, //选中的颜色
          // iconSize:35,           //底部菜单大小
          currentIndex: _currentIndex, //第几个菜单选中
          type: BottomNavigationBarType.fixed, //如果底部有4个或者4个以上的菜单的时候就需要配置这个参数
          onTap: (index) {
            //点击菜单触发的方法
            //注意
            setState(() {
              _currentIndex = index;
            });
          },
          items: const [
            BottomNavigationBarItem(icon: Icon(Icons.home), label: "首页"),
            BottomNavigationBarItem(icon: Icon(Icons.category), label: "分类"),
            BottomNavigationBarItem(icon: Icon(Icons.message), label: "消息"),
            BottomNavigationBarItem(icon: Icon(Icons.settings), label: "设置"),
            BottomNavigationBarItem(icon: Icon(Icons.people), label: "用户")
          ]),
      floatingActionButton: Container(
        height: 60,  //调整FloatingActionButton的大小
        width: 60,
        padding: const EdgeInsets.all(5),
        margin: const EdgeInsets.only(top: 5),  //调整FloatingActionButton的位置
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(30),
        ),
        child: FloatingActionButton(
            backgroundColor:_currentIndex==2?Colors.red:Colors.blue,
            child: const Icon(Icons.add), 
            onPressed: () {
              setState(() {
                _currentIndex=2;
              });
            }
        ),
      ),
      floatingActionButtonLocation:
          FloatingActionButtonLocation.centerDocked, //配置浮动按钮的位置
    );
  }

9.左右侧边栏

image.png
 @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('高德地图'),
        ),
        body: const MyHomePage(),
        drawer: Drawer(
          //左侧侧边栏
          child: Column(
            children: [
              Row(
                children: [
                  Expanded(
                      flex: 1,
                      child: DrawerHeader(
                        decoration: const BoxDecoration(
                            // color: Colors.yellow,
                            image: DecorationImage(
                                image: NetworkImage( ""),
                                fit: BoxFit.cover)),
                        child: Column(
                          children: const [
                            ListTile(
                              leading: CircleAvatar(
                                  backgroundImage: NetworkImage("")),
                              title: Text("张三",
                                  style: TextStyle(color: Colors.red)),
                            ),
                            ListTile(
                              title: Text("邮箱:xxxx@qq.com"),
                            )
                          ],
                        ),
                      ))
                ],
              ),
              const ListTile(
                leading: CircleAvatar(
                  child: Icon(Icons.people),
                ),
                title: Text("个人中心"),
              ),
              const Divider(),
              const ListTile(
                leading: CircleAvatar(
                  child: Icon(Icons.settings),
                ),
                title: Text("系统设置"),
              ),
              Divider(),
            ],
          ),
        ),
        endDrawer: const Drawer(
          //右侧侧边栏
          child: Text("右侧侧边栏"),
        ),
      ),
    );
  }

10.导航栏左右侧图标

image.png
 @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
          // This is the theme of your application.
          //p
          // Try running your application with "flutter run". You'll see the
          // application has a blue toolbar. Then, without quitting the app, try
          // changing the primarySwatch below to Colors.green and then invoke
          // "hot reload" (press "r" in the console where you ran "flutter run",
          // or simply save your changes to "hot reload" in a Flutter IDE).
          // Notice that the counter didn't reset back to zero; the application
          // is not restarted.
          primarySwatch: Colors.blue,
          appBarTheme: const AppBarTheme(centerTitle: true)),//标题居中
      home: Scaffold(
        appBar: AppBar(
          title: const Text('测试'),
          leading: IconButton(
            //左侧图标
            onPressed: () {
              print("2112");
            },
            icon: const Icon(Icons.access_alarm),
          ),
          backgroundColor: Color.fromARGB(255, 43, 0, 234),
          actions: [
            //右侧图标
            IconButton(
              onPressed: () {
                Navigator.of(context).pushReplacementNamed("/pagename");
                Navigator.of(context).pushAndRemoveUntil(
                    MaterialPageRoute(builder: (BuildContext context) {
                  return const Amap();
                }), (route) => false);
                Navigator.of(context).pop();
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (BuildContext context) {
                      return const Amap();
                    },
                  ),
                );
              },
              icon: const Icon(Icons.access_alarm_outlined),
            ),
            IconButton(
              onPressed: () {
                print("----");
              },
              icon: const Icon(Icons.account_balance_outlined),
            ),
          ],
        ),
        body: const MyHomePage(),
        // drawer: Drawer(
        //   //左侧侧边栏
        //   child: Column(
        //     children: [
        //       Row(
        //         children: [
        //           Expanded(
        //               flex: 1,
        //               child: DrawerHeader(
        //                 decoration: const BoxDecoration(
        //                     // color: Colors.yellow,
        //                     image: DecorationImage(
        //                         image: NetworkImage(
        //                             "https://www.itying.com/images/flutter/2.png"),
        //                         fit: BoxFit.cover)),
        //                 child: Column(
        //                   children: const [
        //                     ListTile(
        //                       leading: CircleAvatar(
        //                           backgroundImage: NetworkImage(
        //                               "https://www.itying.com/images/flutter/3.png")),
        //                       title: Text("张三",
        //                           style: TextStyle(color: Colors.red)),
        //                     ),
        //                     ListTile(
        //                       title: Text("邮箱:xxxx@qq.com"),
        //                     )
        //                   ],
        //                 ),
        //               ))
        //         ],
        //       ),
        //       const ListTile(
        //         leading: CircleAvatar(
        //           child: Icon(Icons.people),
        //         ),
        //         title: Text("个人中心"),
        //       ),
        //       const Divider(),
        //       const ListTile(
        //         leading: CircleAvatar(
        //           child: Icon(Icons.settings),
        //         ),
        //         title: Text("系统设置"),
        //       ),
        //       Divider(),
        //     ],
        //   ),
        // ),
        // endDrawer: const Drawer(
        //   //右侧侧边栏
        //   child: Text("右侧侧边栏"),
        // ),
      ),
    );
  }

11.跳转路由

第一种

Navigator.of(context).push(
  MaterialPageRoute(
    builder: (BuildContext context) {
    return const Amap();
     },
  ),
);

返回上级路由

Navigator.of(context).pop();

替换路由跳转

Navigator.of(context).pushReplacementNamed("/pagename");

返回根目录

Navigator.of(context).pushAndRemoveUntil(
  MaterialPageRoute(builder: (BuildContext context) {
  return const Amap();
}), (route) => false);

12.页面传值

微信图片_20221229101000.png

13.Dialog 弹窗 也可以使用插件 flutter Toast

https://pub.dev/packages/fluttertoast/install

image.png
 @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: ElevatedButton(
          onPressed: () {
            print("[[[[[[[[");
            showDialog(
                context: context,
                builder: (context) {
                  return AlertDialog(
                    title: Text("标题"),
                    content: Text("内容"),
                    actions: [
                      TextButton(
                        onPressed: () {
                          print("-------");
                          Navigator.of(context).pop();
                        },
                        child: const Text('确定'),
                      ),
                      TextButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                          print("-------");
                        },
                        child: const Text("取消"),
                      ),
                    ],
                  );
                });
          },
          child: const Text('测试按钮'),
        ),
      ),
    );
  }
image.png
@override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: ElevatedButton(
          onPressed: () {
            print("[[[[[[[[");
            showDialog(
                barrierDismissible: false, //点击灰色背景是否让弹窗消失
                context: context,
                builder: (context) {
                  return SimpleDialog(
                    title: Text('请选择语言'),
                    children: [
                      SimpleDialogOption(
                        onPressed: () {
                          print("汉语");
                          Navigator.of(context).pop();
                        },
                        child: const Text('汉语'),
                      ),
                      const Divider(),
                      SimpleDialogOption(
                        onPressed: () {
                          print("汉语");
                        },
                        child: const Text('汉语'),
                      ),
                      const Divider(),
                      SimpleDialogOption(
                        onPressed: () {
                          print("汉语");
                        },
                        child: const Text('汉语'),
                      ),
                    ],
                  );
                });
          },
          child: const Text('测试按钮'),
        ),
      ),
    );
  }

14.PageView

 @override
  Widget build(BuildContext context) {
    return PageView.builder(
      scrollDirection: Axis.vertical,
      itemBuilder: (context, index) {
        return Center(
          child: Text("第$index屏"),
        );
      },
      itemCount: 10,
      onPageChanged: (index) {
        print(index);
      },
    );
  }

15.AnimatedList


class _HomePageState extends State<HomePage> {
  final _globalKey = GlobalKey<AnimatedListState>();
  bool flag = true;
  List<String> list = ["第一条", "第二条"];

  Widget _buildItem(index) {
    return ListTile(
      key: ValueKey(index),
      title: Text(list[index]),
      trailing: IconButton(
        icon: const Icon(Icons.delete),
        onPressed: () {
          //执行删除
          _deleteItem(index);
        },
      ),
    );
  }

  _deleteItem(index) {   
    if (flag == true) {
      flag = false;
      //执行删除
      _globalKey.currentState!.removeItem(index, (context, animation) {
        //animation的值是从1到0
        var removeItem = _buildItem(index);
        list.removeAt(index); //数组中删除数据
        return ScaleTransition(
          // opacity: animation,
          scale: animation,
          child: removeItem, //删除的时候执行动画的元素
        );
      });
      //解决快速删除的bug
      Timer.periodic(const Duration(milliseconds: 500), (timer) {
        flag = true;
        timer.cancel();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Title'),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          list.add("我是新增的数据");
          _globalKey.currentState!.insertItem(list.length - 1);
        },
      ),
      body: AnimatedList(
          key: _globalKey,
          initialItemCount: list.length,
          itemBuilder: ((context, index, animation) {
             //animation的值是从0到1
            return FadeTransition(
              opacity: animation,
              child: _buildItem(index),
            );
          })),
    );
  }
}

16.表单

Screenshot_20230101_115045.png Screenshot_20230101_115122.png
 ListView(
        padding: const EdgeInsets.all(10),
        children: [
          const TextField(),
          const SizedBox(height: 20),
          const TextField(
              decoration: InputDecoration(border: OutlineInputBorder())),
          const SizedBox(height: 20),
          const TextField(
              decoration: InputDecoration(
                  hintText: "请输入用户名", border: OutlineInputBorder())),
          const SizedBox(height: 20),
          const TextField(
              obscureText: true, //配置密码框
              decoration: InputDecoration(
                  hintText: "请输入密码", border: OutlineInputBorder())),
          const SizedBox(height: 20),
          TextField(
              decoration: InputDecoration(
                  hintText: "请输入密码",
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(20),
                  ))),
          const SizedBox(height: 20),
          const TextField(
              decoration: InputDecoration(
                  icon: Icon(Icons.add),
                  hintText: "请输入网址",
                  prefixText: "http://",
                  prefixIcon: Icon(Icons.lock),
                  border: OutlineInputBorder())),
          const SizedBox(height: 20),
          const TextField(
            decoration: InputDecoration(
                prefixIcon: Icon(Icons.people),
                hintText: "请输入用户名",
                border: OutlineInputBorder()),
          ),
          const SizedBox(height: 10),
          const TextField(
            obscureText: true,
            decoration: InputDecoration(
                prefixIcon: Icon(Icons.lock),
                hintText: "请输入密码",
                border: OutlineInputBorder()),
          ),
          const SizedBox(height: 20),
           const TextField(           
            decoration: InputDecoration(
                suffixIcon: Icon(Icons.close),
                hintText: "请输入关键词",
                border: OutlineInputBorder()),
          ),

          SizedBox(height: 20),
          const TextField(
            maxLines: 4,
            decoration: InputDecoration(
              border: OutlineInputBorder()
            ),
          )
        ],
      )
```![Screenshot_20230101_115045.png](https://img.haomeiwen.com/i2084643/f3bb6dd5bd51acf7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
上一篇下一篇

猜你喜欢

热点阅读