美文网首页
Flutter 自定义SegmentControl

Flutter 自定义SegmentControl

作者: 赵哥窟 | 来源:发表于2021-04-14 15:07 被阅读0次
    Screenshot_1618383789.png

    如图分段控件,只提供一个思路,想要什么式样自己修改即可,那些Base相关的就是基础控件封装了难得写代码。所以替换就可以了。

    import 'package:flutter/material.dart';
    import 'package:toofoo/common/base_component/base_image.dart';
    import 'package:toofoo/common/base_component/base_text.dart';
    import 'package:toofoo/common/color/colorsUtil.dart';
    import 'package:toofoo/common/screenAdaper/ScreenAdaper.dart';
    
    typedef OnChange = void Function(int index);
    
    class SegmentedControl extends StatefulWidget {
      SegmentedControl({Key key, this.onChange,
      this.titleList});
    
      final OnChange onChange;
      final List<String> titleList ;
    
      @override
      SegmentedControlState createState() => SegmentedControlState();
    }
    
    class SegmentedControlState extends State<SegmentedControl> {
    
      int index ;
    
      @override
      void initState() {
        super.initState();
    
        index = 0;
      }
    
      @override
      Widget build(BuildContext context) {
        return Container(
          height: 44,
          child: _segmentedWidget(),
        );
      }
    
      Widget _segmentedWidget(){
        return Stack(
          children: [
            _segmentedTitleWidget(),
            _indicatorWidget(),
          ],
        );
      }
    
      Widget _segmentedTitleWidget(){
        return Container(
          child: Row(
            children: _getTitleWidget(),
          ),
        );
      }
    
      List<Widget> _getTitleWidget(){
        List<Widget> list = [];
        for(int i = 0; i < widget.titleList.length;i++){
          Expanded title = Expanded(
            child: TextButton(
              onPressed: (){
                setState(() {
                  index = i;
                  if(widget.onChange != null){
                    widget.onChange(i);
                  }
                });
              },
              child: Container(
                alignment: Alignment.center,
                child: BaseText.baseText(widget.titleList[i], 18, i==index?'111E36':'6A7182',fontWeight: i==index?FontWeight.bold:null),
              ),
            ),
          );
          list.add(title);
        }
        return list;
      }
      
      Widget _indicatorWidget(){
         double indicatorWidth =  ScreenAdaper.screenWidth()/widget.titleList.length;
        return Container(
          margin: EdgeInsets.only(left: index*indicatorWidth+indicatorWidth/2-5,top: 34),
          child: BaseImage.getBaseImage('common/search_segment.png'),
        );
      }
    
    
    
    
    }
    
    

    使用

    SegmentedControl(
              titleList: ['歌单','歌曲','筛选'],
              onChange: (int index){
    
              },
     ),
    

    相关文章

      网友评论

          本文标题:Flutter 自定义SegmentControl

          本文链接:https://www.haomeiwen.com/subject/ehaklltx.html