I am receiving the following error -
I/flutter (18695): The following StackOverflowError was thrown building Consumer(dirty, dependencies:
I/flutter (18695): [_DefaultInheritedProviderScope]):
I/flutter (18695): Stack Overflow
This seems to relate to error in my Consumer. I am using Provider plugin to try to create a toggle button for Dark Mode in Flutter.
See below for my files -
appstatenotifier.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
ThemeData light = ThemeData(
brightness: Brightness.light,
primarySwatch: Colors.indigo,
accentColor: Colors.pink,
scaffoldBackgroundColor: Color(0xfff1f1f1)
);
ThemeData dark = ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.indigo,
accentColor: Colors.pink,
);
class ThemeNotifier with ChangeNotifier {
final String key = "theme";
SharedPreferences prefs;
bool _darkTheme;
bool get darkTheme => darkTheme;
ThemeNotifier() {
_darkTheme = false;
}
toggleTheme() {
_darkTheme = !_darkTheme;
notifyListeners();
}
}
Below is my main.dart relevant Widgets
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
var themeData = ThemeData(
primarySwatch: Colors.blue,
);
return ChangeNotifierProvider(
create: (_) => ThemeNotifier(),
child: Consumer<ThemeNotifier>(
builder: (context, ThemeNotifier notifier, child) {
return MaterialApp(
theme: notifier.darkTheme ? dark : light,
title: 'Work Out Log',
routes: MyApp.routes,
);
}
),
);
}
}
Widget buildDrawer(context) {
return Drawer(
child: ListView(
children: <Widget>[
ListTile(
title: Text('Dark Theme'),
trailing: Consumer<ThemeNotifier>(
builder: (context, notifier, child) => SwitchListTile(
title: Text("Dark mode"),
onChanged: (val) {
notifier.toggleTheme();
},
value: notifier.darkTheme,
),
),
),
],
),
);
}
Any idea why it's throwing this error?
Solution : The solution to resolve this overflow error is to make your entire widget or in our case the Column scrollable. We can do that by wrapping our Column inside a SingleChildScrollView. Also, wrap the SingleChildScrollView with Center so that the entire UI is centered.
As Viren V Varasadiya pointed out, your getter for darkTheme
is incorrect:
bool get darkTheme => darkTheme;
Presumably, you meant to point it at _darkTheme
, but instead you have the getter that is returning itself. This means that any time you call darkTheme
, the getter looks up the value of darkTheme
, which makes the getter look up the value of darkTheme
, which makes the getter look up the value of darkTheme
, which makes the getter look up the value of darkTheme
, which makes the getter look up... (hopefully you get the idea).
You just need to change the getter to return the correct thing:
bool get darkTheme => _darkTheme;
You Must be Retruning the same thing as the class name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With