MainApp send to page depending on value - dart

I am building a Flutter app and when the app starts I want to send the user to either the login page (if not yet logged in) or the Dashboard page (if logged in).
Basically, the main() will just be code, no widgets. How would I accomplish this?
Im imagining something like:
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: new StarterPoint()
));
}
class StarterPoint extends StatelessWidget {
final bool loggedIn = false;
if (loggedIn) {
Navigator.push(
MaterialPageRoute(builder: (context) => Dashboard()),
);
} else {
Navigator.push(
MaterialPageRoute(builder: (context) => Login()),
);
}
}

Here's a simple example of what you could do. I think you need to keep track of state in StarterPoint depending on whether or not you are logged in.
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: StarterPoint()));
}
class StarterPoint extends StatefulWidget {
#override
State<StatefulWidget> createState() => StarterPointState();
}
class StarterPointState extends State<StarterPoint> {
bool loggedIn = false;
#override
Widget build(BuildContext context) {
if (loggedIn) {
return Dashboard();
} else {
return Login(() => setState(() {
loggedIn = true;
}));
}
}
}
class Dashboard extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Text('hello!');
}
}
class Login extends StatelessWidget {
final Function() callBack;
Login(this.callBack);
#override
Widget build(BuildContext context) {
return Column(children: [
RaisedButton(child: Text('press'), onPressed: () => callBack())
]);
}
}

Related

bloc does not get initialized when using generic bloc provider

Here is the bloc (simplified):
import 'package:autobleidas_flutter/bloc/bloc_base.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:rxdart/rxdart.dart';
class LoginBloc extends BlocBase {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final PublishSubject<bool> loggedIn = PublishSubject<bool>();
final PublishSubject<bool> loading = PublishSubject<bool>();
}
Here is the bloc provider:
class BlocProvider<T> extends InheritedWidget {
final T bloc;
BlocProvider({Key key, Widget child, this.bloc})
: super(key: key, child: child);
static T of<T extends BlocBase>(BuildContext context) {
final type = _typeOf<BlocProvider<T>>();
return (context.inheritFromWidgetOfExactType(type) as BlocProvider).bloc;
}
static Type _typeOf<T>() => T;
#override
bool updateShouldNotify(InheritedWidget oldWidget) {
return true;
}
}
However, in the LoginScreen I cannot access the loggedIn Subject of the bloc. Here is how LoginScreen is opened from main and the bloc is passed to it:
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
localizationsDelegates: GlobalMaterialLocalizations.delegates,
supportedLocales: allTranslations.supportedLocales(),
home: BlocProvider<LoginBloc>(child: LoginScreen()), // <-------- HERE
);
}
}
Here is how I try to access it in the LoginScreen:
class _LoginScreenState extends State<LoginScreen> {
bool _isLoading = false;
#override
void didChangeDependencies() {
LoginBloc bloc = BlocProvider.of<LoginBloc>(context);
bloc.loggedIn.listen((isLoggedIn) => Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => RegistrationScreen())));
bloc.loading.listen((state) => setState(() => _isLoading = state));
super.didChangeDependencies();
}
#override
Widget build(BuildContext context) {
return Container();
}
the error:
The getter 'loggedIn' was called on null.
So why is the bloc null? How do I fix this?
In this line, BlocProvder expect a bloc.
home: BlocProvider<LoginBloc>(child: LoginScreen()),
You are not passing your bloc here.
Pass it like below:
home: BlocProvider<LoginBloc>(child: LoginScreen(),bloc: LoginBloc()),
BlocProvider<LoginBloc> means your defining a type of the bloc you are going to pass.

How to initialize state using the Provider package?

TL;DR - Getting providerInfo = null from Consumer<ProviderInfo>(
builder: (context, providerInfo, child),
I have a flutter app that uses scoped_model that works just fine but I want to refactor it so it'll use Provider
The code with scoped_model:
//imports...
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
final MainModel _model = MainModel();// The data class, extends scoped_model.Model class, with all of other models...
bool _isAuthenticated = false;
#override
void initState() {
_model.init();
super.initState();
}
#override
Widget build(BuildContext context) {
return ScopedModel<MainModel>(
model: _model,
child: MaterialApp(
title: "MyApp",
routes: {
'/': (BuildContext context) => _isAuthenticated == false ? AuthenticationPage() : HomePage(_model),
'/admin': (BuildContext context) =>
_isAuthenticated == false ? AuthenticationPage() : AdminPage(_model),
},
// the rest of build...
}
and the code that I tried to refactor to use Provider:
//#lib/main.dart
//imports...
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider<ProviderInfo>(
builder: (context) {
ProviderInfo(); // the data model.
},
child: Consumer<ProviderInfo>(
builder: (context, providerInfo, child) => MaterialApp(
title: "MyApp",
routes: {
'/': (BuildContext context) {
providerInfo.isAuthenticated == false ? AuthenticationPage() : HomePage(providerInfo);
},
'/admin': (BuildContext context) {
providerInfo.isAuthenticated == false ? AuthenticationPage() : AdminPage(_model);
},
//the rest of build...
},
//#ProviderInfo
class ProviderInfo extends CombinedModel with ProductModel, UserModel, UtilityModel {
ProviderInfo() {
this.init();
}
}
The problem with this code is that in the builder function of Consumer<ProviderInfo> the providerInfo is null (and also after of course, in routes etc...).
what did I do wrong?
how can I refactor it so it'll works fine?
You forgot to return something in the builder of your provider.
Change
ProviderInfo()
To
return ProviderInfo()

How to open a specific screen with quick_actions official plugin in flutter?

I implemented the Quick_actions plugin in my project and i want to open a specific screen but in the quickaction handler function the navigator doesnt work. whit a Try-Catch, the exception shows that the context showld be from a navigator, but im using the context of the navigatorKey of my MaterialApp.
if i put any other function like a print('some text') it works, the problem only happend when I try to use the navigator
Create the quick actions and add the handler function
createQuickActions() {
quickActions.initialize(
(String shortcutId) {
switch (shortcutId) {
case 'settings':
try {
Navigator.push(
MyApp.navigatorKey.currentContext,
MaterialPageRoute(
builder: (context) => SettingsScreen(sistemas),
),
);
} catch (e) {
print(e);
}
print('selected: $shortcutId');
break;
}
}
);
}
Initialice the quick actions
quickActions.setShortcutItems(
<ShortcutItem>[
const ShortcutItem(
type: 'settings',
localizedTitle: 'settings',
icon: 'settings',
),
],
);
All this code its in my SplashScreen because the plugin's documentation says that should be in an early state of the app
I expect that the app open the settings screen and print 'settings' but it opens the main screen and print 'settings' if the app its already open, but if its not it tries to open something and then close itself (not force close message)
In the following example,
Use MainView in quick action will open Login widget and directly click app will open Home widget
You can reference https://www.filledstacks.com/snippet/managing-quick-actions-in-flutter/ for detail
full code
import 'package:flutter/material.dart';
import 'package:quick_actions/quick_actions.dart';
import 'dart:io';
class QuickActionsManager extends StatefulWidget {
final Widget child;
QuickActionsManager({Key key, this.child}) : super(key: key);
_QuickActionsManagerState createState() => _QuickActionsManagerState();
}
class _QuickActionsManagerState extends State<QuickActionsManager> {
final QuickActions quickActions = QuickActions();
#override
void initState() {
super.initState();
_setupQuickActions();
_handleQuickActions();
}
#override
Widget build(BuildContext context) {
return widget.child;
}
void _setupQuickActions() {
quickActions.setShortcutItems(<ShortcutItem>[
ShortcutItem(
type: 'action_main',
localizedTitle: 'Main view',
icon: Platform.isAndroid ? 'quick_box' : 'QuickBox'),
ShortcutItem(
type: 'action_help',
localizedTitle: 'Help',
icon: Platform.isAndroid ? 'quick_heart' : 'QuickHeart')
]);
}
void _handleQuickActions() {
quickActions.initialize((shortcutType) {
if (shortcutType == 'action_main') {
Navigator.push(
context, MaterialPageRoute(builder: (context) => Login()));
} else if(shortcutType == 'action_help') {
print('Show the help dialog!');
}
});
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'QuickActions Demo', home: QuickActionsManager(child: Home()));
}
}
class Home extends StatelessWidget {
const Home({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text('Home')));
}
}
class Login extends StatelessWidget {
const Login({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text('Login')));
}
}

how to send data through different classes in different screens in flutter

i was struck here while making an application my code went like this
void main() {
runApp(Myapp());
}
class Myapp extends StatelessWidget {
bool s=false;
#override
Widget build(BuildContext context) {
return (MaterialApp(
debugShowCheckedModeBanner: false,
title: "haha app",
theme: ThemeData(primarySwatch: Colors.lime),
home: s ? HomeScreen(null) : LoginPage()));
}
}
the above code is of main.dart file
and this is my another file called Login.dart and the code goes like this
class LoginPage extends StatefulWidget {
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
Widget build(BuildContext context) {
return(some button ontap:(\\ on tap on this i have to change the bool s value in main.dart to true how to do that){
}
)
}
on tap the button the value s in main dart file should change to true but without navigator because we are not navigating here just a click.
please help me,
thanks in advance
You can use callbacks to communicate your widgets, like this
Create a method to get the callback , in this case : onChangeBool , pass the callback to your LoginPage Widget.
class Myapp extends StatelessWidget {
bool s=false;
onChangeBool(){
//change your var here
s = true;
//refresh the state
setState(() {
});
}
#override
Widget build(BuildContext context) {
return (MaterialApp(
debugShowCheckedModeBanner: false,
title: "haha app",
theme: ThemeData(primarySwatch: Colors.lime),
home: s ? HomeScreen(null) : LoginPage(onPressed: () => onChangeBool() ));
}
}
Receive the callBack , and call it when you press the button
class LoginPage extends StatefulWidget {
final VoidCallback onPressed;
LoginPage({this.onPressed});
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
Widget build(BuildContext context) {
return RaisedButton(
child: Text("button"),
onPressed: (){
widget.onPressed();
},
)
}
)
}
In case you want to pass Data, you can use ValueChanged callback , or if you want to pass complex data, create your own callback using typedef/
A sample using ValueChanged.
class Myapp extends StatelessWidget {
bool s=false;
receiveData(String data){
print("your text here : $data");
}
#override
Widget build(BuildContext context) {
return (MaterialApp(
debugShowCheckedModeBanner: false,
title: "haha app",
theme: ThemeData(primarySwatch: Colors.lime),
home: s ? HomeScreen(null) : LoginPage(onPressed: receiveData ));
}
}
class LoginPage extends StatefulWidget {
final ValueChanged<String> onPressed;
LoginPage({this.onPressed});
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
Widget build(BuildContext context) {
return RaisedButton(
child: Text("button"),
onPressed: (){
widget.onPressed("passing this data");
},
)
}
)
}

Remote Config Device Language Changes in Flutter

I am encountering a problem, where localization works fine, but the applications needs to be restarted in order for the changes to propagate.
Orientation changes
I know about OrientationBuilder, which will call its builder whenever it detects a change in the device's orientation, which in e.g. Android would be considered as a configuration change, just like device language changes.
Language changes
Is there something like LanguageBuilder? I could not find anything on my own and not on flutter.io nor on pub. I have read this tutorial and know about Locale, but I do not see a Stream for Locale.
My problem is that changing the language in iOS and Android native is really smooth. It gets handled automatically and perfectly integrates with services like Firebase Remote Config.
I really wonder if there is some method that will allow me to refresh my localization.
Question
So I am asking how I can refresh my Remote Config when the device language changes.
No there's no Builder for Locale.
Instead, there's an InheritedWidget which you can subscribe to using Localizations.of.
Since it is an InheritedWidget, all widgets that call Localizations.of will automatically refresh on locale change.
EDIT :
A example on how to live reload text using Flutter Locale system :
Let's assume you have the following class that holds translations :
class MyData {
String title;
MyData({this.title});
}
You'd then have a LocalizationsDelegate that contains such data. A dumb implementation would be the following :
class MyLocale extends LocalizationsDelegate<MyData> {
MyData data;
MyLocale(this.data);
#override
bool isSupported(Locale locale) {
return true;
}
#override
Future<MyData> load(Locale locale) async {
return data;
}
#override
bool shouldReload(MyLocale old) {
return old.data != data;
}
}
To use it simply pass it to MaterialApp.localizationsDelegates (be sure to add flutter_localizations to your pubspec.yaml) :
LocalizationsDelegate myLocale = MyLocale(MyData(title: "Foo"));
...
MaterialApp(
localizationsDelegates: [
myLocale,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
);
You can then freely live reload your translations by replacing myLocale with a new MyLocale instance.
Here's a full example of a click counter app. But where the current count is instead stored inside Locale (because why not ?)
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
class MyCount {
String count;
MyCount({this.count});
}
class MyCountLocale extends LocalizationsDelegate<MyCount> {
MyCount data;
MyCountLocale(this.data);
#override
bool isSupported(Locale locale) {
return true;
}
#override
Future<MyCount> load(Locale locale) async {
return data;
}
#override
bool shouldReload(MyCountLocale old) {
return old.data != data;
}
}
Future<void> main() async {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
ValueNotifier<int> count = ValueNotifier<int>(0);
LocalizationsDelegate myLocale;
#override
void initState() {
count.addListener(() {
setState(() {
myLocale = MyCountLocale(MyCount(count: count.value.toString()));
});
});
myLocale = MyCountLocale(MyCount(count: count.value.toString()));
super.initState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [
myLocale,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
home: MyHomePage(count: count),
);
}
}
class MyHomePage extends StatefulWidget {
final ValueNotifier<int> count;
MyHomePage({this.count});
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
primary: true,
appBar: AppBar(),
body: Column(
children: <Widget>[
FloatingActionButton(
onPressed: () => widget.count.value++,
child: Icon(Icons.plus_one),
),
ListTile(
title: Text(Localizations.of<MyCount>(context, MyCount).count),
),
],
),
);
}
}
Device language changes can be detected using a WidgetsBindingObserver.
It is the simplest to use it with a StatefulWidget in your State (with WidgetsBindingObserver):
class _MyWidgetState extends State<MyWidget> with WidgetsBindingObserver {
#override
void didChangeLocales(List<Locale> locale) {
// The device language was changed when this is called.
}
#override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
#override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
...
}
This means that you can now reload your RemoteConfig in didChangeLocales:
#override
void didChangeLocales(List<Locale> locale) {
_updateRemoteConfig();
}
Future<void> _updateRemoteConfig() async {
final remoteConfig = await RemoteConfig.instance;
await remoteConfig.activateFetched(); // This will apply the new locale.
}

Resources