Home > Back-end >  Flutter appbar leading back to previous page error:Null check operator on a null value
Flutter appbar leading back to previous page error:Null check operator on a null value

Time:08-31

i want to go back to my previous page, first i tried Navigator.pop(context); but it returns a black screen. Second try was with this code which i use it to another screen works fine there but here it return this error: Null check operator on a null value

Second try was with this code which i use it to another screen works fine there but here it return this error: Null check operator on a null value

Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) =>  ShowSessionsPage(widget.appController)),
                );

full code:

import 'ShowSessionsPage.dart';
import 'event.dart';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';
import '../../Panels/SessionOrBookingPanel.dart';
import '../../Controllers/AppController.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Calendar extends StatelessWidget {
  late AppController appController;
  Calendar(appController){
    this.appController = appController;
  }  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Calendar',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(appController),
    );
  }

}

class MyHomePage extends StatefulWidget {
  late AppController appController;
  MyHomePage(appController){
    this.appController = appController;
  }

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  late final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  DateRangePickerController _datePickerController = DateRangePickerController();
  @override
  Widget build(BuildContext context) {
    print(widget.appController.list);
    return Scaffold(
          appBar: AppBar(
            leading: IconButton(
              color: widget.appController.themeController.appBlackDeepColor,
              tooltip: 'Back',
              alignment: Alignment.centerLeft,
              icon: (widget.appController.deviceIsAndroid) ? const Icon(Icons.arrow_back) : const Icon(Icons.arrow_back_ios),
              onPressed: () {
                Navigator.push(
              context,
              MaterialPageRoute(builder: (context) =>  ShowSessionsPage(widget.appController)),
            );
              },
            ),
          ),
          body: SfDateRangePicker(
            view: DateRangePickerView.month,
            monthViewSettings: DateRangePickerMonthViewSettings(firstDayOfWeek: 6,
            specialDates:widget.appController.specialDates),
            monthCellStyle: DateRangePickerMonthCellStyle(
              specialDatesDecoration: BoxDecoration(
                  color: Colors.green,
                  border: Border.all(color: const Color(0xFF2B732F), width: 1),
                  shape: BoxShape.circle),
              blackoutDateTextStyle: TextStyle(color: Colors.white, decoration: TextDecoration.lineThrough),
              specialDatesTextStyle: const TextStyle(color: Colors.white),
            ),
            selectionMode: DateRangePickerSelectionMode.multiple,
            onSelectionChanged: _onSelectionChanged,
            controller: _datePickerController,
            onCancel: () {
              _datePickerController.selectedRanges = null;
            },
          ),
        );
  }

 void _onSelectionChanged(
     DateRangePickerSelectionChangedArgs dateRangePickerSelectionChangedArgs) {
   print(dateRangePickerSelectionChangedArgs.value);
 }
}

Error console:

======== Exception caught by widgets library =======================================================
The following _CastError was thrown building ShowSessionsPage(dirty, dependencies: [_LocalizationsScope-[GlobalKey#0c696]], state: _ShowSessionsPageState#fbc3f):
Null check operator used on a null value

The relevant error-causing widget was: 
  ShowSessionsPage ShowSessionsPage:file:///C:/Users/birbi/Desktop/electromobility_flutter_application/lib/Account/Sessions/Calendar.dart:72:63
When the exception was thrown, this was the stack: 
#0      _ShowSessionsPageState.build (package:electromobility_flutter_application/Account/Sessions/ShowSessionsPage.dart:60:49)
#1      StatefulElement.build (package:flutter/src/widgets/framework.dart:4870:27)
#2      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4754:15)
#3      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4928:11)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:4477:5)
#5      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2659:19)
#6      WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:882:21)
#7      RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:363:5)
#8      SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15)
#9      SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1081:9)
#10     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:995:5)
#14     _invoke (dart:ui/hooks.dart:151:10)
#15     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:308:5)
#16     _drawFrame (dart:ui/hooks.dart:115:31)
(elided 3 frames from dart:async)
====================================================================================================

showSessions code:

class ShowSessionsPage extends StatefulWidget {
  late final AppController appController;

  ShowSessionsPage(appController) {
    this.appController = appController;
  }

  _ShowSessionsPageState createState() => _ShowSessionsPageState();
}

class _ShowSessionsPageState extends State<ShowSessionsPage>{
  List<SessionOrBookingPanel> sessionPanels = [];
  bool sessionsLoaded = false;

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

  void loadSessions() async {
    if (await widget.appController.fetchChargeTransactions())
      setState(() {
        sessionsLoaded = true;
      });
  }

  void createSessionPanels(List<dynamic> sessions) {
    int i = 0;
    sessionPanels.clear();
    if (sessions.length != 0){
      while (i < sessions.length){
        sessionPanels.add(new SessionOrBookingPanel(sessions[i], widget.appController, true, true));
        i  ;
      }
    }
  }

  Widget build(BuildContext context) {
    createSessionPanels(widget.appController.sessions);
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        leading: IconButton(
          color: widget.appController.themeController.appBlackDeepColor,
          tooltip: 'Back',
          alignment: Alignment.centerLeft,
          icon: (widget.appController.deviceIsAndroid) ? const Icon(Icons.arrow_back) : const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        title: Text(AppLocalizations.of(context)!.sessions,
          style: TextStyle(color: widget.appController.themeController.appBlackDeepColor),),
        elevation: 0.0,
      ),
      body: sessionsLoaded ?
      Column(
        children: [ ElevatedButton(child: Text('Open Callendar'),
            onPressed: () => {Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => new Calendar(widget.appController)),
            )}),
          Expanded(
            flex: 15,
            child: Container(
              margin: EdgeInsets.only(top: 10.0, bottom: 10.0),
              child: ListView.separated(
                  padding: EdgeInsets.only(left: 10.0, right: 10.0),
                  scrollDirection: Axis.vertical,
                  itemBuilder: (_, index) => sessionPanels[index],
                  separatorBuilder: (context, index) => Divider(color: Colors.transparent,),
                  itemCount: sessionPanels.length),
            ),
          ),
        ],
      )
          :
      Center(
        child: CircularProgressIndicator(),
      ),
    );
  }
}

CodePudding user response:

Add this to your MaterialApp. The error happens because of the null operator (!) in Text(AppLocalizations.of(context)!.sessions,. Because there is no AppLocalizations in the context it throws an error as it returns null.

MaterialApp(
  localizationsDelegates: AppLocalizations.localizationsDelegates,
  supportedLocales: AppLocalizations.supportedLocales,
  ...
  • Related