(摘) Flutter 组件

声明:内容源自网络,版权归原作者所有。若有侵权请在网页聊天中联系我

ListView

List listData = [
   {
          "title": 'Candy Shop',
          "author": 'Mohamed Chahin',
          "imageUrl": "https://www.itying.com/images/flutter/1.png",
   },
   {
         ...
   },
]


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

  List<Widget> _getData() {
    // List<Widget> list = [];
    // for (var i = 0; i < 20; i++) {
    //   list.add(ListTile(
    //     title: Text("我是$i列表"),
    //   ));
    // }
    // return list;

    var tempList = listData.map((value) {
      return ListTile(leading: Image.network(value["imageUrl"]), title: Text(value["title"]), subtitle: Text(value["author"]));
    });
    return tempList.toList();
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      //scrollDirection: Axis.horizontal,
      padding: const EdgeInsets.all(10),
      children: _getData(),
    );
  }
}

方法2

  List list = [];
  HomeContent({Key? key}) : super(key: key) {
    for (var i = 0; i < 20; i++) {
      list.add(ListTile(
        title: Text("我是$i"),
        subtitle: Text("我是小标题$i"),
        leading: const Icon(Icons.abc),
      ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: list.length,
      itemBuilder: (context, index) {
        return list[index];
      },
    );
  }

修改方法1,调用定义好的数组

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: listData.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(listData[index]["title"]),
          subtitle: Text(listData[index]["author"]),
          leading: Image.network(listData[index]["imageUrl"]),
        );
      },
    );
  }

route 路由

// 不带参数
return Container(
  child: Center(
    child: RaisedButton(
      child: Text('按键-搜索'),
      color: Theme.of(context).accentColor,
      textTheme: ButtonTextTheme.primary,
      onPressed: (){
       //路由
        Navigator.of(context).push(
            MaterialPageRoute(
                builder: (context)=>searchPage()
            )
        );
      },),
  ),
);


// 带参数
return Container(
  child: Center(
    child: RaisedButton(
      child: Text('按键-搜索'),
      color: Theme.of(context).accentColor,
      textTheme: ButtonTextTheme.primary,
      onPressed: (){
      //路由
        Navigator.of(context).push(
            MaterialPageRoute(
                builder: (context)=>searchPage(title: 'sendToTitle',)
            )
        );
      },),
  ),
);

返回:Navigator.of(content).pop();

AppBar

leading 左侧组件
title 中间组件
actions 右侧组件
bottom 底部组件

return Scaffold(
  appBar: AppBar(
    title: Text('Hello Flutter'),
    backgroundColor: Colors.red,
    centerTitle: true,//标题居中显示
    leading: IconButton(
        icon: Icon(Icons.menu),
        onPressed: (){
          print('点击左边按键');
    }),
    actions: <Widget>[
      IconButton(
          icon: Icon(Icons.search),
          onPressed: (){
            print('点击右边按键1');
          }),
      IconButton(
          icon: Icon(Icons.settings),
          onPressed: (){
            print('点击右边按键2');
          }),
    ],
  ),
  body: Center(
    child: Container(
      child: Text('hello flutter'),
    ),
  ),
);

TabBar

可滑动和点击标签栏,通常用于AppBar的底部,可与TabBarView联用,实现滑页效果。

class _categoryPageState extends State<categoryPage> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return DefaultTabController(
        length: 2,
        child: Scaffold(
          appBar: AppBar(
            title: Row(
              children: <Widget>[
                Expanded(
                    child: TabBar(
                        indicatorColor: Colors.white,//选中Label颜色
                        labelColor: Colors.white,//选中文字颜色
                        unselectedLabelColor: Colors.white,//未选中文字颜色
                        indicatorSize: TabBarIndicatorSize.label,//指示器长度
                        isScrollable: true,//如果多个按钮的话可以滑动
                        tabs: <Widget>[
                           Tab(text: '军事'),
                           Tab(text: '经济'),
                    ]))
              ],
            ),
            centerTitle: true, //标题居中显示
          ),
          body: TabBarView(children: <Widget>[
            ListView(
              children: <Widget>[
                ListTile(
                  title: Text('第一行'),
                ),
                ListTile(
                  title: Text('第二行'),
                ),
                ListTile(
                  title: Text('第三行'),
                ),
              ],
            ),
            ListView(
              children: <Widget>[
                ListTile(
                  title: Text('第一行'),
                ),
                ListTile(
                  title: Text('第二行'),
                ),
                ListTile(
                  title: Text('第三行'),
                ),
              ],
            )
          ]),
        ));
  }
}

Drawer 侧边栏

一般用于Scaffold中的draw和endDraw属性作为左右的滑页栏,可以容纳一个子组件,能指定影深

class _formPageState extends State<formPage> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      floatingActionButton: FloatingActionButton(
          child: Text('Back'),
          onPressed: () {
            Navigator.of(context).pop();
          }),
      appBar: AppBar(
        title: Text('from'),
      ),
      body: Container(
        child: Center(
          child: RaisedButton(
            child: Text('按键-登录2'),
            color: Theme.of(context).accentColor,
            textTheme: ButtonTextTheme.primary,
            onPressed: () {
              Navigator.pushNamed(context, '/login');
//              Navigator.of(context).pushReplacementNamed('/login');
            },
          ),
        ),
      ),
      drawer: Drawer(
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                    child: DrawerHeader(
                  child: Text('hello flutter'),
                  decoration: BoxDecoration(
                      color: Colors.blue,//设置头部背景颜色
                      image: DecorationImage(
                          image: NetworkImage(
                              'https://www.itying.com/images/flutter/2.png'),//设置头部背景图片
                          fit: BoxFit.cover)),//图片平铺
                ))
              ],
            ),
            ListTile(
              title: Text('我的空间'),
              leading: CircleAvatar(
                child: Icon(Icons.home),
              ),
            ),
            Divider(),
            ListTile(
              title: Text('我的收藏'),
              leading: CircleAvatar(
                child: Icon(Icons.search),
              ),
            ),
            Divider(),
            ListTile(
              title: Text('我的记录'),
              leading: CircleAvatar(
                child: Icon(Icons.settings),
              ),
            ),
            Divider(),
            ListTile(
              title: Text('我的订单'),
              leading: CircleAvatar(
                child: Icon(Icons.headset),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

AlterDialog 提示框

  void dalog(BuildContext context) {
    showDialog<void>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text("测试"),
            content: SingleChildScrollView(
              child: ListBody(
                children: const <Widget>[Text("中间内容"), Text("中间内容1")],
              ),
            ),
            actions: <Widget>[
              FlatButton(
                child: const Text("actions"),
                onPressed: () {
                  Navigator.of(context).pop(); //关闭弹框9
                },
              )
            ],
          );
        });
  }

TextField

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController usernameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController password2Controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("DEMO"),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            TextField(
              controller: usernameController, //  每个单词的首字母大写
              //  textCapitalization: TextCapitalization.words
              textCapitalization: TextCapitalization.none, // 输入的键盘类型
              keyboardType: TextInputType.number, // 样式
              // 内边框
              decoration: const InputDecoration(
                  contentPadding: EdgeInsets.all(10.0),
                  icon: Icon(Icons.person),
                  labelText: '请输入你的用户名', // 提示文本
                  helperText: '请输入注册的用户名'),
              cursorColor: Colors.green, // 光标颜色
              cursorRadius: const Radius.circular(16.0), // 光标样式
              cursorWidth: 16.0, // 光标大小
              textInputAction: TextInputAction.go, // 完成按钮
            ),
            const SizedBox(height: 30.0),
            TextField(
                controller: passwordController,
                decoration: const InputDecoration(
                    //  外边框
                    border: OutlineInputBorder(),
                    helperText: '请输入用户名',
                    labelText: '用户名',
                    prefixIcon: Icon(Icons.person),
                    suffixIcon: Icon(Icons.print))),
            const SizedBox(height: 30.0),
            TextField(
              controller: password2Controller,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                  contentPadding: EdgeInsets.all(10.0),
                  icon: Icon(Icons.lock),
                  labelText: '请输入密码'),
              obscureText: true, //  是否是安全的
            ),
            RaisedButton(
              onPressed: () {
                if (usernameController.text.length != 11) {
                  print('请输入正确的手机号');
                }
              },
              child: const Text('登陆'),
            )
          ],
        ),
      ),
    );
  }
}

PopupMenuButton

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: Scaffold(
          appBar: AppBar(title: const Text("DEMO")),
          body: const Center(child: DemoPage()),
        ));
  }
}

class DemoPage extends StatefulWidget {
  const DemoPage({Key? key}) : super(key: key);

  @override
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {
  void printSelectValue(String val) {
    print(val);
  }

  @override
  Widget build(BuildContext context) {
    return ListView(children: <Widget>[
      ListTile(
          title: const Text('弹出菜单'),
          trailing: PopupMenuButton<String>(
            padding: EdgeInsets.zero,
            onSelected: printSelectValue,
            itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
              // 菜单项
              const PopupMenuItem(
                value: '会议',
                child: ListTile(
                  leading: Icon(Icons.lock),
                  title: Text('锁定会议'),
                ),
              ),
              const PopupMenuDivider(), // 分割线
              const PopupMenuItem(
                value: '结束会议',
                child: ListTile(
                  leading: Icon(Icons.lock),
                  title: Text('结束会议'),
                ),
              )
            ],
          ))
    ]);
  }
}

ListTile

class DemoPage extends StatefulWidget {
  const DemoPage({Key? key}) : super(key: key);

  @override
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {
  String dropdownValue = 'One';

  @override
  Widget build(BuildContext context) {
    return ListView(children: <Widget>[
      ListTile(
        title: const Text('下拉菜单'),
        trailing: DropdownButton(
          value: dropdownValue,
          onChanged: (val) {
            setState(() {
              dropdownValue = val.toString();
            });
          },
          items: <String>['One', "Two", "Three"]
              .map<DropdownMenuItem<String>>((String val) {
            // 渲染每一个可选项
            return DropdownMenuItem<String>(
              value: val,
              child: Text(val),
            );
          }).toList(),
        ),
      )
    ]);
  }
}

SnackBar

下方弹出的消息

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Code Sample for Scaffold.of.',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: const MyScaffoldBody(),
        appBar: AppBar(title: const Text('Scaffold.of Example')),
      ),
      color: Colors.white,
    );
  }
}

// 在Scaffold子组件里的build方法可以调用Scaffold.of方法
class MyScaffoldBody extends StatelessWidget {
  const MyScaffoldBody({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(
        child: const Text('SHOW A SNACKBAR'),
        onPressed: () {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Row(
                children: const [
                  Icon(
                    Icons.check,
                    color: Colors.green,
                  ),
                  Text('下载成功')
                ],
              ),
              action: SnackBarAction(
                label: '知道了',
                onPressed: () {},
              ),
              // shape: const RoundedRectangleBorder(
              //     borderRadius: BorderRadius.all(Radius.circular(50))),
              duration: const Duration(seconds: 1),
              behavior: SnackBarBehavior.floating,
            ),
          );
        },
      ),
    );
  }
}

flutter动画组件AnimatedContainer

import 'package:flutter/material.dart';

class AnimatedContainerScreen extends StatefulWidget {
  AnimatedContainerScreen({Key key}) : super(key: key);

  @override
  _AnimatedContainerScreenState createState() => _AnimatedContainerScreenState();
}

class _AnimatedContainerScreenState extends State<AnimatedContainerScreen> {
  bool normal = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Animated Container'),
      ),
      body: Container(
        alignment: Alignment.center,
        child: AnimatedContainer(
          width: normal ? 200 : 100,
          height: normal ? 200 : 100,
          color: normal ? Colors.blue : Colors.red,
          duration: Duration(milliseconds: 500),
          curve: Curves.easeInOut,
          onEnd: () {
            debugPrint('animate end ======');
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Text('switch'),
        onPressed: () {
          setState(() {
            normal = !normal;
          });
        }
      )
    );
  }
}

相关文章