简体   繁体   中英

Passing data from custom_widget.dart to main.dart

I'm a beginner and this may be basic to most of you, but I did struggle for a few weeks and now I've decided to ask for help.

I'm using SfCalendar in a Flutter project, and I can't pass data "backwards" to main.dart - appBar.

I want to place the month (onChanged) on the AppBar in main.dart. However, my _month is on another file in another widget

MyApp(
  child:CalendarWidget(
      child: SfCalendar //_month is here))

I hope the screenshot makes more sense.

I tried Provider but failed....(don't know how to use it tbh.):(

Screenshot

main.dart

    import 'package:flutter/material.dart';
    import 'package:calendart/NavBar/NavBar.dart';
    import 'package:flutter/services.dart';
    import 'package:flutter_localizations/flutter_localizations.dart';
    import 'package:syncfusion_localizations/syncfusion_localizations.dart';
    import 'package:calendart/Kontroller/kontroller.dart';
    import 'package:calendart/widget/calendar_widget.dart';
    import 'package:provider/provider.dart';
    import 'provider/event_provider.dart';
    
    void main() {
      //Behält die App in aufrechter position
      WidgetsFlutterBinding.ensureInitialized();
      SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
          .then((value) => runApp(Saveta()));
      //Behält die App in aufrechter Position
    }
    
    class Saveta extends StatefulWidget {
      _SavetaState createState() => _SavetaState();
    }
    
    
    class _SavetaState extends State<Saveta> {
    
      String? month;
    
    
      @override
      Widget build(BuildContext context) {
        return ChangeNotifierProvider(
          create: (context) => EventProvider(),
          child: MaterialApp(
            localizationsDelegates: [
              //Sprachen
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
              SfGlobalLocalizations.delegate
            ],
            supportedLocales: const [
              Locale('de'),
            ],
            locale: const Locale('de'),
            debugShowCheckedModeBanner: false,
            home: Scaffold(
              backgroundColor: Colors.white,
              endDrawer: NavBar(),
              //APP BAR 1
              appBar: PreferredSize(
                preferredSize: const Size.fromHeight(60.0),
                child: AppBar(            
                  leading: Builder(
                    builder: (context) => IconButton(
                      onPressed: () {},
                      icon: const Icon(Icons.refresh),
                    ),
                  ),
                  title: Text('$month',          <<<<<---- i need help here
                    style: const TextStyle(
                        color: Colors.black,
                        fontSize: 27,
                        fontWeight: FontWeight.normal),
                  ),
                  backgroundColor: Colors.white,
                  centerTitle: true,
                  elevation: 0,
                  iconTheme:
                  const IconThemeData(color: Colors.black), //betrifft Icons
                ),
              ),
              body: Column(
                children: [
                  Expanded(
                    flex: 15,
                    child: Scaffold(
                      body: CalendarWidget(),
                      floatingActionButtonLocation:
                          FloatingActionButtonLocation.endDocked,
                      floatingActionButton: FloatingActionButton(
                        elevation: 0,
                        backgroundColor: Colors.transparent,
                        child: const Icon(
                          Icons.search,
                          color: Colors.black,
                          size: 40,
                        ),
                        onPressed: () {},
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 10,
                    child: Kontroller(), 
                  ),
                ],
              ),
    
            ),
          ),
        );
      }
    }


calendar_widget.dart

import 'package:calendart/provider/event_provider.dart';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_calendar/calendar.dart';
import 'package:provider/provider.dart';
import '../model/event_data_source.dart';
import 'package:flutter/scheduler.dart';
import 'package:intl/intl.dart';

class CalendarWidget extends StatefulWidget {
  // Nicht ändern - onTap
  CalendarWidget({Key? key}) : super(key: key);


  @override
  State<CalendarWidget> createState() => _CalendarWidgetState();
}

class _CalendarWidgetState extends State<CalendarWidget> {

  String? month, year;

  late final CalendarTapCallback? onTap;


  @override
  Widget build(BuildContext context) {
    final events = Provider.of<EventProvider>(context).events;

    return Padding(
      padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
      child: SfCalendar(
        view: CalendarView.month,
        initialSelectedDate: DateTime.now(),
        dataSource: EventDataSource(events),
        onTap: (details) {
          final provider = Provider.of<EventProvider>(context, listen: false);
          provider.setDate(details.date!);
          print('Test');
        },
        cellBorderColor: Colors.white,
        backgroundColor: Colors.white,
        onViewChanged: viewChanged,
        todayTextStyle: const TextStyle(
          color: Colors.green,
          fontWeight: FontWeight.w900,
        ),
        headerDateFormat: 'MMMM',
        todayHighlightColor: Colors.transparent,
        firstDayOfWeek: 1,
        headerHeight: 0,
        viewHeaderHeight: 15,
        monthViewSettings: MonthViewSettings(
            dayFormat: 'E',
            numberOfWeeksInView: 6,
            appointmentDisplayCount: 3,
            appointmentDisplayMode: MonthAppointmentDisplayMode.appointment,
            monthCellStyle: MonthCellStyle(
              trailingDatesTextStyle:
                  TextStyle(fontSize: 15, color: Colors.grey.shade300),
              leadingDatesTextStyle:
                  TextStyle(fontSize: 15, color: Colors.grey.shade300),
            )),
      ),
    );
  }

  void viewChanged(ViewChangedDetails viewChangedDetails) {
    SchedulerBinding.instance!.addPostFrameCallback((Duration duration) {
      setState(() {
        month = DateFormat('MMMM')
            .format(viewChangedDetails
                .visibleDates[viewChangedDetails.visibleDates.length ~/ 2])
            .toString();
        year = DateFormat('yyyy')
            .format(viewChangedDetails
                .visibleDates[viewChangedDetails.visibleDates.length ~/ 2])
            .toString();
      });
    });
  }
}

I hope this helps.

@pmatatias @Nikunj Ramani (did't work for me)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM