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?
buildDrawer
? Stack overflows happen when there is an infinite method loop (either a method calling itself or multiple methods calling each other over and over again without being told to stop at some point), but there doesn't seem to be enough information here to be able to tell where the stack overflow is coming from. – Tay