How to navigate different page after async method return response - dart

I have a screen App in which i have onGenerateRoute property of MaterialApp. In the routes method i make an api call and once i get the response i want to let user navigate to login screen
I tried calling my widget Login inside .then() function
class App extends StatelessWidget {
Widget build(BuildContext context) {
return AppBlocProvider(
child: LoginBlocProvider(
child: MaterialApp(
onGenerateRoute: routes,
),
),
);
}
Route routes(RouteSettings settings) {
print(settings.name);
switch (settings.name) {
case '/':
return MaterialPageRoute(builder: (context) {
//HERE I AM MAKING API CALL
final appBloc = AppBlocProvider.of(context);
appBloc.verifyUser().then((response) {
//HERE ONCE I GET THE RESPONSE I WANT TO NAVIGATE USER TO
//lOGIN ACTIVITY
print('called');
return Login();
});
return AppBlocProvider(
child: Center(child: CircularProgressIndicator()),
);
});
break;
case '/Login':
return MaterialPageRoute(builder: (BuildContext context) {
return Login();
});
break;
case '/HomeScreen':
return MaterialPageRoute(builder: (BuildContext context) {
return Home();
});
break;
}
return MaterialPageRoute(builder: (context) {
print('returned null');
});
}
api call get successful and even .then() method executes but login screen doesn't appear

The reason return Login(); doesn't do anything was because another return has been executed already: return AppBlocProvider(child: Widget());
Similar to this sample, since a return has been already made, the other return won't do anything. The sample prints 'bar', and 'foo' was never printed using print(bar());.
void main() {
print(bar());
}
Future<String> foo() async{
await Future.delayed(Duration(seconds: 5));
return 'foo';
}
String bar(){
String txt = 'bar';
foo().then((String value){
print('Future finished: $value');
// Since print already got a String return,
// returning this value won't do anything
return value; // 'foo' won't be printed on main()
});
return txt;
}
You may want to consider moving the navigation inside Login and also display CircularProgressIndicator() there.

Related

Flutter set startup page based on Shared Preference

I've been trying without success to load different pages according to my Shared Preference settings.
Based on several posts found in stackoverflow, i end up with the following solution:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:testing/screens/login.dart';
import 'package:testing/screens/home.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Widget page = Login();
Future getSharedPrefs() async {
String user = Preferences.local.getString('user');
if (user != null) {
print(user);
this.page = Home();
}
}
#override
void initState() {
super.initState();
this.getSharedPrefs();
}
#override
Widget build(BuildContext context) {
return MaterialApp(home: this.page);
}
}
class Preferences {
static SharedPreferences local;
/// Initializes the Shared Preferences and sets the info towards a global variable
static Future init() async {
local = await SharedPreferences.getInstance();
}
}
The variable user is not null because the print(user) returns a value as expected, but the login screen is always being opened.
Your problem is that your build method returns before your getSharedPrefs future is complete. The getSharedPrefs returns instantly as soon as it's called because it's async and you're treating it as a "Fire and Forget" by not awaiting. Seeing that you can't await in your initState function that makes sense.
This is where you want to use the FutureBuilder widget. Create a Future that returns a boolean (or enum if you want more states) and use a future builder as your home child to return the correct widget.
Create your future
Future<bool> showLoginPage() async {
var sharedPreferences = await SharedPreferences.getInstance();
// sharedPreferences.setString('user', 'hasuser');
String user = sharedPreferences.getString('user');
return user == null;
}
When user is null this will return true. Use this future in a Future builder to listen to the value changes and respond accordingly.
#override
Widget build(BuildContext context) {
return MaterialApp(home: FutureBuilder<bool>(
future: showLoginPage(),
builder: (buildContext, snapshot) {
if(snapshot.hasData) {
if(snapshot.data){
// Return your login here
return Container(color: Colors.blue);
}
// Return your home here
return Container(color: Colors.red);
} else {
// Return loading screen while reading preferences
return Center(child: CircularProgressIndicator());
}
},
));
}
I ran this code and it works fine. You should see a blue screen when login is required and a red screen when there's a user present. Uncomment the line in showLoginPage to test.
There is a much pretty way of doing this.
Assuming that you have some routes and a boolean SharedPreference key called initialized.
You need to use the WidgetsFlutterBinding.ensureInitialized() function before calling runApp() method.
void main() async {
var mapp;
var routes = <String, WidgetBuilder>{
'/initialize': (BuildContext context) => Initialize(),
'/register': (BuildContext context) => Register(),
'/home': (BuildContext context) => Home(),
};
print("Initializing.");
WidgetsFlutterBinding.ensureInitialized();
await SharedPreferencesClass.restore("initialized").then((value) {
if (value) {
mapp = MaterialApp(
debugShowCheckedModeBanner: false,
title: 'AppName',
theme: ThemeData(
primarySwatch: Colors.blue,
),
routes: routes,
home: Home(),
);
} else {
mapp = MaterialApp(
debugShowCheckedModeBanner: false,
title: 'AppName',
theme: ThemeData(
primarySwatch: Colors.blue,
),
routes: routes,
home: Initialize(),
);
}
});
print("Done.");
runApp(mapp);
}
The SharedPreference Class Code :
class SharedPreferencesClass {
static Future restore(String key) async {
final SharedPreferences sharedPrefs = await SharedPreferences.getInstance();
return (sharedPrefs.get(key) ?? false);
}
static save(String key, dynamic value) async {
final SharedPreferences sharedPrefs = await SharedPreferences.getInstance();
if (value is bool) {
sharedPrefs.setBool(key, value);
} else if (value is String) {
sharedPrefs.setString(key, value);
} else if (value is int) {
sharedPrefs.setInt(key, value);
} else if (value is double) {
sharedPrefs.setDouble(key, value);
} else if (value is List<String>) {
sharedPrefs.setStringList(key, value);
}
}
}

Flutter How to make it automatically - (navigate to login) when http status code is 401

Here is my previous codes.
class mainScreen extends StatefulWidget
{
Api api = new Api();
override
Widget build(BuildContext context) {
return new MaterialButton(
onPressed: () async{
new Future.then(
api.doSthA(),onError: (e) {
Navigator.of(context).pushNamed("/login"); //this is repeat
})
new Future.then(
api.doSthB(),onError: (e) {
Navigator.of(context).pushNamed("/login"); //this is repeat
}
)
}
);
}
}
class Api
{
Future<dynamic> doSthA() async{
return http
.post(
"url"
)
.then((http.Response res) {
if(res.body.statusCode == 401){
throw new Exception("401");
}else{
return _decoder.convert(res);
}
}
}
Future<dynamic> doSthB() async{
similar with doSthA
}
}
I want it simplify to
new MaterialButton(
onPressed: () async{
new Future.then(api.doSthA())...
new Future.then(api.doSthB())...
}
auto execute Navigator to login when api return 401.
Because Navigator must need widget's content.so I have no idea how to let it integrate with Api class.I want make Navigator be part of Api manager.
Try this when you want to navigate to login
Navigator.pushNamedAndRemoveUntil(
context,
'/login', (_) => false);
Put this in build method
Api api = Api(context: context)
Api class
class Api
{
BuildContext context;
Api({this.context});
}
ApiCall Method
if(res.statusCode == 401){
Navigator.pushNamedAndRemoveUntil(
context,
'/login', (_) => false);
return null;
}

Using SharedPreferences to set login state and retrieving it at App launch - Flutter

I have an flutter app in which I have to check the login status when the app is launched and call the relevant screen accordingly.
The code used to launch the app:
class MyApp extends StatefulWidget {
#override
MyAppState createState() {
return new MyAppState();
}
}
class MyAppState extends State<MyApp> {
bool isLoggedIn;
Future<bool> getLoginState() async{
SharedPreferences pf = await SharedPreferences.getInstance();
bool loginState = pf.getBool('loginState');
return loginState;
// return pf.commit();
}
#override
Widget build(BuildContext context) {
getLoginState().then((isAuth){
this.isLoggedIn = isAuth;
});
if(this.isLoggedIn) {return Container(child: Text('Logged In'));}
else {return Container(child: Text('Not Logged In));}
}
}
I am able to save the SharedPreference and retrieve it here, the issue is that as getLoginState() is an async function, this.isLoggedIn is null by the time the if condition is executed. The boolean assertion fails in the if statement and the app crashes.
How do I ensure that the bool variable isLoggedIn used in the if condition has a value when the if statement is executed?
Any help would be appreciated.
You can use FutureBuilder to solve this problem.
#override
Widget build(BuildContext context) {
new FutureBuilder<String>(
future: getLoginState(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.active:
case ConnectionState.waiting:
return new Text('Loading...');
case ConnectionState.done:
if (snapshot.hasData) {
loginState = snapshot.data;
if(loginState) {
return Container(child: Text('Logged In'));
}
else {
return Container(child: Text('Not Logged In));
}
} else {
return Container(child: Text('Error..));
}
}
},
)
}
Note: we don't need isLoggedIn state variable.

Usage of FutureBuilder with setState

How to use the FutureBuilder with setState properly? For example, when i create a stateful widget its starting to load data (FutureBuilder) and then i should update the list with new data, so i use setState, but its starting to loop for infinity (because i rebuild the widget again), any solutions?
class FeedListState extends State<FeedList> {
Future<Null> updateList() async {
await widget.feeds.update();
setState(() {
widget.items = widget.feeds.getList();
});
//widget.items = widget.feeds.getList();
}
#override
Widget build(BuildContext context) {
return new FutureBuilder<Null>(
future: updateList(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Center(
child: new CircularProgressIndicator(),
);
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return new Scrollbar(
child: new RefreshIndicator(
child: ListView.builder(
physics:
const AlwaysScrollableScrollPhysics(), //Even if zero elements to update scroll
itemCount: widget.items.length,
itemBuilder: (context, index) {
return FeedListItem(widget.items[index]);
},
),
onRefresh: updateList,
),
);
}
},
);
}
}
Indeed, it will loop into infinity because whenever build is called, updateList is also called and returns a brand new future.
You have to keep your build pure. It should just read and combine variables and properties, but never cause any side effects!
Another note: All fields of your StatefulWidget subclass must be final (widget.items = ... is bad). The state that changes must be stored in the State object.
In this case you can store the result (the data for the list) in the future itself, there is no need for a separate field. It's even dangerous to call setState from a future, because the future might complete after the disposal of the state, and it will throw an error.
Here is some update code that takes into account all of these things:
class FeedListState extends State<FeedList> {
// no idea how you named your data class...
Future<List<ItemData>> _listFuture;
#override
void initState() {
super.initState();
// initial load
_listFuture = updateAndGetList();
}
void refreshList() {
// reload
setState(() {
_listFuture = updateAndGetList();
});
}
Future<List<ItemData>> updateAndGetList() async {
await widget.feeds.update();
// return the list here
return widget.feeds.getList();
}
#override
Widget build(BuildContext context) {
return new FutureBuilder<List<ItemData>>(
future: _listFuture,
builder: (BuildContext context, AsyncSnapshot<List<ItemData>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return new Center(
child: new CircularProgressIndicator(),
);
} else if (snapshot.hasError) {
return new Text('Error: ${snapshot.error}');
} else {
final items = snapshot.data ?? <ItemData>[]; // handle the case that data is null
return new Scrollbar(
child: new RefreshIndicator(
child: ListView.builder(
physics: const AlwaysScrollableScrollPhysics(), //Even if zero elements to update scroll
itemCount: items.length,
itemBuilder: (context, index) {
return FeedListItem(items[index]);
},
),
onRefresh: refreshList,
),
);
}
},
);
}
}
Use can SchedulerBinding for using setState() inside Future Builders or Stream Builder,
SchedulerBinding.instance
.addPostFrameCallback((_) => setState(() {
isServiceError = false;
isDataFetched = true;
}));
Screenshot (Null Safe):
Code:
You don't need setState while using FutureBuilder.
class MyPage extends StatefulWidget {
#override
State<MyPage> createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> {
// Declare a variable.
late final Future<int> _future;
#override
void initState() {
super.initState();
_future = _calculate(); // Assign your Future to it.
}
// This is your actual Future.
Future<int> _calculate() => Future.delayed(Duration(seconds: 3), () => 42);
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<int>(
future: _future, // Use your variable here (not the actual Future)
builder: (_, snapshot) {
if (snapshot.hasData) return Text('Value = ${snapshot.data!}');
return Text('Loading...');
},
),
);
}
}

Flutter Like button functionality using Futures

I'm trying to build a Save button that lets the user save/ unsave (like/ unlike) items displayed in a ListView.
What I have so far:
Repository that provides a Future<bool> that determines which state the icon should be rendered in
FutureBuilder that calls the repository and renders the icon as either saved/ unsaved.
Icon wrapped in a GestureDetector that makes a call to the repository within a setState call when onTap is invoked.
`
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: _repository.isSaved(item),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.none:
case ConnectionState.active:
return Icon(Icons.favorite_border);
case ConnectionState.done:
return GestureDetector(
child: Icon(
snapshot.data ? Icons.favorite : Icons.favorite_border,
color: snapshot.data ? Colors.red : null),
onTap: () {
setState(() {
if (snapshot.data) {
_repository.removeItem(item);
} else {
_repository.saveItem(item);
}
});
},
);
}
});
}
`
The issue I'm having is that when I tap to save an item in the list - the item is saved however the icon is not updated until I scroll it off screen then back on again.
When I tap to unsave an item, it's state is reflected immediately and updates as expected.
I suspect that the save call is taking longer to complete than the delete call. Both of these are async operations:
void removeItem(String item) async {
_databaseClient.deleteItem(item);
}
void saveItem(String item) async {
_databaseClient.saveItem(item);
}
#override
void deleteItem(String item) async {
var client = await db;
client.delete("items_table", where: "item = '$item'"); // returns Future<int> but I'm not using this currently
}
void _saveItem(String item) async {
var client = await db;
client.insert("items_table", item); // returns Future<int> but I'm not using this currently
}
Future<bool> isSaved(String name) async {
var matching = await _databaseClient.getNameByName(name);
return matching != null && matching.isNotEmpty;
}
Any idea what could be causing this?
When you tap the button, setState will be called. then FutureBuilder will wait for the isSaved method. if the save method is being in progress. isSaved will return the last state and Icon will not change.
I suggest to wait for the result of Save and Remove method and call setState after that.
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: _repository.isSaved(item),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.none:
case ConnectionState.active:
return Icon(Icons.favorite_border);
case ConnectionState.done:
return GestureDetector(
child: Icon(
snapshot.data ? Icons.favorite : Icons.favorite_border,
color: snapshot.data ? Colors.red : null),
onTap: () async{
if (snapshot.data) {
await _repository.removeItem(item);
} else {
await _repository.saveItem(item);
}
setState(() {
});
},
);
}
});
}
However, if the methods take so long, it delays which cause bad user experience. it better to change the icon to progress circle during running methods.

Resources