Created
August 26, 2021 10:43
-
-
Save ninetails/2b08b6bcb4b8516a0668f2f6ff6d19e9 to your computer and use it in GitHub Desktop.
Flutter config from simple json asset with no depth, just a draft and totally unoptimized
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:flutter/material.dart'; | |
class Config extends InheritedWidget { | |
final Map<String, dynamic> config; | |
final Widget child; | |
Config({Key? key, required this.child, required this.config}) | |
: super(key: key, child: child); | |
static Config of(BuildContext context) { | |
Config? c = context.dependOnInheritedWidgetOfExactType<Config>(); | |
if (c == null) { | |
throw new AssertionError('Config was not set'); | |
} | |
return c; | |
} | |
@override | |
bool updateShouldNotify(Config oldWidget) { | |
return false; | |
} | |
/// Usage: | |
/// | |
/// ```dart | |
/// return Config.fromAsset( | |
/// context: context, | |
/// path: "assets/config.json", | |
/// loading: SplashScreen(), | |
/// onError: (error) => Text('${error}'), | |
/// child: ChangeNotifierProvider( | |
/// create: (ctx) => ProductsProvider(), | |
/// child: Text('mah child here'), | |
/// ), | |
/// ); | |
/// ``` | |
static Widget fromAsset({ | |
required BuildContext context, | |
required String path, | |
required Widget child, | |
Widget Function(Object?)? onError, | |
Widget? loading, | |
}) { | |
return FutureBuilder( | |
future: DefaultAssetBundle.of(context) | |
.loadString(path) | |
.then((config) => jsonDecode(config)), | |
builder: (context, snapshot) { | |
if (snapshot.hasData) { | |
return Config( | |
config: snapshot.data as Map<String, dynamic>, | |
child: child, | |
); | |
} else if (snapshot.hasError) { | |
if (onError != null) { | |
return onError(snapshot.error); | |
} else { | |
throw new AssertionError(snapshot.error); | |
} | |
} else { | |
if (loading != null) { | |
return loading; | |
} | |
return Container(); | |
} | |
}); | |
} | |
/// Usage: | |
/// | |
/// const stringValue = Config.of(context).get<String>(key); | |
/// const intValue = Config.of(context).get<int>(key); | |
T get<T>(String key) { | |
if (!this.config.containsKey(key)) { | |
throw new AssertionError('Unknown config key: ${key}'); | |
} | |
if (this.config[key] is T) { | |
return this.config[key] as T; | |
} | |
throw new AssertionError('Type mismatch for ${key}'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment