Как сделать виджет Tab, который имеет 3 фасонных бокса рядом с флаттером? - PullRequest
0 голосов
/ 17 февраля 2020

Я пытался использовать виджет вкладок в Flutter . Мне удалось это сделать, но я не могу выбрать квадратные прямоугольники для настройки виджета вкладок,

и дополнений к этому, мне нужно сделать это не внутри панели приложения, они даже просят меня положить это на дно, что, я полагаю, будет правильно делать botombar?

Это образец, который я видел, и я хотел попробовать.

Containers Tabs

Подробнее c, вкладка сверху. Я также хочу поменять его и использовать снизу, если необходимо, но я не смог получить квадратную форму на контейнере.

ОБНОВЛЕНИЕ

вот альтернатива, которую я сделал, но проблема это то, что его можно прокручивать, и я надеюсь оставить его в виде трех ячеек, и люди могут прокручивать его слева направо,

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:survey/widgets/widgetlist.dart';


class pinsurvey extends StatefulWidget {
  @override
  _pinsurveyState createState() => _pinsurveyState();
}

class _pinsurveyState extends State<pinsurvey> with TickerProviderStateMixin {

  TabController _controller;
  AnimationController _animationControllerOn;
  AnimationController _animationControllerOff;

  Animation _colorTweenBackgroundOn;
  Animation _colorTweenBackgroundOff;
  Animation _colorTweenForegroundOn;
  Animation _colorTweenForegroundOff;

  int _currentIndex = 0;
  int _prevControllerIndex = 0;
  double _aniValue = 0.0;
  double _prevAniValue = 0.0;
  List textlist = [
    "CURRENT PINNED",
    "NEWLY CREATED",
    "ARCHIVED",
  ];


  Color _foregroundOn = Colors.white;
  Color _foregroundOff = Colors.black;
  Color _backgroundOn = Colors.blue;
  Color _backgroundOff = Colors.grey[300];
  ScrollController _scrollController = new ScrollController();
  List _keys = [];
  bool _buttonTap = false;

  @override
  void initState() {
    super.initState();

    for (int index = 0; index < textlist.length; index++) {

      _keys.add(new GlobalKey());
    }
    _controller = TabController(vsync: this, length: textlist.length);
    _controller.animation.addListener(_handleTabAnimation);
    _controller.addListener(_handleTabChange);
    _animationControllerOff =
        AnimationController(vsync: this, duration: Duration(milliseconds: 75));
    _animationControllerOff.value = 1.0;
    _colorTweenBackgroundOff =
        ColorTween(begin: _backgroundOn, end: _backgroundOff)
            .animate(_animationControllerOff);
    _colorTweenForegroundOff =
        ColorTween(begin: _foregroundOn, end: _foregroundOff)
            .animate(_animationControllerOff);
    _animationControllerOn =
        AnimationController(vsync: this, duration: Duration(milliseconds: 150));
    _animationControllerOn.value = 1.0;
    _colorTweenBackgroundOn =
        ColorTween(begin: _backgroundOff, end: _backgroundOn)
            .animate(_animationControllerOn);
    _colorTweenForegroundOn =
        ColorTween(begin: _foregroundOff, end: _foregroundOn)
            .animate(_animationControllerOn);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          appBar: AppBar(
            elevation: 0.0,
            automaticallyImplyLeading: false,
            backgroundColor: Colors.transparent,
            title: Container(
              width: 150,
              height: 60,
              child: Image.asset(imgtit2),
            ),
          ),
          backgroundColor: Colors.white,
          body: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
              Text("PIN A NEW SURVEY",style: txtttitsize),
              SizedBox(height: 20),
              Container(
                  height: 49.0,
                  child: ListView.builder(
                      physics: BouncingScrollPhysics(),
                      controller: _scrollController,
                      scrollDirection: Axis.horizontal,
                      itemCount: textlist.length,
                      itemBuilder: (BuildContext context, int index) {
                        return Padding(
                            key: _keys[index],
                            padding: EdgeInsets.all(1.0),
                            child: ButtonTheme(
                                child: AnimatedBuilder(
                                  animation: _colorTweenBackgroundOn,
                                  builder: (context, child) => FlatButton(
                                      color: _getBackgroundColor(index),
                                      shape: RoundedRectangleBorder(
                                          borderRadius: new BorderRadius.circular(1.0)),
                                      onPressed: () {
                                        setState(() {
                                          _buttonTap = true;
                                          _controller.animateTo(index);
                                          _setCurrentIndex(index);
                                           _scrollTo(index);
                                        });
                                      },
                                      child: Text(textlist[index])),
                                )));
                      })),
              Flexible(
                  child: TabBarView(
                    controller: _controller,
                    children: <Widget>[
                      Text(textlist[0]),
                      Text(textlist[1]),
                      Text(textlist[2]),
                    ],
                  )),
            ]),
          )),
    );
  }

  _handleTabAnimation() {
    _aniValue = _controller.animation.value;
    if (!_buttonTap && ((_aniValue - _prevAniValue).abs() < 1)) {
      _setCurrentIndex(_aniValue.round());
    }
    _prevAniValue = _aniValue;
  }
  _handleTabChange() {
    if (_buttonTap) _setCurrentIndex(_controller.index);
    if ((_controller.index == _prevControllerIndex) ||
        (_controller.index == _aniValue.round())) _buttonTap = false;
    _prevControllerIndex = _controller.index;
  }
  _setCurrentIndex(int index) {
    if (index != _currentIndex) {
      setState(() {
        _currentIndex = index;
      });
     _triggerAnimation();
      _scrollTo(index);
    }
  }
  _triggerAnimation() {
    _animationControllerOn.reset();
    _animationControllerOff.reset();
   _animationControllerOn.forward();
    _animationControllerOff.forward();
  }

  _scrollTo(int index) {
    double screenWidth = MediaQuery.of(context).size.width;
    RenderBox renderBox = _keys[index].currentContext.findRenderObject();
    double size = renderBox.size.width;
    double position = renderBox.localToGlobal(Offset.zero).dx;
    double offset = (position + size / 2) - screenWidth / 2;
    if (offset < 0) {
      renderBox = _keys[0].currentContext.findRenderObject();
      position = renderBox.localToGlobal(Offset.zero).dx;
      if (position > offset) offset = position;
    } else {
      renderBox = _keys[textlist.length - 1].currentContext.findRenderObject();
      position = renderBox.localToGlobal(Offset.zero).dx;
      size = renderBox.size.width;
      if (position + size < screenWidth) screenWidth = position + size;
      if (position + size - offset < screenWidth) {
        offset = position + size - screenWidth;
      }
    }
    _scrollController.animateTo(offset + _scrollController.offset,
        duration: new Duration(milliseconds: 150), curve: Curves.easeInOut);
  }

  _getBackgroundColor(int index) {
    if (index == _currentIndex) {
      return _colorTweenBackgroundOn.value;
    } else if (index == _prevControllerIndex) {
      return _colorTweenBackgroundOff.value;
    } else {
      return _backgroundOff;
    }
  }


}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...