Unable to access fetched data in initState in Flutter - api

I have class named Cards that has a method getCards that returns back a Future. I use this method to get cards from an endpoint.
Cards:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
class Cards {
String _accessToken;
String _refreshToken;
List<dynamic> cardsId = List();
Future<dynamic> getCards() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
_accessToken = sharedPreferences.getString("access");
_refreshToken = sharedPreferences.getString("refresh");
var jsonData;
var response = await sendRequestToGetCards(
url: "http://10.0.2.2:8000/accounts/list/", accessToken: _accessToken);
if (response.statusCode == 200) {
jsonData = json.decode(utf8.decode(response.bodyBytes));
return jsonData;
} else if (response.statusCode == 401) {
_accessToken = await getNewAccessToken(_refreshToken);
response = await sendRequestToGetCards(
url: "http://10.0.2.2:8000/accounts/list/",
accessToken: _accessToken);
if (response.statusCode == 200) {
jsonData = json.decode(utf8.decode(response.bodyBytes));
return jsonData;
}
}
}
getNewAccessToken(String refreshToken) async {
var refreshResponse = await http.post(
"http://10.0.2.2:8000/users/api/token/refresh/",
body: {'refresh': refreshToken});
if (refreshResponse.statusCode == 200) {
var jsonData = json.decode(refreshResponse.body);
return jsonData['access'];
}
}
sendRequestToGetCards({String url, String accessToken}) async {
var response = await http.get(
url,
headers: {"Authorization": "Bearer $accessToken"},
);
return response;
}
}
I have an other class called CardData as my Provider data/state:
import 'package:flutter/material.dart';
import '../cards/cards.dart';
class CardData extends ChangeNotifier {
static Cards cards = Cards();
Future<dynamic> cardsList = cards.getCards;
}
Which you can see I created an object from Cards to access getCards that makes me able to access the returned Future and saving it in cardsList.
Now in my widget that I used to display all the cards I created a method called addToList to access the Provider data.
I've created some lists to save Widgets to pass them to other Widget later.
List<Widget> cardsList = List();
List<dynamic> cardsId = List();
List<Widget> nonCards = List();
List<dynamic> nonCardsId = List();
addToList() async {
var jsonData = await Provider.of<CardData>(context).cardsList;
for (var i = 0, len = jsonData.length; i < len; i++) {
if(jsonData[i]['account_type'] == "1") {
cardsList.add(
BankCard(
bankName: jsonData[i]['title'],
colors: [Color(0xFFD00E00), Color(0xFFF44336)],
cardNumber: jsonData[i]['number'],
cardDesc: jsonData[i]['description'],
),
);
cardsId.add(jsonData[i]['id']);
} else if(jsonData[i]['account_type'] == "2") {
nonCards.add(
NonBankCard(
bankName: jsonData[i]['title'],
colors: [Color(0xFFFF4B2B), Color(0xFFFDB76C)],
),
);
nonCardsId.add(jsonData[i]['id']);
}
}
}
But I need to use addToList method in initState as you know but I can't. when I do use it there the app screen will disappears.

you should initialize your list at the beginning
List<Widget> cardsList = new List<Widget>();
Call addToList inside your initState function:
#override
void initState() {
addToList();
}
at the end of addToList() put the updated list in setState()
setState(() {
cardsList = List.from(cardsList);
});

Related

Flutter : method call on null when using shared preference

I want to use shared preference to keep user login and i'm using api with provider .
i tried to put it in main but i don't how to do it because i have two different page to go so i was used it in the first page but i found another error
[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception:
NoSuchMethodError: The method 'login' was called on null. E/flutter (
4199): Receiver: null
and this is the method which i used
UserProvider userProvider;
ServiceProvider serviceProvider;
bool alive = true;
bool isLoading = false;
var page;
#override
initState() {
init();
super.initState();
}
init() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool language = prefs.getBool('language');
bool type = prefs.getBool('type');
bool login = prefs.getBool('islog');
if (alive) {
if (language == true && type == true && login == true) {
signIn();
} else if ((language == true && type == false && login == true)) {
visitor();
}
} else {
if (alive) {
setState(() {
isLoading = false;
});
}
}
}
signIn() async {
//var res = await userProvider.residentLogin(context, phone, pass);
SharedPreferences prefs = await SharedPreferences.getInstance();
var phone = prefs.getString('phone');
String pass = prefs.getString("pass");
bool type = prefs.getBool('type');
print("Shared ***************resident********************************");
await userProvider.residentLogin(context, phone, pass);
await serviceProvider.getHomeServiceList(context);
await serviceProvider.getAdsList(context);
await serviceProvider.getVideosList(context);
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => ResidentBottomTab()));
print('Hello Tourist !!');
}
visitor() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var phone = prefs.getString('phone');
String pass = prefs.getString("pass");
await userProvider.login(context, phone, pass);
await serviceProvider.getVisitorAdsList(context);
await serviceProvider.getVisitorVideosList(context);
bool type = prefs.getBool('type');
print("Shared ******************visitor*****************************");
if (alive) {
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => VisitorHome()));
print('Hello Tourist !!');
}
}
#override
void dispose() {
alive = false;
super.dispose();
}
login method
Future<VisitorLoginModel> login(BuildContext context, phone, pass) async {
final Map<String, dynamic> body = {
'phone': phone,
'password': pass,
'token': '123',
'serial_number': '123',
'lang': 'en',
'os': 'android',
};
_isLoading = true;
notifyListeners();
print('Starting request');
http.Response response = await http.post(Environment.userLogin,
body: json.encode(body), headers: Environment.requestHeader);
print('Completed request');
print('user SignUp response : ${response.body}');
//print(body.toString());
Map<String, dynamic> res = json.decode(response.body);
var results;
if (res['status'] == 1) {
// login successful
_visitorLoginModel = parseVisitorLogin(response.body);
Provider.of<LoginVisitorUserProvider>(context, listen: false).userData =
visitorLoginModel;
Provider.of<LoginVisitorUserProvider>(context, listen: false)
.sessionToken = visitorLoginModel.data.token;
headers = Provider.of<LoginVisitorUserProvider>(context, listen: false)
.httpHeader;
// print('token');
print('this is session token' +
Provider.of<LoginVisitorUserProvider>(context, listen: false)
.sessionToken);
} else {
// login failed;
results =
FailedRequest(code: 401, message: res['massage'], status: false);
}
_isLoading = false;
notifyListeners();
return visitorLoginModel;
}
so anyone has an idea to solve this case !
The method call await userProvider.login(context, phone, pass); is being done on a non initialized variable. UserProvider userProvider; has been declared but not initialized
The issue here is the userProvider is being declared but not initialized and the same goes for serviceProvider
In Flutter any uninitialized variable will implicitly assigned with null
So, at the line await userProvider.login(context, phone, pass); where you call login method in which userProvider is not only initialized
To Solve the issue do the following,
In initState,
userProvider = Provider.of<UserProvider>(context, listen: false);

How to setup a base URL and where do I declare it in flutter dio for api calls?

like how to fix boilerplate code in separate file and use it in ui pages.
I Need to declare this uri variable in separate file and access across over all pages:
static var uri = "https://xxx/xxx/web_api/public";
static BaseOptions options = BaseOptions(
baseUrl: uri,
responseType: ResponseType.plain,
connectTimeout: 30000,
receiveTimeout: 30000,
// ignore: missing_return
validateStatus: (code) {
if (code >= 200) {
return true;
}
}); static Dio dio = Dio(options);
In UI page i have to declare that uri variable and BaseOption variable in this future function:
Future<dynamic> _loginUser(String email, String password) async {
try {
Options options = Options(
headers: {"Content-Type": "application/json"},
);
Response response = await dio.post('/login',
data: {
"email": email,
"password": password,
"user_type": 2,
"status": 1
},
options: options);
if (response.statusCode == 200 || response.statusCode == 201) {
var responseJson = json.decode(response.data);
return responseJson;
} else if (response.statusCode == 401) {
throw Exception("Incorrect Email/Password");
} else
throw Exception('Authentication Error');
} on DioError catch (exception) {
if (exception == null ||
exception.toString().contains('SocketException')) {
throw Exception("Network Error");
} else if (exception.type == DioErrorType.RECEIVE_TIMEOUT ||
exception.type == DioErrorType.CONNECT_TIMEOUT) {
throw Exception(
"Could'nt connect, please ensure you have a stable network.");
} else {
return null;
}
}
}
You can create app_config.dart file and manage different environments like below:
const _baseUrl = "baseUrl";
enum Environment { dev, stage, prod }
Map<String, dynamic> _config;
void setEnvironment(Environment env) {
switch (env) {
case Environment.dev:
_config = devConstants;
break;
case Environment.stage:
_config = stageConstants;
break;
case Environment.prod:
_config = prodConstants;
break;
}
}
dynamic get apiBaseUrl {
return _config[_baseUrl];
}
Map<String, dynamic> devConstants = {
_baseUrl: "https://devapi.xyz.com/",
};
Map<String, dynamic> stageConstants = {
_baseUrl: "https://api.stage.com/",
};
Map<String, dynamic> prodConstants = {
_baseUrl: "https://api.production.com/",
};
Maybe instead of statically declaring your Dio object you could put it in a class, also put your loginUser function in there, and use Provider to obtain that object to call it where you need it.
class Api {
static var uri = "https://xxx/xxx/web_api/public";
static BaseOptions options = BaseOptions(
baseUrl: uri,
responseType: ResponseType.plain,
connectTimeout: 30000,
receiveTimeout: 30000,
// ignore: missing_return
validateStatus: (code) {
if (code >= 200) {
return true;
}
});
Dio dio = Dio(options);
Future<dynamic> loginUser(String email, String password) async {
try {
RequestOptions options = RequestOptions(
headers: {"Content-Type": "application/json"},
);
Response response = await dio.post('/login',
data: {
"email": email,
"password": password,
"user_type": 2,
"status": 1
},
options: options);
//the rest of your code here
}
https://pub.dev/packages/provider
Provider(
create: (_) => Api(),
child: ...
)
https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html
YourWidget(
child: Consumer<Api>(
builder: (context, api, child) {
return FutureBuilder<dynamic>(
future: api.loginUser('mail#mail.com', 'user_password')
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (snapshot.hasData) {
//show a widget based on snapshot.data
} else {
//show another widget
}
}
},
),
)

Flutter - How to add Multipi API data source?

I have 2 API with the same data but different link, Sometime one of them isn't working so I want to try to get data from first one if it's not working so get data from the second (as a backup data source )
Can any one help me to do this ?
Thanks in advance.
import 'package:http/http.dart';
import 'dart:convert';
class MyWorking {
Future getData() async {
String data;
Response response = await get(
'first Url');
if (response.statusCode == 200) {
data = response.body;
print(data);
return jsonDecode(data);
} else {
print(response.statusCode);
}
}
}
I tried this and it worked but as you can see the second url in if statement so is their away to but it under the first url ?
import 'package:http/http.dart';
import 'dart:convert';
class MyWorking {
Future getData() async {
String data;
Response response = await get('first URL');
if (response.statusCode == 200) {
data = response.body;
return jsonDecode(data);
} else if (response.statusCode != 200) {
response = await get('second URL');
data = response.body;
return jsonDecode(data);
} else {
print(response.statusCode);
}
}
}
try this:
Future getData(int index) async { //changed this line
List<String> data = ['first url','second url']; //changed this line
Response response = await get(data[index]);
if (response.statusCode == 200) {
data = response.body;
print(data);
return jsonDecode(data);
} else {
print(response.statusCode);
index == 0 ? getData(1):getData(0); //add this line
}
}

How to call an async method in initState in flutter

I need to get some information from an endpoint. I have this method:
List<Widget> cardsList = List();
List<dynamic> cardsId = List();
addToList() async {
var jsonData = await Provider.of<CardData>(context).cardsList;
print(jsonData);
for (var i = 0, len = jsonData.length; i < len; i++) {
if (jsonData[i]['account_type'] == "1") {
cardsList.add(
BankCard(
bankName: jsonData[i]['title'],
colors: [Color(0xFFD00E00), Color(0xFFF44336)],
cardNumber: jsonData[i]['number'],
cardDesc: jsonData[i]['description'],
),
);
cardsId.add(jsonData[i]['id']);
}
}
}
and a class as provider data called CardData:
import 'package:flutter/material.dart';
import '../cards/cards.dart';
class CardData extends ChangeNotifier {
static Cards cards = Cards();
Future<dynamic> cardsList = cards.getCards();
}
and a class called Card to send request and doing all other stuff:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
class Cards {
String _accessToken;
String _refreshToken;
Future<dynamic> getCards() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
_accessToken = sharedPreferences.getString("access");
_refreshToken = sharedPreferences.getString("refresh");
var jsonData;
var response = await sendRequestToGetCards(
url: "http://10.0.2.2:8000/accounts/list/", accessToken: _accessToken);
if (response.statusCode == 200) {
jsonData = json.decode(utf8.decode(response.bodyBytes));
return jsonData;
} else if (response.statusCode == 401) {
_accessToken = await getNewAccessToken(_refreshToken);
response = await sendRequestToGetCards(
url: "http://10.0.2.2:8000/accounts/list/",
accessToken: _accessToken);
if (response.statusCode == 200) {
jsonData = json.decode(utf8.decode(response.bodyBytes));
return jsonData;
}
}
}
getNewAccessToken(String refreshToken) async {
var refreshResponse = await http.post(
"http://10.0.2.2:8000/users/api/token/refresh/",
body: {'refresh': refreshToken});
if (refreshResponse.statusCode == 200) {
var jsonData = json.decode(refreshResponse.body);
return jsonData['access'];
}
}
sendRequestToGetCards({String url, String accessToken}) async {
var response = await http.get(
url,
headers: {"Authorization": "Bearer $accessToken"},
);
return response;
}
}
But when I call addToList method in initState to retrieve data before build method, the main UI disappears.
What's wrong with it?
You can call async function in the initState, but as it itself is not an async function it will not wait for futures to complete before moving on to the build method, which is why your UI disappears because it is building with no data so there are no cards. I would suggest using a FutureBuilder in your build method to build when the async function returns.

KnockoutJS + WebAPI 2 Token Authentication - maintain login state until token expires

I'm fairly new to token based authentication and I have a problem of how to maintain login state after I login.
I want to create a SPA website for which I am using Knockoutjs for my front end and SammyJS for routing and changing the views.
After I login in and get the token I store it in localStorage and set the username into an observable which I am displaying.
My problem is that after I close the tab or browser and I go back to the site, the token is in the localStorage but I can't see the user logged in.
I want to maintain the login state until the token expires. My question is what should I do with the token from the localStorage when I enter the site in order to maintain the login state of that user?
Do I need to make something in the startup class or to check if that user exists in the DB?
Thanks in advance!
Here is my code:
StartupAuth.cs
[assembly: OwinStartup(typeof(EventHub.PL.WebUI.Startup))] namespace EventHub.PL.WebUI {
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get;private set; }
public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
public const string TokenEndpointPath = "/api/token";
public static string PublicClientId { get; private set; }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString(TokenEndpointPath),
Provider = new ApplicationOAuthProvider(PublicClientId),
//AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
//app.UseOAuthBearerTokens( OAuthOptions );
app.UseOAuthAuthorizationServer(OAuthOptions);
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
}
}
AccountController.cs
[HttpPost]
[AllowAnonymous]
[Route("Login")]
public async Task<IHttpActionResult> Login(LoginUser model)
{
var request = HttpContext.Current.Request;
var tokenServiceUrl = request.Url.GetLeftPart(UriPartial.Authority) + request.ApplicationPath + "/api/Token";
using (var client = new HttpClient())
{
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", model.Email),
new KeyValuePair<string, string>("password", model.Password)
};
var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams);
var tokenServiceResponse = await client.PostAsync(tokenServiceUrl, requestParamsFormUrlEncoded);
var responseString = await tokenServiceResponse.Content.ReadAsStringAsync();
var json = JsonConvert.DeserializeObject<TokenResponse>(responseString);
var responseCode = tokenServiceResponse.StatusCode;
if (responseCode == HttpStatusCode.OK)
{
RegisterUser user = userRepository.GetNameById(json.Id);
var data = new
{
status = "success",
json.access_token,
user.Lastname
};
return Json(data);
}
return Json(new { status = "failed" });
}
}
here is the KO part:
var LoginApp = function () {
var instance = this;
instance.mainViewModel = new MainViewModel();
instance.loginViewModel = new LoginViewModel();
instance.loginRepository = new LoginRepository();
instance.loginViewModel.signIn = function() {
$('.loader-header').show();
var postData = {
email: instance.loginViewModel.email(),
password: instance.loginViewModel.password
}
instance.loginRepository.SignIn(SignInSuccess, postData);
};
instance.SignInSuccess = function(response) {
if (response.status === 'success') {
instance.mainViewModel.username(response.Lastname);
instance.mainViewModel.isVisible(true);
var userData = {
token: response.access_token,
username: response.Lastname
};
localStorage.setItem('AuthorizationData', JSON.stringify(userData));
$('.loader-header').hide();
dialog.close();
} else {
$('.loader-header').hide();
}
};
instance.init = function () {
ko.applyBindings(instance.loginViewModel, document.getElementById("signin-form"));
ko.applyBindings(instance.mainViewModel, document.getElementById("main-wrapper"));
}
instance.init();
}
$(document).ready(function () {
var loginApp = LoginApp();
});
UPDATE
here is my routing also
var appRoot = root;
(function ($) {
var app = $.sammy('#page', function () {
this.get('#/home', function (context) {
document.title = 'Home - ' + title;
var url = getUrlFromHash(context.path);
loadView(url, new MainViewModel(), MainApp);
//context.load(url).swap();
});
this.get('#/about', function (context) {
var url = getUrlFromHash(context.path);
loadView(url, new AboutViewModel(), AboutApp);
});
this.get('#/manage', function (context) {
var url = getUrlFromHash(context.path);
loadView(url, new AboutViewModel(), AboutApp);
});
});
$(function () {
app.run('#/home');
});
})(jQuery);
function loadView(url, viewModel, callback) {
$.get(url, function (response) {
var $container = $('#page');
//var $view = $('#page').html(response);
$container.html(response);
callback();
});
}
function getUrlFromHash(hash) {
var url = hash.replace('#/', '');
if (url === appRoot)
url = 'home';
return url;
}
Right now all you're doing is storing the user's credentials in localStorage but not using them to perform authorization. One alternative is to use the Sammy.OAuth2 plugin (which you can find it here).
You can define a route to make the authentication like:
app.post("#/oauth/login", function(context) {
this.load('http://yourwebsite/login',
{
cache: false,
type: 'post',
data: {
email: $("input[name=email]").val(),
password: $("input[name=password]").val()
}
})
.then(function(content) {
if(content != false){
if(app.getAccessToken() == null){
app.setAccessToken(token());
}
}else{
app.trigger("oauth.denied");
return false;
}
});
});
In 'protected' routes you can check if the user is already logged in like this:
app.get("#/profile", function(context) {
if(app.getAccessToken() != null)
context.render('view/profile.template');
else
this.requireOAuth();
});
This examples will have to be modified to populate the token according to your scenario. Here's a complete tutorial on Sammy.Oath2.