Last active
May 26, 2020 12:35
-
-
Save lesnitsky/81dee2900598978718e2a40f844cb733 to your computer and use it in GitHub Desktop.
InheritedWidget override
This file contains 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 'package:flutter/material.dart'; | |
class Service { | |
final String authToken; | |
Service({this.authToken}); | |
getData() async { | |
if (authToken == null) { | |
fetchAnonymous(); | |
} else { | |
fetchAuthenticated(authToken); | |
} | |
} | |
} | |
class ServiceProvider extends InheritedWidget { | |
final Widget child; | |
final String authToken; | |
Service get service => Service(authToken: authToken); | |
ServiceProvider({Key key, this.child, this.authToken}) | |
: super(key: key, child: child); | |
@override | |
bool updateShouldNotify(ServiceProvider oldWidget) { | |
return oldWidget.child != child || oldWidget.authToken != authToken; | |
} | |
static ServiceProvider of(BuildContext context) => | |
context.dependOnInheritedWidgetOfExactType<ServiceProvider>(); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return ServiceProvider( | |
// no auth token, anonymous flow | |
child: MaterialApp( | |
home: Anonymous(), | |
), | |
); | |
} | |
} | |
class Anonymous extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
final service = ServiceProvider.of(context).service; | |
// service is anonymous here | |
return Container( | |
// override anonymous service from MyApp and make everything below this widget authenticated | |
child: ServiceProvider( | |
authToken: 'Bearer 1234', | |
child: AuthenticatedWidget(), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment