Flutter 小案例

底部tabbar 实现

import 'package:flutter/material.dart';
import 'bottom_nav_bar.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'myApp',
      home: BottomNavBar(),
    );
  }
}
import 'package:flutter/material.dart';
import './pages/email_screen.dart';
import './pages/page_screen.dart';
import './pages/play_screen.dart';
import './pages/home_screen.dart';

class BottomNavBar extends StatefulWidget {
  @override
  _BottomNavBarState createState() => _BottomNavBarState();
}

class _BottomNavBarState extends State<BottomNavBar> {
  final _BtmNavBarColor = Colors.blue;
  int _currentIndex = 0;
  List<Widget> pageList = new List(); // 此处也可以直接赋值数组
  // 重写初始化方法
  @override
  void initState() {
    // 1.将页面装载到List组件中
    pageList
      ..add(HomeScreen())
      ..add(PageScreen())
      ..add(EmailScreen())
      ..add(PlayScreen());
    // 通过父类调用初始化方法
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //3.设置要显示的组件
      body: pageList[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(
              icon: Icon(
                Icons.home,
                color: _BtmNavBarColor,
              ),
              title: Text(
                'Home',
                style: TextStyle(color: _BtmNavBarColor),
              )),
          BottomNavigationBarItem(
              icon: Icon(
                Icons.pages,
                color: _BtmNavBarColor,
              ),
              title: Text(
                'Pages',
                style: TextStyle(color: _BtmNavBarColor),
              )),
          BottomNavigationBarItem(
              icon: Icon(
                Icons.email,
                color: _BtmNavBarColor,
              ),
              title: Text(
                'Email',
                style: TextStyle(color: _BtmNavBarColor),
              )),
          BottomNavigationBarItem(
              icon: Icon(
                Icons.airplay,
                color: _BtmNavBarColor,
              ),
              title: Text(
                'AipPlay',
                style: TextStyle(color: _BtmNavBarColor),
              )),
        ],
//两个字段,shifting是只有选中的时候才显示icon下面的text,fixed是不管选中不选中都显示text.
        type: BottomNavigationBarType.fixed,
        //2.设置tabbar的点击事件 并接收一个触发对象的下标
        onTap: (int index) {
          //将点击的index 传给 body中要显示的下标
          setState((){
             _currentIndex= index;
           });
        },
        //4.设置高亮的tabbar下标
        currentIndex: _currentIndex,
      ),
    );
  }
}

页面切换效果实现

import 'package:flutter/material.dart';
import './pages/custom_router.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'my App',
      //设置App主题颜色
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FirstPage(),
    );
  }
}

class FirstPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blue,
      appBar: AppBar(
        title: Text('First Page'),
        elevation: 4.0,
        leading: Container(),
      ),
      body: Center(
        child: MaterialButton(
          child: Icon(
            Icons.navigate_next,
            color: Colors.white,
            size: 64.0,
          ),
          onPressed: () {
            Navigator.push(context, CustomRoute(SecondPage()));
          },
        ),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.pinkAccent,
      appBar: AppBar(
        title: Text('Second Page'),
        elevation: 4.0,
        backgroundColor: Colors.pinkAccent,
      ),
      body: Center(
        child: MaterialButton(
          child: Icon(
            Icons.navigate_before,
            color: Colors.white,
            size: 64.0,
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
}
//custom_router.dartimport 'package:flutter/material.dart';

class CustomRoute extends PageRouteBuilder {
  final Widget widget;
  //构造函数,重构父类的方法
  CustomRoute(this.widget)
      : super(
            //动画时间
            transitionDuration: const Duration(seconds: 1),
            //实现跳转
            pageBuilder: (BuildContext context, Animation<double> animation1,
                Animation<double> animation2) {
              return widget;
            },
            //实现动画
            transitionsBuilder: (context, Animation<double> animation1,
                Animation<double> animation2, child) {
              // 渐变
              // return FadeTransition(
              //   opacity: Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(
              //       parent: animation1, curve: Curves.fastOutSlowIn)),
              //   //child参数一定要设置上 否则会出现黑屏 该参数是用来设置多个动画叠加嵌套使用的(比如既放大又旋转)
              //   child: child,
              // );
              //缩放
              // return ScaleTransition(
              //   scale: Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(
              //       parent: animation1, curve: Curves.fastOutSlowIn)),
              //   child: child,
              // );
              //旋转加缩放
              // return RotationTransition(
              //     turns: Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(
              //         parent: animation1, curve: Curves.fastOutSlowIn)),
              //     child: ScaleTransition(
              //       scale: Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(
              //           parent: animation1, curve: Curves.fastOutSlowIn)),
              //       child: child,
              //     ));
              // 抽屉滑动
              return SlideTransition(
                  position: Tween<Offset>(
                          begin: Offset(-1.0, 0.0), end: Offset(0.0, 0.0))
                      .animate(CurvedAnimation(
                          parent: animation1,
                          //设置动画曲线
                          curve: Curves.fastOutSlowIn)),
                  child: child);
            });
}

顶部Tabbar实现

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'my App',
      home: KeepAlive(),
    );
  }
}

class KeepAlive extends StatefulWidget {
  @override
  _KeepAliveState createState() => _KeepAliveState();
}
    //类的混入
class _KeepAliveState extends State<KeepAlive>
    with SingleTickerProviderStateMixin {
  //实例化一个tab controller
  // 为了使tab起作用,我们需要保持选中的tab和相关内容同步。这就是 TabController的职责。
  TabController _controller;
  //2.重写初始化页面方法
  @override
  void initState() {
    super.initState();
    //设置tab的个数 并传入this 固定写法
    _controller = TabController(length: 3, vsync: this);
  }

  //3.重写组件销毁方法
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('tabbar'),
        //1.构建Tabbar组件以及配置tab
        bottom: TabBar(
         //在TabBar中指定实例化的TabController
          controller: _controller,
          tabs: <Widget>[
            Tab(
              icon: Icon(Icons.directions_car),
            ),
            Tab(
              icon: Icon(Icons.directions_transit),
            ),
            Tab(
              icon: Icon(Icons.directions_bike),
            ),
          ],
        ),
      ),
      //4.在body中显示被选中的页面
      body: TabBarView(
        //在TabBarView中指定实例化的TabController
        controller: _controller,
        children: <Widget>[
          Center(
            child: Text('This is Car!'),
          ),
          Center(
            child: Text('This is Transit!'),
          ),
          Center(
            child: Text('This is Bike!'),
          ),
        ],
      ),
    );
  }
}

保存状态 缓存页面

import 'package:flutter/material.dart';

class KeepAliveScreen extends StatefulWidget {
  @override
  _KeepAliveScreenState createState() => _KeepAliveScreenState();
}

// 类混入
class _KeepAliveScreenState extends State<KeepAliveScreen>
    with AutomaticKeepAliveClientMixin {
  int _counter = 0;
  // 重写方法 保存状态 默认为false
  @override
  bool get wantKeepAlive => true;

  //定义一个按钮点击事件的处理函数
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          //Center 嵌套 column 那么column轴上的居中对齐会失效 同理row
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('点一下加1,点一下加1'),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: Icon(Icons.add)),
    );
  }
}

搜索条实现

import 'package:flutter/material.dart';
import 'package:myapp/pages/assets.dart';

class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('searchPage'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.search),
            padding: const EdgeInsets.fromLTRB(0.0, 0.0, 50.0, 0.0),
            onPressed: () {
              // print('搜索');
              showSearch(delegate: SearchBar(), context: context);
            },
          )
        ],
      ),
    );
  }
}

class SearchBar extends SearchDelegate<String> {
  //设置右边x号
  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () {
          //清空输入框内容
          query = '';
        },
      )
    ];
  }

  // 设置左边<-
  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: AnimatedIcon(
        //设置一个带动画的Icon
        icon: AnimatedIcons.menu_arrow, progress: transitionAnimation,
      ),
      onPressed: () => close(context, null), //关闭当前页面
    );
  }

  // 设置搜索推荐项
  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestionList = query.isEmpty
        ? recentSuggest
        : searchList.where((input) {
            //查询所输入的字符串
            return input.startsWith(query);
          }).toList();
    return ListView.builder(
        itemCount: suggestionList.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: RichText(
                text: TextSpan(
                    //截取列表item中所输入的字符串 并设置了样式
                    text: suggestionList[index].substring(0, query.length),
                    style: TextStyle(
                        color: Colors.black, fontWeight: FontWeight.bold),
                    children: [
                  TextSpan(
                      //将item中剩余的字符串 设置样式
                      text: suggestionList[index].substring(query.length),
                      style: TextStyle(color: Colors.grey))
                ])),
          );
        });
  }

  // 点击搜索,结果样式设置
  @override
  Widget buildResults(BuildContext context) {
    return Container(
      width: 100.0,
      height: 100.0,
      child: Card(
        color: Colors.blueAccent,
        child: Center(
          child: Text(query),
        ),
      ),
    );
  }
}

添加照片(流式布局)

import 'package:flutter/material.dart';

class WrapDemo extends StatefulWidget {
  @override
  _WrapDemoState createState() => _WrapDemoState();
}

class _WrapDemoState extends State<WrapDemo> {
  // 定义组件列表
  List<Widget> boxList = List();
  // 定义初始化方法
  @override
  void initState() {
    boxList..add(buildButton());
    super.initState();
  }

  // 定义buildButton方法 返回类型为组件
  Widget buildButton() {
    //返回一个带手势的组件
    return GestureDetector(
      onTap: () {
        if (boxList.length < 9) {
          print('add');
          setState(() {
            boxList.insert(boxList.length - 1, buildPicture());
          });
        }
      },
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Container(
          width: 80.0,
          height: 80.0,
          color: Colors.black54,
          child: Icon(Icons.add),
        ),
      ),
    );
  }

  // 定义buildPicture方法 返回类型为组件
  Widget buildPicture() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Container(
        width: 80,
        height: 80,
        color: Colors.amber,
        child: Center(
          child: Text('照片'),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    //适配
    final width = MediaQuery.of(context).size.width;
    final height = MediaQuery.of(context).size.height;
    return Scaffold(
      appBar: AppBar(
        title: Text('添加照片'),
      ),
      body: Center(
        child: Opacity(
          opacity: 0.8,
          child: Container(
            width: width,
            height: height / 2,
            color: Colors.grey,
            child: Wrap(
              children: boxList,
              spacing: 26.0,
            ),
          ),
        ),
      ),
    );
  }
}

欢迎页

import 'package:flutter/material.dart';
import './home_page.dart';

class AnimationPage extends StatefulWidget {
  @override
  _AnimationPageState createState() => _AnimationPageState();
}

class _AnimationPageState extends State<AnimationPage>
    with SingleTickerProviderStateMixin {
  //定义一个控制器
  AnimationController _controller;
  //定义一个animation
  Animation _animation;
  // 定义初始化方法
  @override
  void initState() {
    _controller = AnimationController(
        vsync: this, duration: Duration(milliseconds: 3000));
    _animation = Tween(begin: 0.0, end: 1.0).animate(_controller);
    super.initState();

    // 动画监听器 监听动画对象的状态
    _animation.addStatusListener((status) {
      //如果动画结束则跳转页面后并清除当前页面
      if (status == AnimationStatus.completed) { //如果动画结束了
        Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(builder: (context) => HomePage()),
            (route) => route == null); //销毁当前页面
      }
    });
    // 播放动画
    _controller.forward();
  }

  // 销毁_controller
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值