Skip to content

Commit

Permalink
feat: made language switch work via InheritedWidget
Browse files Browse the repository at this point in the history
  • Loading branch information
johsoe committed Sep 8, 2021
1 parent db374e1 commit dd74506
Show file tree
Hide file tree
Showing 8 changed files with 208 additions and 142 deletions.
44 changes: 20 additions & 24 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,28 @@ void main() {
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
Consumer<NStack<Localization>>(
builder: (context, nstack, child) {
return Text(context.localization.defaultSection.title);
}
return MaterialApp(
home: MainScreen(),
);
}
}

return MaterialApp(
home: NStackInitWidget(
child: Scaffold(
appBar: AppBar(
title: Consumer<NStack<Localization>>(
builder: (context, nstack, child) {
return Text(context.localization.defaultSection.test);
}
),
),
body: Center(
child: MaterialButton(onPressed: () => {
NStackWidget.of(context).changeLocalizationOffline(Locale("de-DE"))
}, child: Consumer<NStack<Localization>>(
builder: (context, nstack, child) {
return Text("Selected locale: ${NStackWidget.of(context).activeLanguage.name}");
}
),),
),
),
class MainScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
// App open!
NStackScope.of(context).nstack.appOpen(Localizations.localeOf(context));

return Scaffold(
appBar: AppBar(
title: Text(context.localization.test.testDollarSign),
),
body: Center(
child: MaterialButton(onPressed: () async => {
NStackScope.of(context).changeLanguage(Locale("de-DE"))
},
child: Text("Selected locale: ${NStackScope.of(context).nstack.activeLanguage.name}")
,),
),
);
}
Expand Down
71 changes: 44 additions & 27 deletions example/lib/nstack.dart
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
/// Generated by NStack, do not modify this file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:nstack/models/language.dart';
import 'package:nstack/models/localize_index.dart';
import 'package:nstack/models/nstack_config.dart';
import 'package:nstack/nstack.dart';
import 'package:nstack/partial/section_key_delegate.dart';
import 'package:provider/provider.dart';

// Update this file by running:
// - `flutter pub run build_runner build`, if your package depends on Flutter
Expand Down Expand Up @@ -36,9 +37,9 @@ class _Test extends SectionKeyDelegate {

const _config = NStackConfig(projectId: 'h6wJremI2TGFM88gbLkdyljWQuwf2hxhxvCH', apiKey: 'zp2S18H32b67eYAbRQh94tVw76ZzaKKXlHjd');

const _languages = [
Language(id: 56, name: 'English', locale: 'en-EN', direction: 'LRM', isDefault: true, isBestFit: true),
Language(id: 7, name: 'German (Austria)', locale: 'de-AT', direction: 'LRM', isDefault: false, isBestFit: false),
final _languages = [
LocalizeIndex(id: 1216, url: null, lastUpdatedAt: null, shouldUpdate: false, language: Language(id: 56, name: 'English', locale: 'en-EN', direction: 'LRM', isDefault: true, isBestFit: true)),
LocalizeIndex(id: 1270, url: null, lastUpdatedAt: null, shouldUpdate: false, language: Language(id: 7, name: 'German (Austria)', locale: 'de-AT', direction: 'LRM', isDefault: false, isBestFit: false)),
];

const _bundledTranslations = {
Expand All @@ -52,55 +53,71 @@ final _nstack = NStack<Localization>(
availableLanguages: _languages,
bundledTranslations: _bundledTranslations,
pickedLanguageLocale: '',
debug: kDebugMode
);

class NStackWidget extends InheritedWidget {
final NStack<Localization> nstack = _nstack;
class NStackScope extends InheritedWidget {
final NStack<Localization> nstack;
final NStackState state;
final String checksum;

NStackWidget({Key? key, required Widget child})
NStackScope({Key? key, required Widget child, required this.state, required this.nstack, required this.checksum})
: super(key: key, child: child);

static NStack of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<NStackWidget>()!.nstack;
static NStackState of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<NStackScope>()!.state;

@override
bool updateShouldNotify(NStackWidget oldWidget) =>
nstack != oldWidget.nstack;
bool updateShouldNotify(NStackScope oldWidget) =>
checksum != oldWidget.checksum;
}

class NStackInitWidget extends StatefulWidget {
class NStackWidget extends StatefulWidget {
final Widget child;

const NStackInitWidget({Key? key, required Widget child})
const NStackWidget({Key? key, required Widget child})
: child = child,
super(key: key);

@override
_NStackInitState createState() => _NStackInitState();
NStackState createState() => NStackState();
}

class _NStackInitState extends State<NStackInitWidget> {
static bool _initialized = false;

void setupNStack(BuildContext context) {
//final locale = Localizations.localeOf(context);
final nstack = NStackWidget.of(context);
nstack.appOpen(Locale("en-UK"));
class NStackState extends State<NStackWidget> {
final NStack<Localization> nstack = _nstack;

changeLanguage(Locale locale) async {
print("Starting language switch...");
await _nstack.changeLocalization(locale);
print("Language switch done!");
setState(() {});
}

_attemptAppOpen() {
try {
nstack.appOpen(Localizations.localeOf(context));
} catch(s,e) {
print("NStack could not call appOpen() as the NStackWidget is too far up the widget tree.");
print("Consider calling NStackScope.of(context).nstack.appOpen(Localizations.localeOf(context)) in a splashscreen or later.");
//throw e;
}
}

@override
void initState() {
super.initState();
_attemptAppOpen();
}

@override
Widget build(BuildContext context) {
if (!_initialized) {
setupNStack(context);
_initialized = true;
}
return ChangeNotifierProvider(create: (_) => _nstack, child: widget.child,);
return NStackScope(child: widget.child, state: this, nstack: this.nstack, checksum: nstack.checksum,);
}
}

/// Allows to access the Nstack Localization using the BuildContext
extension NStackWidgetExtension on BuildContext {
Localization get localization => NStackWidget.of(this).localization;
Localization get localization => NStackScope.of(this).nstack.localization;
}

/// Allows to access the Nstack Localization from StatefulWidget's State
Expand Down
2 changes: 1 addition & 1 deletion example/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ packages:
path: ".."
relative: true
source: path
version: "0.2.5"
version: "0.3.0"
package_config:
dependency: transitive
description:
Expand Down
Loading

0 comments on commit dd74506

Please sign in to comment.