【问题标题】:Center a listview child on selection将列表视图子项居中选择
【发布时间】:2021-05-06 07:43:11
【问题描述】:

我正在尝试将所有选定的日期设置为黄色背景并始终位于中心,我该如何实现?

我现在拥有的:

这是我迄今为止所取得的成就:

选择的当前日期:https://i.stack.imgur.com/P2bPp.png
选择了另一个日期:https://i.stack.imgur.com/oKFXu.png

我想要实现的示例:

https://i.stack.imgur.com/yb6Lx.png
https://i.stack.imgur.com/G9rZc.png

请指教。提前致谢。

这是我的代码:

日期选择器

 return Container(
    height: 85.0,
    margin: EdgeInsets.only(left: 20.0, right: 20.0),
    child: ListView.builder(
      scrollDirection: Axis.horizontal,
      controller: _controller,
      itemCount: daysCount,
      itemBuilder: (context, index) {
        int daysCountBefore = daysCount ~/ 2;
        DateTime today = DateTime.now();

        //get half of the days count before today first then start up total daysCount
        // 2021-01-30 15:31:16.481
        DateTime startDate =
            today.subtract(Duration(days: daysCountBefore));

        //convert to 00:00:00.000 hours
        // 2021-01-30 00:00:00.000
        DateTime _startDate =
            new DateTime(startDate.year, startDate.month, startDate.day);

        // print(_startDate.day);
        // print(daysCountBefore);

        //show days count from start date
        DateTime dates = _startDate.add(Duration(days: index));

        //format to 00:00:00.00 hrs
        //mainly for _compareDates();
        DateTime _dates = new DateTime(dates.year, dates.month, dates.day);

        bool isSelected = _currentDate != null
            ? _compareDates(_dates, _currentDate)
            : false;

        return DateWidget(
          date: dates,
          width: isSelected ? 65.0 : 40.0,
          selectedColor:
              isSelected ? widget.selectedDateColor : Colors.transparent,
          dayNumTextStyle: isSelected
              ? kSelectedDayNumTextStyle
              : kNotSelectedDayNumTextStyle,
          dayMonthTextStyle: isSelected
              ? kSelectedDayMonthTextStyle
              : kNotSelectedDayMonthTextStyle,
          dateTapped: (dateToShow) {
            //change state to the date that is tapped
            setState(() {
              _currentDate = dateToShow;
            });

            //Callback
            widget.onDateChange(dateToShow);
          },
        );
      },
    ));

日期小部件:

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

class DateWidget extends StatelessWidget {
  final DateTime date;
  final TextStyle textStyle;
  final Color selectedColor;
  final TextStyle dayMonthTextStyle;
  final Function(DateTime) dateTapped;
  final double width; //75.0
  final TextStyle dayNumTextStyle;

  DateWidget(
      {@required this.date,
      @required this.dateTapped,
      this.textStyle,
      this.width,
      this.selectedColor,
      this.dayNumTextStyle,
      this.dayMonthTextStyle});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        child: Container(
            margin: EdgeInsets.all(3.0),
            width: width,
            height: 80.0,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(20.0)),
              color: selectedColor,
            ),
            child: Padding(
              padding: EdgeInsets.all(8.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(new DateFormat('MMM').format(date).toUpperCase(),
                      style: dayMonthTextStyle),
                  Text(date.day.toString(), style: dayNumTextStyle),
                  Text(
                    new DateFormat('E').format(date).toUpperCase(),
                    // style: TextStyle(fontWeight: FontWeight.bold)
                    style: dayMonthTextStyle,
                  )
                ],
              ),
            )),
        onTap: () {
          dateTapped(date);
        });
  }
}

【问题讨论】:

  • 尝试添加示例代码,以便社区可以重现您的情况!如果您添加代码,将会有更多人对您的问题感兴趣。
  • 感谢您的建议!我已经编辑了我的帖子并添加了我的代码

标签: flutter listview dart widget


【解决方案1】:

您可以使用Carousel Slider

例子-

CarouselSlider(
  options: CarouselOptions(height: 400.0),
  items: [1,2,3,4,5].map((i) {
    return Builder(
      builder: (BuildContext context) {
        return Container(
          width: MediaQuery.of(context).size.width,
          margin: EdgeInsets.symmetric(horizontal: 5.0),
          decoration: BoxDecoration(
            color: Colors.amber
          ),
          child: Text('text $i', style: TextStyle(fontSize: 16.0),)
        );
      },
    );
  }).toList(),
)

【讨论】:

    【解决方案2】:

    这是一个仅基于 ListView.builder 及其 ScrollController 的解决方案:

    import 'dart:math';
    
    import 'package:flutter/material.dart';
    import 'package:flutter_hooks/flutter_hooks.dart';
    
    void main() {
      runApp(
        MaterialApp(
          title: 'Flutter Demo',
          home: Scaffold(
            body: MyWidget(data: List.generate(100, (index) => index)),
          ),
        ),
      );
    }
    
    class MyWidget extends HookWidget {
      final List<int> data;
    
      const MyWidget({Key key, this.data}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        final _scrollController = useScrollController();
        final _selected = useState(0);
        return LayoutBuilder(
          builder: (context, constraints) {
            final double size = constraints.biggest.width / 10;
            return SizedBox(
              height: size,
              child: ListView.builder(
                controller: _scrollController,
                scrollDirection: Axis.horizontal,
                itemExtent: size,
                itemCount: data.length,
                itemBuilder: (context, index) => Padding(
                  padding: EdgeInsets.all(size * .05),
                  child: GestureDetector(
                    onTap: () {
                      _selected.value = index;
                      _scrollController.animateTo(
                        max(index - 4.5, 0) * size,
                        duration: Duration(seconds: 1),
                        curve: Curves.easeInOut,
                      );
                    },
                    child: Card(
                      color: _selected.value == index
                          ? Colors.amber
                          : Colors.lightGreen.shade100,
                      child: Center(
                        child: Text(data[index].toString()),
                      ),
                    ),
                  ),
                ),
              ),
            );
          },
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-04
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 2014-07-31
      • 2015-02-12
      • 2016-10-26
      相关资源
      最近更新 更多