The calendar is working fine, but the problem is whenever I change the month the events aren't visible on the calendar dates. but it appears after I click on any date. can anyone explain what is going wrong here?
Full Calendar Widget implementation
Calendar(
initialDate: month2,
startOnMonday: false,
onMonthChanged: (m) => {
print("onMonthChanged called: " + m.month.toString()),
print(month2),
if (m.month != month2.month)
{
setState(() {
month2 = m;
year2 = m.year;
eventsMap();
}),
events.clear(),
}
},
selectedColor: Colors.blue,
todayColor: Colors.red,
eventColor: Colors.green,
eventDoneColor: Colors.amber,
bottomBarColor: Colors.deepOrange,
events: events,
isExpanded: true,
dayOfWeekStyle: TextStyle(
fontSize: 12,
color: Colors.blueGrey,
fontWeight: FontWeight.bold,
),
bottomBarTextStyle: TextStyle(
color: Colors.white,
),
hideArrows: false,
weekDays: const ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
)
I'm using a calendar widget that displays events on dates in a dot form and also in a form of a list just below it. When I change the month it triggers an onMonthChanged event and fetches the events to display. The only problem I'm having is that Initially, the events aren't showing on dates but after I click on any date, then it shows the events. So, in short, the problem is events aren't displayed initially.
onMonthChanged property implementation
onMonthChanged: (m) => {
print("onMonthChanged called: " + m.month.toString()),
if (m.month != month2)
{
setState(() {
month2 = m.month;
year2 = m.year;
eventsMap();
}),
events.clear(),
}
},
Calendar class
class Calendar extends StatefulWidget {
final ValueChanged<DateTime>? onDateSelected;
final ValueChanged<DateTime>? onMonthChanged;
final ValueChanged<bool>? onExpandStateChanged;
final ValueChanged? onRangeSelected;
final ValueChanged<CleanCalendarEvent>? onEventSelected;
final bool isExpandable;
final DayBuilder? dayBuilder;
final EventListBuilder? eventListBuilder;
final bool hideArrows;
final bool hideTodayIcon;
final Map<DateTime, List<CleanCalendarEvent>>? events;
final Color? selectedColor;
final Color? todayColor;
final String todayButtonText;
final Color? eventColor;
final Color? eventDoneColor;
final DateTime? initialDate;
final bool isExpanded;
final List<String> weekDays;
final String? locale;
final bool startOnMonday;
final bool hideBottomBar;
final TextStyle? dayOfWeekStyle;
final TextStyle? bottomBarTextStyle;
final Color? bottomBarArrowColor;
final Color? bottomBarColor;
final String? expandableDateFormat;
}
provide Date and Time object to
initialDate
parameter
you are using on month changed callback so you have to use onselecteddate callback
Related
I need to use theme extinction for colors for example inside theme extension for LargeBodyTextStyle
#immutable
class BodyLargeStyle extends ThemeExtension<BodyLargeStyle> {
final Color? color;
final double? fontSize;
final double? lineHeight;
final FontWeight? fontWeight;
final String? fontFamily;
const BodyLargeStyle({
required this.color,
required this.fontSize,
required this.lineHeight,
required this.fontWeight,
required this.fontFamily,
});
#override
ThemeExtension<BodyLargeStyle> copyWith() {
// TODO: implement copyWith
throw UnimplementedError();
}
#override
ThemeExtension<BodyLargeStyle> lerp(
ThemeExtension<BodyLargeStyle>? other, double t) {
// TODO: implement lerp
throw UnimplementedError();
}
static BodyLargeStyle bodyLargeStyle = BodyLargeStyle(
color: Theme.of(context).extension<CustomColors>()!.color,
fontSize: 12,
lineHeight: 1,
fontWeight: FontWeight.w400,
fontFamily: "any",
);
}
here I need to implement something like this but I don't have the context and I need to get use
of how theme Extention useful when changing from light to dark via verse
this is RadioModel.dart
I am a beginner in flutter and I want to display my JSON file data on vx swipper.builder but i don't know whats going on here when i pass item count i face this error i know i am doing something wrong and i can't fix this
I am a beginner in flutter and I want to display my JSON file data on vx swipper.builder but i don't know whats going on here when i pass item count i face this error i know i am doing something wrong and i can't fix this
I am a beginner in flutter and I want to display my JSON file data on vx swipper.builder but i don't know whats going on here when i pass item count i face this error i know i am doing something wrong and i can't fix this
import 'dart:convert';
class MyRadioList {
static List<MyRadio>? radios;
// Get Item by ID
MyRadio getById(int id) =>
radios!.firstWhere((element) => element.id == id, orElse: null);
// Get Item by position
MyRadio getByPosition(int pos) => radios![pos];
}
class MyRadio {
final int id;
final int order;
final String name;
final String tagline;
final String color;
final String desc;
final String url;
final String category;
final String icon;
final String image;
final String lang;
MyRadio({
required this.id,
required this.order,
required this.name,
required this.tagline,
required this.color,
required this.desc,
required this.url,
required this.category,
required this.icon,
required this.image,
required this.lang,
});
factory MyRadio.fromMap(Map<String, dynamic> map) {
return MyRadio(
id: map['id'],
order: map['order'],
name: map['name'],
tagline: map['tagline'],
color: map['color'],
desc: map['desc'],
url: map['url'],
category: map['category'],
icon: map['icon'],
image: map['image'],
lang: map['lang'],
);
}
toMap() => {
"id": id,
"order": order,
"name": name,
"tagline": tagline,
"color": color,
"desc": desc,
"url": url,
"category": category,
"icon": icon,
"image": image,
"lang": lang,
};
}
// this is HomePage.dart
import 'dart:convert';
import 'dart:ffi';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_application_1/models/RadioModel.dart';
import 'package:flutter_application_1/utils/Ai_Utils.dart';
import 'package:velocity_x/velocity_x.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
//get daata from radio model
#override
void initstate() {
super.initState();
fetchradios();
}
fetchradios() async {
final radioJson = await rootBundle.loadString("assets/radio.json");
final decodedData = jsonDecode(radioJson);
MyRadioList.radios = List.from(decodedData)
.map<MyRadio>(((radio) => MyRadio.fromMap(radio)))
.toList();
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(),
body: Stack(children: [
VxAnimatedBox()
.withGradient(LinearGradient(
colors: [AiColors.primaryColor1, AiColors.primaryColor2],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
))
.size(context.screenWidth, context.screenHeight)
.make(),
AppBar(
title: "AI Radio".text.xl4.bold.white.make().shimmer(
primaryColor: Vx.purple300, secondaryColor: Colors.white),
elevation: 0.0,
backgroundColor: Colors.transparent,
centerTitle: true,
).h(100.0).p16(),
VxSwiper.builder(
itemCount: MyRadioList.radios?.length, // error line
itemBuilder: (context, index) {
final rad = MyRadioList.radios![index];
return VxBox(child: ZStack([]))
.bgImage(DecorationImage(image: NetworkImage(rad.image)))
.make();
})
]),
);
}
}
itemCount must be a non-nullable int.
But your static List<MyRadio>? radios is a nullable List, so the length may be null if the List is never initialized
You can use the If-null operator ?? to initialize it to 0 or whatever default value you want to use if the length happens to be null
Change this line:
itemCount: MyRadioList.radios?.length, // error line
To this:
itemCount: MyRadioList.radios?.length ?? 0 // 0 or whatever default value
The line above essentially reads if MyRadioList.radios?.length is not null, then use it, otherwise set MyRadioList.radios?.length to 0.
Using ?? ensures that the length of your list will never be null
I want to change the way DatePicker shows the Date, so that it shows
day/month/year. As of right now it shows in the format of year/month/day and I'm not sure on how to change this. I've been searching a lot but couldn't find the right way to do this.
I will show my code below, hopefully someone can help me :D
Thank you in Advance guys.
class WFDatePickerField extends DateTimeField {
final bool? hasError;
final bool hasErrorDecoration;
final double? errorHeight;
final dynamic error;
final DateTimeValue value;
final TextStyle? errorStyle;
WFDatePickerField(
{Key? key,
required this.value,
required String labelText,
String hintText = '',
TextEditingController? controller,
FormFieldValidator<DateTime>? validator,
FloatingLabelBehavior? floatingLabelBehavior =
FloatingLabelBehavior.never,
String format = 'dd.MM.yyyy',
final InputDecoration? decoration,
this.errorStyle,
this.hasError,
this.hasErrorDecoration=false,
this.error,
this.errorHeight})
: super(
key: key,
decoration: ErrorDecorationSelector(hasError, hasErrorDecoration, errorHeight, error, value, errorStyle).getDecoration(),
readOnly: true,
style: AppTheme()
.textStyles
.bodyText1!
.copyWith(color: Colors.white.withOpacity(0.5)),
initialValue: value.value,
format: DateFormat('dd/MM/yyyy'),
controller: controller,
validator: validator,
onShowPicker: (context, currentValue) async {
DateTime? newDate;
String? deviceLocale = await (Devicelocale.currentLocale);
LocaleType locale =
deviceLocale != null && deviceLocale.contains('de')
? LocaleType.de
: LocaleType.en;
await DatePicker.showDatePicker(context,
minTime: DateTime(1900, 1, 1),
maxTime: DateTime(DateTime.now().year - 18,
DateTime.now().month, DateTime.now().day),
locale: locale,
onConfirm: (date) => newDate = date);
return newDate;
},
onChanged: (newValue) {
value.value = newValue;
},
);
}
if I'M not mistaken your trying to format the date if that is what you're asking
[enter link description here][1]
// Use this link it is flutter intl dateFormater it has different style
[1]: https://pub.dev/packages/intl
I am building a calendar through syncfusion calendar on a flutter app and I have been getting an error that tells me "Field '' has not been initialized". I know that I need to initialize _startDate and _endDate but I am not sure what value it should be given.
Code :
class EventCalendar extends StatefulWidget {
const EventCalendar({Key? key}) : super(key: key);
#override
EventCalendarState createState() => EventCalendarState();
}
List<Color> _colorCollection = <Color>[];
List<String> _colorNames = <String>[];
int _selectedColorIndex = 0;
late DataSource _events;
Meeting? _selectedAppointment;
late DateTime _startDate;
late TimeOfDay _startTime;
late DateTime _endDate;
late TimeOfDay _endTime;
bool _isAllDay = false;
String _subject = '';
String _notes = '';
class EventCalendarState extends State<EventCalendar> {
EventCalendarState();
CalendarView _calendarView = CalendarView.month;
late List<String> eventNameCollection;
late List<Meeting> appointments;
#override
void initState() {
_calendarView = CalendarView.month;
appointments = getMeetingDetails();
_events = DataSource(appointments);
// initialize _startDate and _endDate here?
_selectedAppointment = null;
_selectedColorIndex = 0;
_subject = '';
_notes = '';
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: UserDrawer(),
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.black),
backgroundColor: Colors.transparent,
elevation: 0,
centerTitle: true,
title: const Text('Itinerary',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
color: Colors.black)),
),
resizeToAvoidBottomInset: false,
body: Padding(
padding: const EdgeInsets.fromLTRB(5, 0, 5, 5),
child: getEventCalendar(_calendarView, _events, onCalendarTapped)),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add, color: Colors.white),
backgroundColor: Color(0xFF003893),
onPressed: () => Navigator.push<Widget>(
context,
MaterialPageRoute(
builder: (BuildContext context) => EventEditor()),
)));
}
SfCalendar getEventCalendar(
CalendarView _calendarView,
CalendarDataSource _calendarDataSource,
CalendarTapCallback calendarTapCallback) {
return SfCalendar(
view: _calendarView,
backgroundColor: Colors.transparent,
initialSelectedDate: DateTime.now(),
todayHighlightColor: Color(0xFF003893),
selectionDecoration: BoxDecoration(color: Colors.white60),
showNavigationArrow: true,
cellBorderColor: Colors.transparent,
firstDayOfWeek: 1,
onTap: calendarTapCallback,
allowedViews: [
CalendarView.day,
CalendarView.week,
CalendarView.month,
CalendarView.timelineWeek
],
monthViewSettings: MonthViewSettings(
showAgenda: true,
agendaViewHeight: 250,
appointmentDisplayMode: MonthAppointmentDisplayMode.appointment),
dataSource: _calendarDataSource,
initialDisplayDate: DateTime(DateTime.now().year, DateTime.now().month,
DateTime.now().day, 0, 0, 0),
timeSlotViewSettings: TimeSlotViewSettings(
minimumAppointmentDuration: const Duration(minutes: 60)),
);
}
void onCalendarViewChange(String value) {
if (value == 'Day') {
_calendarView = CalendarView.day;
} else if (value == 'Week') {
_calendarView = CalendarView.week;
} else if (value == 'Month') {
_calendarView = CalendarView.month;
} else if (value == 'Timeline week') {
_calendarView = CalendarView.timelineWeek;
}
setState(() {});
}
void onCalendarTapped(CalendarTapDetails calendarTapDetails) {
if (calendarTapDetails.targetElement != CalendarElement.appointment) {
return;
}
setState(() {
_selectedAppointment = null;
_isAllDay = false;
_selectedColorIndex = 0;
_subject = '';
_notes = '';
if (_calendarView == CalendarView.month) {
_calendarView = CalendarView.day;
} else {
if (calendarTapDetails.appointments != null &&
calendarTapDetails.appointments!.length == 1) {
final Meeting meetingDetails = calendarTapDetails.appointments![0];
_startDate = meetingDetails.from;
_endDate = meetingDetails.to;
_isAllDay = meetingDetails.isAllDay;
_selectedColorIndex =
_colorCollection.indexOf(meetingDetails.background);
_subject = meetingDetails.eventName == '(No title)'
? ''
: meetingDetails.eventName;
_notes = meetingDetails.description;
_selectedAppointment = meetingDetails;
} else {
final DateTime date = calendarTapDetails.date!;
_startDate = date;
_endDate = date.add(const Duration(hours: 1));
}
_startTime =
TimeOfDay(hour: _startDate.hour, minute: _startDate.minute);
_endTime = TimeOfDay(hour: _endDate.hour, minute: _endDate.minute);
Navigator.push<Widget>(
context,
MaterialPageRoute(builder: (BuildContext context) => EventEditor()),
);
}
});
}
List<Meeting> getMeetingDetails() {
final List<Meeting> meetingCollection = <Meeting>[];
eventNameCollection = <String>[];
eventNameCollection.add('');
_colorCollection = <Color>[];
_colorCollection.add(const Color(0xFF3D4FB5));
_colorCollection.add(const Color(0xFF0F8644));
_colorCollection.add(const Color(0xFF8B1FA9));
_colorCollection.add(const Color(0xFFD20100));
_colorCollection.add(const Color(0xFFFC571D));
_colorCollection.add(const Color(0xFF85461E));
_colorCollection.add(const Color(0xFFFF00FF));
_colorCollection.add(const Color(0xFFE47C73));
_colorCollection.add(const Color(0xFF636363));
_colorNames = <String>[];
_colorNames.add('Blue');
_colorNames.add('Green');
_colorNames.add('Purple');
_colorNames.add('Red');
_colorNames.add('Orange');
_colorNames.add('Caramel');
_colorNames.add('Magenta');
_colorNames.add('Peach');
_colorNames.add('Gray');
return meetingCollection;
}
}
class DataSource extends CalendarDataSource {
DataSource(List<Meeting> source) {
appointments = source;
}
#override
bool isAllDay(int index) => appointments![index].isAllDay;
#override
String getSubject(int index) => appointments![index].eventName;
#override
String getNotes(int index) => appointments![index].description;
#override
Color getColor(int index) => appointments![index].background;
#override
DateTime getStartTime(int index) => appointments![index].from;
#override
DateTime getEndTime(int index) => appointments![index].to;
}
class Meeting {
Meeting(
{required this.from,
required this.to,
this.background = Colors.green,
this.isAllDay = false,
this.eventName = '',
this.description = ''});
final String eventName;
final DateTime from;
final DateTime to;
final Color background;
final bool isAllDay;
final String description;
}
On top of the error, when I go to another page and return back to this calendar page, whatever events that was saved on it earlier on disappears already.
What value should I be giving to initialize _startDate and _endDate and how do I save the state of the page?
All state properties must be declared inside State class. late means that such variable will be initialized later (for example in initState method). If initialization time is not known make variable nullable, I.e. use question mark for type (e.g. DateTime?.
You don't initialize start and end dates, to be able to accept null use ?
like that
DateTime? _startDate;
DateTime? _endDate;
You can make them nullable, with DateTime? and before using them, where you got an error like when you want to access the hour property from them, you can check them if they are null, like this:
if([_startTime, _endTime].contains(null)) return;
Also, since you don't use the data outside of the handler and it is used after you change the value, you can initialize them with DateTime.now(), like this:
DateTime _startDate = DateTime.now();
And you can do this:
if (_calendarView == CalendarView.month) {
_calendarView = CalendarView.day;
return;
}
To remove the else that's coming after.
While specifying the variable as nullable we need to set the values before use them, in this case the AppointmentEditor class used the _startDate and _endDate values before initializing them, hence to use the values we must ensure that the values were set with values, hence before navigate to the editor page we must set values for the startDate and endDate variable with the required values, in this case you can use the selected date value from CalendarController or current date time value, or the date time value which you want to add the event in calendar.
In this shared code snippet, we have used current time value for the both variables as a default value, kindly set the _startDate and _endDate in the onPressed callback of the FloatingActionButton. Please find the attached code snippet for the same.
Code snippet:
onPressed: () {
_startDate??=DateTime.now();
_endDate??=DateTime.now();
Navigator.push<Widget>(
context,
MaterialPageRoute(
builder: (BuildContext context) => AppointmentEditor()),
)
}
I want to pass the title data from one screen (ChatModel.dart) to another one.
I created a Model that includes the topic, which in this case is the title of the screen.
This is the model code:
class User {
final int id;
final String topic;
final String imageUrl;
final bool isThereNewMessages;
User({
this.id,
this.topic,
this.imageUrl,
this.isThereNewMessages,
});
}
final User Members = User(
id: 0,
topic: 'New Members',
imageUrl: 'https://...',
isThereNewMessages: true,
);
final User Sell = User(
id: 1,
topic: 'Sell and Buy',
imageUrl: 'https://i....',
isThereNewMessages: true,
);
What I need to do is to access dinamically to the topic in each screen.
I've created a variable to access to the User model:
final chat = User;
and imported the file.
Then I am accessing by doing this:
Text(
User.topic,
textScaleFactor: 1.5,
style: TextStyle(fontWeight: FontWeight.bold),
),
Its not working. How should I pass the data?
You are accessing the User constructor instead of the Members variable.
Change
final chat = User;
To
final chat = Member;
Then
Text(
chat.topic,
textScaleFactor: 1.5,
style: TextStyle(fontWeight: FontWeight.bold),
),