How do I deal with logins on different devices based on API response in flutter? - api

I'm confused about how to deal with multiple logins with different devices, and I want to give the function back to the login layout when there are other devices that have just logged in to the same user
Future<EventArticleList> getEventArticleList(String token) async {
BuildContext context;
Map<String, String> headers = {
"Accept": "application/json",
"Authorization": "Bearer $token"
};
var response = await client.get('$endpoint/', headers: headers);
if (response.statusCode == 200) {
print("Masuk Data");
return EventArticleList.fromJson(
json.decode(response.body),
);
} else if (response.statusCode == 401) {
print("401");
return Navigator.of(context)
.pushNamedAndRemoveUntil(RoutePaths.Login, (_) => false);
} else {
throw Exception("ini Eror apa ?");
}
}
the compilation appears I try to add the navigator back to status.code == 401
NoSuchMethodError: The method 'ancestorStateOfType' was called on null

Try this code
Your main class
import 'package:flutter/material.dart';
import 'package:flutterapitut/view/adddata.dart';
import 'package:flutterapitut/view/dashboard.dart';
import 'package:flutterapitut/view/login.dart';
import 'package:flutterapitut/view/register.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final String title='';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter CRUD API',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LoginPage(title: 'Flutter CRUD API'),
routes: <String,WidgetBuilder>{
'/dashboard' : (BuildContext context) => new Dashboard(title:title),
'/login' : (BuildContext context) => new LoginPage(title:title),
},
);
}
}
Your Database Helper class
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class DatabaseHelper{
String serverUrl = "http://flutterapitutorial.codeforiraq.org/api";
var status ;
var token ;
loginData(String email , String password) async{
String myUrl = "$serverUrl/login1";
final response = await http.post(myUrl,
headers: {
'Accept':'application/json'
},
body: {
"email": "$email",
"password" : "$password"
} ) ;
status = response.body.contains('error');
var data = json.decode(response.body);
if(status){
print('data : ${data["error"]}');
}else{
print('data : ${data["token"]}');
_save(data["token"]);
}
}
_save(String token) async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = token;
prefs.setString(key, value);
}
read() async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key ) ?? 0;
print('read : $value');
}
}
Your login class
import 'package:flutter/material.dart';
import 'package:flutterapitut/Controllers/databasehelper.dart';
import 'package:flutterapitut/view/dashboard.dart';
import 'package:flutterapitut/view/register.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LoginPage extends StatefulWidget{
LoginPage({Key key , this.title}) : super(key : key);
final String title;
#override
LoginPageState createState() => LoginPageState();
}
class LoginPageState extends State<LoginPage> {
read() async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key ) ?? 0;
if(value != '0'){
Navigator.of(context).push(
new MaterialPageRoute(
builder: (BuildContext context) => new Dashboard(),
)
);
}
}
#override
initState(){
read();
}
DatabaseHelper databaseHelper = new DatabaseHelper();
String msgStatus = '';
final TextEditingController _emailController = new TextEditingController();
final TextEditingController _passwordController = new TextEditingController();
_onPressed(){
setState(() {
if(_emailController.text.trim().toLowerCase().isNotEmpty &&
_passwordController.text.trim().isNotEmpty ){
databaseHelper.loginData(_emailController.text.trim().toLowerCase(),
_passwordController.text.trim()).whenComplete((){
if(databaseHelper.status){
_showDialog();
msgStatus = 'Check email or password';
}else{
Navigator.pushReplacementNamed(context, '/dashboard');
}
});
}
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Login',
home: Scaffold(
appBar: AppBar(
title: Text('Login'),
),
body: Container(
child: ListView(
padding: const EdgeInsets.only(top: 62,left: 12.0,right: 12.0,bottom: 12.0),
children: <Widget>[
Container(
height: 50,
child: new TextField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email',
hintText: 'Place your email',
icon: new Icon(Icons.email),
),
),
),
Container(
height: 50,
child: new TextField(
controller: _passwordController,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Password',
hintText: 'Place your password',
icon: new Icon(Icons.vpn_key),
),
),
),
new Padding(padding: new EdgeInsets.only(top: 44.0),),
Container(
height: 50,
child: new RaisedButton(
onPressed: _onPressed,
color: Colors.blue,
child: new Text(
'Login',
style: new TextStyle(
color: Colors.white,
backgroundColor: Colors.blue),),
),
),
new Padding(padding: new EdgeInsets.only(top: 44.0),),
Container(
height: 50,
child: new Text(
'$msgStatus',
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontWeight: FontWeight.bold),
),
),
new Padding(padding: new EdgeInsets.only(top: 44.0),),
Container(
height: 50,
child: new FlatButton(
onPressed: ()=>Navigator.of(context).push(
new MaterialPageRoute(
builder: (BuildContext context) => new RegisterPage(),
)
)
,
color: Colors.blue,
child: new Text(
'Register',
style: new TextStyle(
color: Colors.white,
),),
),
),
],
),
),
),
);
}
void _showDialog(){
showDialog(
context:context ,
builder:(BuildContext context){
return AlertDialog(
title: new Text('Failed'),
content: new Text('Check your email or password'),
actions: <Widget>[
new RaisedButton(
child: new Text(
'Close',
),
onPressed: (){
Navigator.of(context).pop();
},
),
],
);
}
);
}
}
Here Dashboard is the class you expected to navigate after successfully login
Want more code visite here I hope this work correctly

Related

How to show list item to another page

From the code below, when I create user(student) data It will show up as a list. Each student information will be shown by a ListTile widget. When I slide and press the completed button on the ListTile, I want my ListTile to show on the 'Completed' page list view. I am currently working with sqlite. I am having a hard time trying to figure this out.
main.dart
import 'package:flutter/material.dart';
import '../database/db.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:crypto/crypto.dart';
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return (MaterialApp(
home: Scaffold(
body: PageView(children: <Widget>[Home(), Completed()]),
)));
}
}
//Uncompleted
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: false,
title: Text("Students"),
actions: [
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AddInfo()),
).then((value) {
setState(() {});
});
},
icon: Icon(Icons.add),
)
],
),
body: userInfoBuilder(context),
);
}
Future<List<UserInfo>> loadUserInfo() async {
DBHelper sd = DBHelper();
return await sd.userInfo();
}
Future<void> deleteUserInfo(String id) async {
DBHelper sd = DBHelper();
sd.deleteUserInfo(id);
}
Widget userInfoBuilder(BuildContext parentContext) {
return FutureBuilder<List<UserInfo>>(
builder: (context, snap) {
if (snap.data == null || snap.data.isEmpty) {
return Container();
}
return ListView.builder(
itemCount: snap.data.length,
itemBuilder: (context, index) {
UserInfo userInfo = snap.data[index];
return Slidable(
actionPane: SlidableBehindActionPane(),
actions: <Widget>[
IconSlideAction(
caption: 'delete',
icon: Icons.delete,
color: Colors.red,
onTap: () {
setState(() {
deleteUserInfo(userInfo.id);
});
})
],
secondaryActions: <Widget>[
IconSlideAction(
caption: 'completed',
icon: Icons.check,
color: Colors.green,
onTap: () {}),
],
child: ListTile(
title: Text(
userInfo.name,
style: TextStyle(
fontSize: 18.0,
),
),
trailing: Text(
'${userInfo.grade}-${userInfo.classnum}-${userInfo.studentnum}',
style: TextStyle(color: Colors.grey),
),
),
);
},
);
},
future: loadUserInfo(),
);
}
}
//completed
class Completed extends StatefulWidget {
#override
_CompletedState createState() => _CompletedState();
}
class _CompletedState extends State<Completed> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: false,
title: Text(
"Completed",
),
),
body: userInfoBuilder(context),
);
}
Widget userInfoBuilder(BuildContext parentContext) {
return FutureBuilder<List<UserInfo>>(
builder: (context, snap) {
if (snap.data == null || snap.data.isEmpty) {
return Container();
}
return ListView.builder();
},
future: loadUserInfo(),
);
}
Future<List<UserInfo>> loadUserInfo() async {
DBHelper sd = DBHelper();
return await sd.userInfo();
}
}
//Add user information
class AddInfo extends StatefulWidget {
#override
_AddInfoState createState() => _AddInfoState();
}
class _AddInfoState extends State<AddInfo> {
hideKeyboard() {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
}
final formKey = GlobalKey<FormState>();
String _grade;
final List<String> _grades = ['1', '2', '3'];
String name = '';
String classNum = ' ';
String studentNum = ' ';
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
hideKeyboard();
},
child: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
color: Colors.black,
onPressed: () {
Navigator.pop(context);
hideKeyboard();
})),
body: Form(
key: formKey,
child: Column(
children: <Widget>[
usrNameField(),
Row(
children: <Widget>[
Expanded(child: usrGradeField()),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20.0),
),
Expanded(child: usrClassField()),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20.0),
),
Expanded(child: usrNumField()),
],
),
submitButton()
],
),
),
));
}
Widget usrNameField() {
return TextFormField(
keyboardType: TextInputType.name,
decoration: InputDecoration(
labelText: 'name',
),
onChanged: (String name) {
this.name = name;
},
validator: (input) => input.trim().isEmpty ? 'Enter name' : null);
}
Widget usrGradeField() {
return DropdownButtonFormField(
icon: Icon(Icons.arrow_drop_down_circle),
iconSize: 22.0,
items: _grades.map((String grade) {
return DropdownMenuItem(
value: grade,
child: Text(
grade,
style: TextStyle(color: Colors.black, fontSize: 18.0),
),
);
}).toList(),
style: TextStyle(fontSize: 18.0),
decoration: InputDecoration(
labelText: 'Grade',
),
validator: (input) => input.trim().isEmpty ? 'Enter grade.' : null,
onChanged: (value) {
setState(() {
_grade = value;
});
},
value: _grade,
);
}
Widget usrClassField() {
return TextFormField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Class',
),
validator: (input) => input.trim().isEmpty ? 'Enter class.' : null,
onChanged: (String classNum) {
this.classNum = classNum;
},
);
}
Widget usrNumField() {
return TextFormField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Number',
),
validator: (input) => input.trim().isEmpty ? 'Enter number' : null,
onChanged: (String studentNum) {
this.studentNum = studentNum;
},
);
}
Widget submitButton() {
return MaterialButton(
color: Colors.blue,
child: Text(
'submit',
style: TextStyle(color: Colors.white),
),
onPressed: () {
hideKeyboard();
if (formKey.currentState.validate()) {
saveDB();
Navigator.pop(context);
}
},
);
}
Future<void> saveDB() async {
DBHelper sd = DBHelper();
var fido = UserInfo(
id: str2sha512(DateTime.now().toString()),
name: this.name,
grade: this._grade,
classnum: this.classNum,
studentnum: this.studentNum,
);
await sd.insertUserInfo(fido);
print(await sd.userInfo());
}
String str2sha512(String text) {
var bytes = utf8.encode(text);
var digest = sha512.convert(bytes);
return digest.toString();
}
}
db.dart
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class UserInfo {
final String id;
final String name;
final String grade;
final String classnum;
final String studentnum;
UserInfo({
this.id,
this.name,
this.grade,
this.classnum,
this.studentnum,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'grade': grade,
'classnum': classnum,
'studentnum': studentnum,
};
}
#override
String toString() {
return 'userInfo{id: $id, name: $name, grade: $grade, classnum: $classnum, studentnum: $studentnum}';
}
}
final String TableName = 'userInfo';
class DBHelper {
var _db;
Future<Database> get database async {
if (_db != null) return _db;
_db = openDatabase(
join(await getDatabasesPath(), 'userInfo.db'),
onCreate: (db, version) {
return db.execute(
"CREATE TABLE userInfo(id TEXT PRIMARY KEY, name TEXT, grade TEXT, classnum TEXT, studentnum TEXT, phonenumber TEXT, status INTEGER)",
);
},
version: 1,
);
return _db;
}
Future<void> insertUserInfo(UserInfo userInfo) async {
final db = await database;
await db.insert(
TableName,
userInfo.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<List<UserInfo>> userInfo() async {
final db = await database;
final List<Map<String, dynamic>> maps = await db.query('userInfo');
return List.generate(maps.length, (i) {
return UserInfo(
id: maps[i]['id'],
name: maps[i]['name'],
grade: maps[i]['grade'],
classnum: maps[i]['classnum'],
studentnum: maps[i]['studentnum'],
);
});
}
Future<void> updateUserInfo(UserInfo userInfo) async {
final db = await database;
await db.update(
TableName,
userInfo.toMap(),
where: "id = ?",
whereArgs: [userInfo.id],
);
}
Future<void> deleteUserInfo(String id) async {
final db = await database;
await db.delete(
TableName,
where: "id = ?",
whereArgs: [id],
);
}
}
You can use the Provider package to listen to changes on your app and notify any listeners and update the UI here's A link to an example from the flutter devs

I want to show notification count from my login response json data from a login API in my flutter app

I have successfully got a logged in from the login api then i have got a response of json from here. from response i can fetch some of the data. but cann't fetch the notification array and need to count notification array for my notification icon count . How can i do it ? please help.
The response json format is -
{
"id": 1,
"name": "Mr Admin",
"email": "admin2#gmail.com",
"username": "admin2",
"api_token": "oYfajebhRzlxpMZV8dHI6w5R8CrpgybaGqX2ZaIXkGpumE9hZSgLVVINAgaF",
"user_types_id": null,
"created_at": "2020-01-21 16:21:48",
"updated_at": "2020-10-14 11:31:10",
"deleted_at": null,
"unread_notifications": [
{
"id": "d54ee0cc-054a-4d51-a53b-5f6f658841ae",
"type": "App\\Notifications\\HandSlipStatusNotification",
"notifiable_id": 1,
"notifiable_type": "App\\User",
"data": {
"payment_id": 471,
"generate_payment_id": "10200471",
"message": "Hand Slip Settled.",
"amount": 850
},
"read_at": null,
"created_at": "2020-10-12 15:50:38",
"updated_at": "2020-10-12 15:50:38"
},
{
"id": "aedb7880-4201-4805-b017-62242dfed741",
"type": "App\\Notifications\\HandSlipStatusNotification",
"notifiable_id": 1,
"notifiable_type": "App\\User",
"data": {
"payment_id": 471,
"generate_payment_id": "10200471",
"message": "Hand Slip Disbursed.",
"amount": 850
},
"read_at": null,
"created_at": "2020-10-12 15:50:25",
"updated_at": "2020-10-12 15:50:25"
},
i can show the id , name , email etc but cann't access unread_notifications.
my code -
api_service.dart ->
class LoginResponseModel {
final String token;
final String error;
LoginResponseModel({this.token, this.error});
factory LoginResponseModel.fromJson(Map<String, dynamic> json) {
return LoginResponseModel(
token: json["token"] != null ? json["token"] : "",
error: json["error"] != null ? json["error"] : "",
);
}
}
class LoginRequestModel {
String email;
String password;
String username;
LoginRequestModel({
this.email,
this.password,
this.username,
});
Map<String, dynamic> toJson() {
Map<String, dynamic> map = {
// 'email': email.trim(),
'username': username.trim(),
'password': password.trim(),
};
return map;
}
}
login_model
class LoginResponseModel {
final String token;
final String error;
LoginResponseModel({this.token, this.error});
factory LoginResponseModel.fromJson(Map<String, dynamic> json) {
return LoginResponseModel(
token: json["token"] != null ? json["token"] : "",
error: json["error"] != null ? json["error"] : "",
);
}
}
class LoginRequestModel {
String email;
String password;
String username;
LoginRequestModel({
this.email,
this.password,
this.username,
});
Map<String, dynamic> toJson() {
Map<String, dynamic> map = {
// 'email': email.trim(),
'username': username.trim(),
'password': password.trim(),
};
return map;
}
}
login.dart
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'homepage.dart';
class Login extends StatefulWidget {
#override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
var allData ;
TextEditingController _userController = TextEditingController();
TextEditingController _passwordController = TextEditingController();
bool _isLoading = false;
// arrange method for api log in
signIn( String username,String password) async {
String url = "my Url";
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
Map body = { "username": username, "password": password
};
var notificatiion;
var jsonResponse;
var res = await http.post(url, body: body);
//need to check the api status
if (res.statusCode == 200) {
jsonResponse = json.decode(res.body);
notificatiion = jsonResponse['unread_notifications'];
print("Response status: ${res.statusCode}");
print("Response status: ${res.body}");
if (jsonResponse != null) {
setState(() {
_isLoading = false;
});
sharedPreferences.setString("token", jsonResponse['token']);
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (BuildContext) =>
HomePage(
email: jsonResponse['email'],
name: jsonResponse['name'],
username : jsonResponse['username'],
notification: notificatiion,
),
),
(Route<dynamic> route) => false);
}
} else {
setState(() {
_isLoading == false;
});
print(" Response status : ${res.body}");
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: Center(
child: Container(
padding: EdgeInsets.fromLTRB(20, 100, 20, 20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text("Login",
style: TextStyle(fontSize: 32),
),
SizedBox(
height: 30,
),
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
child: Container(
height: 220,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
),
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(30),
child: TextField(
controller: _userController,
decoration: InputDecoration(hintText: "username"),
),
),
Padding(
padding: const EdgeInsets.all(30),
child: TextField(
controller: _passwordController,
obscureText: true,
decoration: InputDecoration(hintText: "Password"),
),
),
],
),
),
),
SizedBox(
height: 60,
width: MediaQuery.of(context).size.width,
child: RaisedButton(
color: Colors.lightBlue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
child: Text("Sign In"),
onPressed: _userController.text == ""||
_passwordController.text == ""
? null
: () {
setState(() {
_isLoading = true ;
});
signIn(_userController.text, _passwordController.text);
},
),
),
SizedBox(
height: 20,
),
FlatButton(
child: Text("Forgot password"),
onPressed: (){
},
),
],
),
),
),
),
),
);
}
}
i want to show all the response value in home page . in a profile and in notification's icon. Help me .
homepage.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'login.dart';
import 'login.dart';
class HomePage extends StatelessWidget {
String email;
String name;
String username;
List<dynamic> notification;
HomePage({this.email, this.name, this.username, this.notification, });
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Cash-Management"),
backgroundColor: Colors.blue,
actions: [
IconButton(icon: Icon(Icons.notifications), onPressed: () {}),
IconButton(
icon: Icon(Icons.exit_to_app),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Login()),
);
}),
],
),
body: ListView(
children: <Widget>[
Container(
height: 200,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(
" $email ",
style: TextStyle(fontSize: 16),
),
Text(" $name "),
Text(" $username "),
],
),
),
Container(
height: 300,
child: ListView.builder(
itemCount: notification == null ? 0 : notification.length,
itemBuilder: (context, index){
return ListTile(
title: Text(notification[index] ["id"]),
subtitle: Text(notification[index]["type"]),
);
}),
),
],
),
),
);
}
}

Error fetching data from api and display it

I want to make a get request from my restApi and then display the data in a listView but for some reason it is not working.
The error I'm getting:
The getter 'length' was called on null.
Receiver: null
Tried calling: length
Api call (apiBaseHelper.dart)
Future<List<Post>> getAllPosts() async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key) ?? 0;
final getPublishedPostUrl = "http://192.168.1.7:5000/post/all";
final response = await http.get(getPublishedPostUrl, headers: {
'Accept': 'application/json',
'Authorization': 'Bearer $value'
});
if (response.statusCode == 200) {
List jsonResponse = json.decode(response.body);
return jsonResponse.map((posts) => new Post.fromJson(posts)).toList();
} else {
throw "something ";
}
}
PostListView
class PostListView extends StatelessWidget {
final List<Post> posts;
PostListView({Key key, this.posts}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: posts.length,
itemBuilder: (context, index) {
return Column(
children: <Widget>[
Container(
constraints: BoxConstraints.expand(
height:
Theme.of(context).textTheme.display1.fontSize * 1.1 + 200.0,
),
color: Colors.white10,
alignment: Alignment.center,
child: Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
contentPadding: EdgeInsets.all(10.0),
title: new Text(posts[index].title),
leading: new Image.network(
posts[index].picture,
fit: BoxFit.cover,
height: 40.0,
width: 40.0,
),
subtitle: Text(posts[index].category),
),
],
),
),
),
],
);
},
));
}
}
homePage.dart
class HomePage extends StatefulWidget {
final ApiBaseHelper apiBaseHelper = ApiBaseHelper();
#override
State<StatefulWidget> createState() {
return _HomePageState();
}
}
class _HomePageState extends State<HomePage> {
Future<List<Post>> futurePost;
#override
void initState() {
super.initState();
futurePost = ApiBaseHelper().getAllPosts();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.teal,
body: new Padding(
padding: EdgeInsets.fromLTRB(1.0, 10.0, 1.0, 10.0),
child: FutureBuilder<List<Post>>(
future: ApiBaseHelper().getAllPosts(),
builder: (context, AsyncSnapshot<List<Post>> snapshot) {
if (snapshot.hasError) {
print(snapshot.error);
}
return snapshot.hasData
? PostListView()
: Center(child: CircularProgressIndicator());
},
),
),
);
}
}
I have been working on it for like 2 days and I don't know where the problem exactly
I'm sorry if it's too much code. thank you in advance
This code section here ,
return snapshot.hasData
? PostListView()
: Center(child: CircularProgressIndicator());
Add PostListView(posts:snapshot.data)
Tell me if it works.

returning null user back from function

I am working on Login page with Local db SQL in flutter.
The page isn't creating a SQL table and returning null user, thus showing the snackbar "wrong email".
I have tried to debug but can't find the solution as i am pretty new at this.
This is my sign up page:
class _RegisterState extends State<Register> {
DatabaseHelper db = new DatabaseHelper();
TextEditingController emailController = TextEditingController();
TextEditingController mobileController = TextEditingController();
Future<User> _loginUser(String email,String mobile) async{
User saveUser = User.fromMapObject({
email:"hfah#gmail.com",
mobile:"1432567890"
});
await db.saveUser(saveUser).then((val) async {
if(val == 1){
User user = await db.loginUser(email, mobile);
return user;
}
});
}
final _formKey = GlobalKey<FormState>();
final scaffoldKey = new GlobalKey<ScaffoldState>();
#override
Widget build(BuildContext context) {
final bgColor = const Color(0xFF4b0081);
return Scaffold(
resizeToAvoidBottomPadding: false,
backgroundColor: bgColor,
key: scaffoldKey,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image(
image: AssetImage("assets/newlogo2.png"),
width: 200,
height: 50,
),
Container(
padding: const EdgeInsets.only(top:20.0, right: 20, left: 20),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: "Mobile No",
labelStyle: TextStyle(color: Colors.white)
),
style: TextStyle(color: Colors.white, fontSize: 20.0),
onChanged: (val) {
setState(() => mob = val);
},
controller: emailController,
),
SizedBox(height: 20.0,),
TextFormField(
validator: (val) => val.isEmpty ? 'Enter an Email' : null,
decoration: InputDecoration(
labelText: "Email ID",
labelStyle: TextStyle(color: Colors.white)
),
style: TextStyle(color: Colors.white, fontSize: 20.0),
onChanged: (val){
setState(() => email = val);
},
controller: mobileController,
),
SizedBox(height: 20.0,),
RaisedButton(
color: Colors.white,
child: Text(
'Register',
style: TextStyle(color: bgColor),
),
onPressed: () async {
User user = await _loginUser(emailController.text, mobileController.text);
if(user != null){
Navigator.of(context).push(MaterialPageRoute<Null>(
builder: (BuildContext context){
return new Home(
user:user,
);
}
));
}else{
scaffoldKey.currentState.showSnackBar(
SnackBar(content: Text("Wrong email"),)
);
}
},
splashColor: Colors.grey,
),
SizedBox(height: 12.0,),
Text(
error,
style: TextStyle(
color: Colors.red,
fontSize: 14.0
),
),
FlatButton(
color: bgColor,
child: Text(
'Back to Sign In',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
onPressed: () async {
setState(() {
//widget.toggleView();
},);
},
),
],
),
),
),
],
),
);
}
This is DatabaseHelper class
class DatabaseHelper{
static final DatabaseHelper _instance = new DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
static Database _db;
String colemail = 'emial_id';
String tablename = 'User';
String colMobile = 'mobild_no';
Future<Database> get db async{
if(_db != null) return _db;
_db = await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async{
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "main.db");
var theDb = await openDatabase(path,version:1,onCreate: _onCreate);
return theDb;
}
void _onCreate(Database db,int version) async{
await db.execute("""
CREATE TABLE User(
user_id INTEGER PRIMARY KEY,
email_id TEXT,
mobile_no TEXT
)""");
print("Table created");
}
Future<int> saveUser(User user) async{
var dbClient = await db;
int res = await dbClient.insert(tablename, user.toMap());
return res;
}
Future<User> loginUser(String email,String mobile) async{
var dbClient = await db;
String sql = "SELECT * FROM User WHERE email_id = '$email' AND
mobile_no = '$mobile' ";
var result = await dbClient.rawQuery(sql);
if(result.length == 0) return null;
return User.fromMapObject(result.first);
}
}
And this is User class
class User{
int _user_id;
String email_id;
String mobile_no;
User(this.email_id,this.mobile_no,this._user_id);
String get emailID => email_id;
String get mobileNO => mobile_no;
int get user_id =>_user_id;
set emailID(String newMail){
this.email_id = newMail;
}
set mobileNO(String newMob){
this.mobile_no = newMob;
}
Map <String,dynamic> toMap(){
return {
'email_id': email_id,
'mobile_no': mobile_no,
'user_id':_user_id
};
}
User.fromMapObject(dynamic map){
this.email_id = map['email_id'];
this.mobile_no = map['mobile_no'];
this._user_id = map['user_id'];
}
}
Please help !!!
In _RegisterState class, I don't see if you instantiated DatabaseHelper db; so db is null and you are trying to invoke saveUser on null instance variable in following code
await db.saveUser(saveUser).then((val) async {
if(val == 1){
User user = await db.loginUser(email, mobile);
return user;
}
});
Replace this
Scaffold.of(context).showSnackBar(SnackBar(content: Text("Wrong email"),));
with
scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Wrong email")));
You just need to instantiate db:
class _RegisterState extends State<Register> {
DatabaseHelper db = new DatabaseHelper();
....
}
For the Snackbar error, replace this code:
else{
Scaffold.of(context).showSnackBar(
SnackBar(content: Text("Wrong email"),)
);
}
with:
else{
globalKey.currentState.showSnackBar(
SnackBar(content: Text("Wrong email"),)
);
}

come from back navigation app not refreshing in flutter

When i am on edit profile screen i changed my details and back from the back icon, On the next screen my updated data not reflecting.
This is my home screen where i need to call below API:
Main.dart
#override
Widget build(BuildContext context) {
return new MaterialApp(
showPerformanceOverlay: false,
debugShowCheckedModeBanner: false,
title: 'hempmeASAP',
home: (is_loggedin) ? Home():Login(),
routes: {
"/home": (_) => new Home(),
"/login": (_) => new Login(),
"/signup": (_) => new Signup(),
"/forgot": (_) => new ForgotPassword()
},
);
}
home.dart
void initState() {
super.initState();
getProfileData();
}
getProfileData() {
customFun.readToken().then((val) {
setState(() {
access_token = val;
});
try{
(() async {
await restApis.getProfile(access_token).then((val) => setState((){
print(val);
name = (val["data"]["name"]).toString();
profile_img = val["data"]["avatarUrl"];
}));
})();
}catch(e){
setState(() {
showProgressBar = false;
//show_error = true;
//error_msg = "The exception thrown is $e";
});
scaffoldKey.currentState.showSnackBar(SnackBar(
backgroundColor: Colors.red,
content: Text("The exception thrown is $e"),
));
}
});
}
// I need to pass updated name and profile_img here
child: new Scaffold(
key: scaffoldKey,
//drawer: new Drawer(child: DrawerList()),
appBar: AppBarComponent(context: context, appbarTitle:appBarTitle, name: name, profile_img: profile_img),
)
app_bar_component.dart
class AppBarComponent extends AppBar {
AppBarComponent({Key key, BuildContext context, appbarTitle, name, profile_img, screenName})
: super(
key: key,
backgroundColor: Colors.white,
//centerTitle: false,
iconTheme: IconThemeData(
color: Color(0xff888888), //change your color here
),
title: Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Stack(
children: <Widget>[
CircleAvatar(
radius: 26.0,
backgroundImage: (profile_img != null && profile_img != "") ? NetworkImage("$profile_img"):NetworkImage('https://via.placeholder.com/150',scale: 1.0),
backgroundColor: Colors.transparent,
),
]
),
Padding(
padding: const EdgeInsets.all(10.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
margin: EdgeInsets.only(bottom: 2.0),
child: Text("$name",style: TextStyle(color: Color(0xff444444),fontSize: 16.0))
),
screenName != 'edit' ?
GestureDetector(
child: Text("Edit Profile", style: TextStyle(fontSize: 11.0, color: Colors.blue,decoration: TextDecoration.underline)),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Editprofile())
);
}
):Container()
]
)
)
],
),
),
actions: <Widget>[
new IconButton(
onPressed: () =>
customFun.logout().then((_) =>
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=> Login(logout:true)))
),
icon: Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 8.0,top: 4.0),
child: Icon(Icons.exit_to_app,color: Color(0xff888888)),
),
]
)
),
],
);
}
editprofile.dart
void _submitlogin() {
final form = formKey.currentState;
Map _data;
if(form.validate()){
if(_newpassword != _confirmpassword){
setState(() {
show_error = true;
error_msg = "Confirm Password should match password";
});
}
showProgressBar = true;
customFun.readToken().then((val) {
access_token = val;
try{
(() async {
await restApis.postUpdateProfile(access_token,_name,_mobile,_oldpassword,_newpassword,_confirmpassword).then((val) => setState(() {
// print("response");
print(val);
if(val["success"]){
form.save();
scaffoldKey.currentState.showSnackBar(SnackBar(
backgroundColor: Colors.green,
content: Text(val["message"]),
));
setState(() {
showProgressBar = false;
show_error = false;
});
_getProfleDetail();
}else{
showProgressBar = false;
scaffoldKey.currentState.showSnackBar(SnackBar(
backgroundColor: Colors.red,
content: Text(val["message"]),
));
}
}));
})();
}catch(e){
setState(() {
showProgressBar = false;
//show_error = true;
//error_msg = "The exception thrown is $e";
});
scaffoldKey.currentState.showSnackBar(SnackBar(
backgroundColor: Colors.red,
content: Text("The exception thrown is $e"),
));
}
});
}
}
THESE ARE THE MAIN FUNCTIONS AND WHEN I UPDATE MY PROFILE AND BACK FROM NAVIGATION BACK ICON ON EDIT PROFILE SCREEN ON MY HOME PAGE APP BAR PROFILE PHOTO AND THE NAME IS NOT UPDATING. NAME AND PROFILE PHOTO SHOULD BE UPDATED IN APP.
I need to call getProfileData(); function when i am coming to home screen from edit profile screen.
UPDATED: My issue is when i update my image from updateprofile screen this result is not reflecting on the home screen.
Please let me know if any solution.