Instantly share code, notes, and snippets.

@roughike /main.dart Secret
Last active Jan 12, 2019

Embed
What would you like to do?
Solution for https://gist.github.com/hillelcoren/d3c5e27b9e52f9f8560f87ca67cbf751: changing themes on a Flutter Redux without AppBuilder widget
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';
void main() {
final store = Store<AppState>(
reducer,
distinct: true,
initialState: AppState(enableDarkMode: false),
);
runApp(StoreProvider<AppState>(
store: store,
child: MyApp(),
));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StoreConnector<AppState, bool>(
distinct: true,
converter: (store) => store.state.enableDarkMode,
builder: (_, bool enableDarkMode) {
return MaterialApp(
theme: ThemeData(
brightness: enableDarkMode ? Brightness.dark : Brightness.light,
),
home: Scaffold(
appBar: AppBar(
title: Text('Test Redux App'),
),
body: SettingsView(),
),
);
},
);
}
}
class SettingsView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StoreBuilder( // Would use a StoreConnector & ViewModel in the real world
builder: (BuildContext context, Store<AppState> store) {
final state = store.state;
return SwitchListTile(
title: Text('Dark Mode'),
value: state.enableDarkMode,
onChanged: (value) {
store.dispatch(UpdateDarkMode(enable: !state.enableDarkMode));
},
secondary: Icon(Icons.settings),
);
},
);
}
}
// Redux
class AppState {
AppState({@required this.enableDarkMode});
bool enableDarkMode;
}
class UpdateDarkMode {
UpdateDarkMode({@required this.enable});
final bool enable;
}
AppState reducer(AppState state, dynamic action) {
if (action is UpdateDarkMode) {
return AppState(
enableDarkMode: action.enable,
);
}
return state;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment