简体   繁体   English

如何才能在Flutter中更改此日历小部件中的选定日期?

[英]How can I change the selected date in this calendar widget in flutter?

I am trying to make a calendar widget where one date can be selected, I can set the selected date with hardcode but I want to be able to change the selected date from the inner Widget (DayWidget). 我正在尝试制作一个可以选择一个日期的日历小部件,我可以使用硬编码设置所选日期,但是我希望能够从内部小部件(DayWidget)更改所选日期。

My code: 我的代码:

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

class HorizontalCalendar extends StatefulWidget {
  final double height;
  final double width;
  final EdgeInsets padding;
  final EdgeInsets margin;
  final int month;
  final int year;
  final int selectedDate;
  HorizontalCalendar({
    @required this.year,
    @required this.month,
    this.selectedDate,
    this.height,
    this.width,
    this.margin = const EdgeInsets.all(0),
    this.padding = const EdgeInsets.all(0),
  });
  @override
  _HorizontalCalendarState createState() => _HorizontalCalendarState();
}

class _HorizontalCalendarState extends State<HorizontalCalendar> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: widget.height,
      margin: widget.margin,
      padding: widget.padding,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: DateTime(widget.year, widget.month + 1, 0).day,
        itemBuilder: (context, index) {
          index = index + 1;
          DateTime date = DateTime(widget.year, widget.month, index);
          return DayWidget(
            day: index,
            dayName: DateFormat('EEEE').format(date).substring(0, 3),
            selected: widget.selectedDate == index ? true : false,
          );
        },
      ),
    );
  }
}

DayWidget: DayWidget:

class DayWidget extends StatelessWidget {
  final int day;
  final String dayName;
  final bool selected;
  DayWidget({this.day, this.dayName, this.selected = false});
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 5),
      child: SizedBox(
        width: MediaQuery.of(context).size.width * 0.17,
        child: FlatButton(
          color: selected ? Colors.white : Colors.transparent,
          shape: new RoundedRectangleBorder(
              borderRadius: new BorderRadius.circular(15.0),
              side: BorderSide(
                  color: selected ? Colors.white : Colors.grey,
                  width: 1,
                  style: BorderStyle.solid)),
          onPressed: () {
            // Here I should be able to change the selected date from
            // The HorizontalCalendar
          },
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              Text(
                dayName,
                style: TextStyle(
                    color: selected ? Colors.blueGrey : Colors.white60,
                    fontSize: 15,
                    fontWeight: selected ? FontWeight.w900 : FontWeight.w300),
              ),
              Text(
                day.toString(),
                style: TextStyle(
                    color: selected ? Colors.blueGrey : Colors.white,
                    fontSize: 24,
                    fontWeight: selected ? FontWeight.w900 : FontWeight.w500),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

image of the widget for clarification 小部件的图像,以进行澄清

Im trying to change the selected date when the DayWidget is pressed, but i do not seem to have access to the HorizontalCalendar Widget, i tried to make a method static, but if i make a method inside the HorizontalCalendar static I cannot use setState to update the view. 我试图在按下DayWidget时更改选定的日期,但是我似乎无法访问Horizo​​ntalCalendar Widget,我试图使方法成为静态方法,但是如果我使Horizo​​ntalCalendar中的方法成为静态方法,则无法使用setState更新风景。

Please guide me into a better way to implement this. 请引导我以更好的方式实现此目标。

  1. First we need to move selectedDate to mutable variable. 首先,我们需要 selectedDate移至可变变量。 we need to re-declare it on _HorizontalCalendarState class. 我们需要在_HorizontalCalendarState类上重新声明它。
class HorizontalCalendar extends StatefulWidget {
  final double height;
  final double width;
  final EdgeInsets padding;
  final EdgeInsets margin;
  final int month;
  final int year;
  final int selectedDate; // this is immutable
  HorizontalCalendar({
    @required this.year,
    @required this.month,
    this.selectedDate,
    this.height,
    this.width,
    this.margin = const EdgeInsets.all(0),
    this.padding = const EdgeInsets.all(0),
  });
  @override
  _HorizontalCalendarState createState() => _HorizontalCalendarState();
}

class _HorizontalCalendarState extends State<HorizontalCalendar> {

  int selectedDay; // this is mutable

  @override
  void initState() {
    selectedDay = widget.selectedDate;
    super.initState();
  }
  1. Secondly, we can pass callback to DayWidget. 其次,我们可以将回调传递给DayWidget。
return DayWidget(
  day: index,
  dayName: DateFormat('EEEE').format(date).substring(0, 3),
  selected: selectedDay == index ? true : false, // modify this
  callback: (int day) { // Add this
    selectedDay = day;
    setState((){});
  },
);
  1. Finally, we can callback within DayWidget : 最后,我们可以在DayWidget中回调:
onPressed: () {
  callback(day);
  // Here I should be able to change the selected date from
  // The HorizontalCalendar
},

This is the result : 结果是:

演示版

  1. Full Code 完整代码
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class HorizontalCalendar extends StatefulWidget {
  final double height;
  final double width;
  final EdgeInsets padding;
  final EdgeInsets margin;
  final int month;
  final int year;
  final int selectedDate; // this is immutable
  HorizontalCalendar({
    @required this.year,
    @required this.month,
    this.selectedDate,
    this.height,
    this.width,
    this.margin = const EdgeInsets.all(0),
    this.padding = const EdgeInsets.all(0),
  });
  @override
  _HorizontalCalendarState createState() => _HorizontalCalendarState();
}

class _HorizontalCalendarState extends State<HorizontalCalendar> {

  int selectedDay; // this is mutable

  @override
  void initState() {
    selectedDay = widget.selectedDate;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: widget.height,
      margin: widget.margin,
      padding: widget.padding,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: DateTime(widget.year, widget.month + 1, 0).day,
        itemBuilder: (context, index) {
          index = index + 1;
          DateTime date = DateTime(widget.year, widget.month, index);
          return DayWidget(
            day: index,
            dayName: DateFormat('EEEE').format(date).substring(0, 3),
            selected: selectedDay == index ? true : false,
            callback: (int day) {
              selectedDay = day;
              setState((){});
            },
          );
        },
      ),
    );
  }
}

class DayWidget extends StatelessWidget {
  final int day;
  final String dayName;
  final bool selected;
  final Function(int) callback;
  DayWidget({
    this.day,
    this.dayName,
    this.selected = false,
    this.callback,
  });
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 5),
      child: SizedBox(
        width: MediaQuery.of(context).size.width * 0.17,
        child: FlatButton(
          color: selected ? Colors.white : Colors.transparent,
          shape: new RoundedRectangleBorder(
            borderRadius: new BorderRadius.circular(15.0),
            side: BorderSide(
                color: selected ? Colors.white : Colors.grey,
                width: 1,
                style: BorderStyle.solid),
          ),
          onPressed: () {
            callback(day);
            // Here I should be able to change the selected date from
            // The HorizontalCalendar
          },
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              Text(
                dayName,
                style: TextStyle(
                  color: selected ? Colors.blueGrey : Colors.white60,
                  fontSize: 15,
                  fontWeight: selected ? FontWeight.w900 : FontWeight.w300,
                ),
              ),
              Text(
                day.toString(),
                style: TextStyle(
                  color: selected ? Colors.blueGrey : Colors.white,
                  fontSize: 24,
                  fontWeight: selected ? FontWeight.w900 : FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在flutter中从日历中获取选定的日期 - how to get the selected date from the calendar in flutter flutter 当 api 更改时,我如何重建我的小部件? - flutter how can i rebuild my widget when api change? 如何更改 Flutter 默认时间选择小部件文本? - How can I change the Flutter default time selection widget text? 如何从 Flutter 中的另一个小部件更改 DropdownButton 值? - How can I change DropdownButton values from another widget in Flutter? 如何在Flutter中更改所选图块边框的颜色? - How can I change the colour of the border of the selected tile in Flutter? 在 flutter 中选中时,如何更改图标 colors? - How can I change Icon colors when it's selected in flutter? Flutter - 如何从其他小部件访问 DropDown 中当前选定的项目? - Flutter - How can I access current selected item in DropDown from other widget? 如何使用 flutter 中的 dropdownSearch 小部件获取列表中所选项目的 ID? - How can I get the id of a selected item in a list using the the dropdownSearch widget in flutter? 如何根据日历上的选定日期从 Firebase 获取数据? - How can I fetch data from Firebase based on the selected date on calendar? 如何在 flutter 中添加自定义日历? - how can I add a custom calendar in flutter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM