Home > Enterprise >  How can I resolve this - Error: Could not find the correct Provider<dModeProvider> above this
How can I resolve this - Error: Could not find the correct Provider<dModeProvider> above this

Time:03-15

Trying to get a dark theme to work on my project app, spent hours making small tweaks to get it to slowly function. Cant get past this error however, I realise the issue is due to the provider not being on the same level, but cant for the life of me find where I need to rectify the issue. If anyone could help would be awesome. This is where the main issue is.

import 'package:flutter/material.dart';
import 'package:location/location.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'Colours.dart';
import 'darkmode.dart';
import 'homeDrawer.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'customTransitions.dart';


void main() {
  runApp(const MaterialApp(
    home: MyState()
    )
  );
}

class MyState extends StatefulWidget {
  const MyState({Key? key}) : super(key: key);

  @override
  _MyStateState createState() => _MyStateState();
}

class _MyStateState extends State<MyState> {

  //Runs automatically when called upon
  @override
  void initState(){
    super.initState();
    getCurrentMode();
  }

  //Reads current stored theme from the preference function and stores it in the provider for user consistency
  void getCurrentMode() async {
    themeProvider.darkMode =
    await themeProvider.dModePreference.getTheme();
  }

  //Initial declaration of map related values and map controller
  late GoogleMapController mapController;
  final LatLng _center = const LatLng(52.912170, -1.184238); // Sets default starting map location as Clifton Campus
  final Location _location = Location();

  //Function runs when the map is created
  void _onMapCreated(GoogleMapController controller){
    mapController = controller;
  }



  //creates instance of the theme provider from darkmode.dart
  dModeProvider themeProvider = dModeProvider();





  @override
  Widget build(BuildContext context) {
    final themeChange = Provider.of<dModeProvider>(context);
    return
    ChangeNotifierProvider(
        create: (_) => dModeProvider(),
        child: Consumer<dModeProvider>(
          builder:(BuildContext context, value, Widget? child) {
            //MaterialApp wraps page and allows theme changes - dark/light mode
            return MaterialApp(
              theme: Styles.themeData(themeProvider.darkMode, context),
              home: Scaffold(
                appBar: AppBar(
                  title: const Text("Campus Navigation"),
                //   actions: <Widget> [
                //     Checkbox(
                //   value: themeChange.darkMode,
                //       onChanged: (bool? value){
                //         themeChange.darkMode = value!;
                //       }
                //       )
                // ],


                  flexibleSpace: Container(
                    decoration: const BoxDecoration(
                        gradient: LinearGradient(
                            begin: Alignment.bottomRight,
                            end: Alignment.topLeft,
                            colors: [secondaryColour, mainColour])

                    ),
                  ),
            ),


                //Sets the background screen to be slightly obscured
                drawerScrimColor: black.withOpacity(0.70),
                drawer: const Drawer(
                  child: homeDrawer(),
                ),


                body: Container(
                  //Establishes the size of the current device screen and uses that as the sizing for the container
                  height: MediaQuery
                      .of(context)
                      .size
                      .height,
                  width: MediaQuery
                      .of(context)
                      .size
                      .width,

                  child: Stack(
                    children: [
                      GoogleMap(
                        initialCameraPosition: CameraPosition(
                          target: _center,
                          zoom: 15.0,
                        ),
                        onMapCreated: _onMapCreated,
                        //enabling getting 'my' location
                        myLocationEnabled: true,
                        //sets map type to normal or topographic, satellite, etc
                        mapType: MapType.normal
                        ,
                      ),


                    ],
                  ),

                ),

              ),
            );


          }
    ),
            );
          }
        }



This is the separate classes made for the provider

import 'package:shared_preferences/shared_preferences.dart';
import 'package:my_application_mpd/Colours.dart';

/// This file has the purpose of making all of the relevant code required to implement a setting for dark mode and light mode
/// Utilised and adapted the method outlined here - https://medium.flutterdevs.com/implement-dark-mode-in-flutter-using-provider-158925112bf9


//Class utilising 'SharedPreferences' to store the setting in the memory and keep dark mode on even if app is closed
class dModePref{
  static const THEME_STATUS = "THEMESTATUS";

  //When dark mode status is changed, saves it
  setdMode( bool value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool(THEME_STATUS, value);
  }

  //Returns current dark mode status
  Future<bool> getTheme() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getBool(THEME_STATUS) ?? false;
  }
}

//Accesses dThemePref in  order to check if the preference has changed and act accordingly
class dModeProvider with ChangeNotifier {
  dModePref dModePreference = dModePref();
  bool _darkMode = false;

  bool get darkMode => _darkMode;

  //Sets the dark modes value to the parsed value and notifies app of change
  set darkMode (bool value){
    _darkMode = value;
    dModePreference.setdMode(value);
    notifyListeners();
  }
}

class Styles {

  static ThemeData themeData(bool dModeStatus, BuildContext context){
    return ThemeData(
      //Theme data for both light and dark mode - detects if dark mode is on and changes to dark colours if it is
      //All colours stored within Colours.dart
      primarySwatch: Colors.blue,
      primaryColor: dModeStatus ? mainColourDark : mainColour,
      backgroundColor: dModeStatus ? secondaryColourDark : secondaryColour,
      indicatorColor: dModeStatus ? indicatorDark : indicatorLight,
      hintColor: dModeStatus ? hintDark : hintLight,
      highlightColor: dModeStatus ? highlightDark : highlightLight,
      hoverColor: dModeStatus ? hoverDark : hoverLight,
      focusColor: dModeStatus ? focusDark : focusLight,
      disabledColor: Colors.grey,
      cardColor: dModeStatus ? cardDark : cardLight,
      canvasColor: dModeStatus ? canvasDark : canvasLight,
      brightness: dModeStatus ? Brightness.dark : Brightness.light,
      buttonTheme: Theme.of(context).buttonTheme.copyWith(colorScheme: dModeStatus ? const ColorScheme.dark() : const ColorScheme.light()),
      appBarTheme: const AppBarTheme(elevation: 0.0,
    ),
    );
  }
}

CodePudding user response:

It seems to me, that you did not put on Widget tree after ChangeNotifierProvider class which extends ChangeNotifier. Check the docs https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple

  • Related