sharedp references Getting Stored Data in Another Flutter Page - flutter

I want to get user details such as id, email, username in my HomePage when the user login into the login page. I was able to get the data via this
SPUtil.putString('user', user);
print(user);
Now, the issue is how should I pick it up in another page for usage or display those data. I have a file called sputils.dart where all the code that I used to get the data.
class AuthService {
Future<String> login({
required String username,
required String password,
}) async {
try {
final body = {
'username': username,
'password': password,
};
final response = await http.post(
Uri.parse('$BASE_URL/login'),
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode(body),
);
if (response.statusCode != 200) {
throw LoginError.unexpected;
}
Map<String, dynamic> data = jsonDecode(response.body);
User loggedInUser = User.fromJson(data['user']);
String user = jsonEncode(loggedInUser);
SPUtil.putString('user', user);
print(user);
return jsonDecode(response.body)['token'];
} on LoginError {
print('login error');
rethrow;
} catch (e) {
print(e);
throw LoginError.unexpected;
}
}
import 'dart:async';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:synchronized/synchronized.dart';
// SharedPreferences
class SPUtil {
static SPUtil? _singleton;
static SharedPreferences? _prefs;
static final Lock _lock = Lock();
static Future<SPUtil> getInstance() async {
if (_singleton == null) {
await _lock.synchronized(() async {
if (_singleton == null) {
// keep local instance till it is fully initialized.
final singleton = SPUtil._();
await singleton._init();
_singleton = singleton;
}
});
}
return _singleton!;
}
SPUtil._();
Future _init() async {
_prefs = await SharedPreferences.getInstance();
}
// put object
static Future<bool> putObject(String key, Object value) {
return _prefs!.setString(key, json.encode(value));
}
// get string
static String getString(String key, {String defValue = ''}) {
if (_prefs == null) return defValue;
return _prefs!.getString(key) ?? defValue;
}
// put string
static Future<bool> putString(String key, String value) async {
return _prefs!.setString(key, value);
}
// get bool
static bool getBool(String key, {bool defValue = false}) {
if (_prefs == null) return defValue;
return _prefs!.getBool(key) ?? defValue;
}
// put bool
static Future<bool> putBool(String key, {bool value = false}) {
return _prefs!.setBool(key, value);
}
// get int
static int getInt(String key, {int defValue = 0}) {
if (_prefs == null) return defValue;
return _prefs!.getInt(key) ?? defValue;
}
// put int.
static Future<bool> putInt(String key, int value) {
return _prefs!.setInt(key, value);
}
// get double
static double getDouble(String key, {double defValue = 0.0}) {
if (_prefs == null) return defValue;
return _prefs!.getDouble(key) ?? defValue;
}
// put double
static Future<bool> putDouble(String key, double value) {
return _prefs!.setDouble(key, value);
}
// get string list
static List<String> getStringList(String key,
{List<String> defValue = const []}) {
if (_prefs == null) return defValue;
return _prefs!.getStringList(key) ?? defValue;
}
// put string list
static Future<bool> putStringList(String key, List<String> value) {
return _prefs!.setStringList(key, value);
}
// clear
static Future<bool> clear() {
return _prefs!.clear();
}
// clear a string
static Future<bool> clearString(String key) {
return _prefs!.remove(key);
}
//Sp is initialized
static bool isInitialized() {
return _prefs != null;
}
}

To use saved data from another page,
make your data instance to global(static)
save the data inside of static class
If your application is simple and just test something, go to No.1.
Or else, go to No.2.
make class static : https://dev.to/lucianojung/global-variable-access-in-flutter-3ijm
Using getController is easier to make it global : https://pub.dev/packages/get

Related

Flutter : TypeError: Cannot read properties of null (reading 'setString')

I want to make progress tracker like if the user passed level 1 level 1 I will send to the Map level 1 is true (Finished),
I don't want to use database so I tried Shared Preferences Package then I faced the Error That in the title
... if you have a better way to do it please write it
class CheckLvl extends StatelessWidget {
static SharedPreferences sharedPreferences;
Map<String , String> Check = {
'1':'true',
'2':'false',
'3':'false',
'4':'false',
};
String encoded ;
String encodedMap;
Map<String , String> decoded;
CheckLvl(){
encoded = jsonEncode(Check);
sharedPreferences.setString('State', encoded);
}
static init () async
{
sharedPreferences = await SharedPreferences.getInstance();
}
Future<bool> isComplete (String index) async {
encodedMap = sharedPreferences.getString('State');
decoded = jsonDecode(encodedMap);
print(decoded);
if (decoded[index]=='true')
return true;
}
void Done(String index)
{
encodedMap = sharedPreferences.getString('State');
decoded = jsonDecode(encodedMap);
decoded[index]='true';
}
It is possible to get null data while reading , you can do
Future<bool> isComplete (String index) async {
final String? data = sharedPreferences.getString('State');
return data=='true' ;
}
Better using FutureBuilder for future method like
class CheckLvl extends StatefulWidget {
#override
State<CheckLvl> createState() => _CheckLvlState();
}
class _CheckLvlState extends State<CheckLvl> {
SharedPreferences? sharedPreferences;
Map<String, String> Check = {
'1': 'true',
'2': 'false',
'3': 'false',
'4': 'false',
};
Future<void> init() async {
sharedPreferences = await SharedPreferences.getInstance();
}
String? encoded;
String? encodedMap;
Map<String, String>? decoded;
Future<bool> isComplete(String index) async {
encodedMap = sharedPreferences!.getString('State');
decoded = jsonDecode(encodedMap!);
print(decoded);
if (decoded?[index] == 'true') return true;
return false;
}
void Done(String index) async {
encodedMap = sharedPreferences!.getString('State');
decoded = jsonDecode(encodedMap!);
decoded?[index] = 'true';
}
late final prefFuture = init();
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: prefFuture,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text("got data");
}
return CircularProgressIndicator();
},
);
}
}
class CheckLvl extends StatelessWidget {
static SharedPreferences? sharedPreferences;
Map<String, String> Check = {
'1': 'true',
'2': 'false',
'3': 'false',
'4': 'false',
};
String? encoded;
String? encodedMap;
Map<String, String>? decoded;
static Future<SharedPreferences> init() async {
return await SharedPreferences.getInstance();
}
Future<bool> isComplete(String index) async {
sharedPreferences ??= await init();
encodedMap = sharedPreferences!.getString('State');
decoded = jsonDecode(encodedMap!);
print(decoded);
if (decoded?[index] == 'true') return true;
return false;
}
void Done(String index) async {
sharedPreferences ??= await init();
encodedMap = sharedPreferences!.getString('State');
decoded = jsonDecode(encodedMap!);
decoded?[index] = 'true';
}
#override
Widget build(BuildContext context) {
throw UnimplementedError();
}
}

type 'Null' is not a subtype of type 'DatabaseNotes' in type cast

The problem lies in the FutureBuilder widget section. I am trying to get the data from a snapshot in a FutureBuilder, but I get an error as 'type 'Null' is not a subtype of type 'DatabaseNotes' in type cast'. I tried declaring the _note field as late final but it still throws the same error. I have taken care of the null safety part by adding the ? in after the data type (here, it is DatabaseNotes). I still don't get what is wrong here.
The following is the code for the NewNoteView widget:
class NewNoteView extends StatefulWidget {
const NewNoteView({Key? key}) : super(key: key);
#override
State<NewNoteView> createState() => _NewNoteViewState();
}
class _NewNoteViewState extends State<NewNoteView> {
DatabaseNotes? _note;
late final NotesService _notesService;
late final TextEditingController _textController;
#override
void initState() {
_notesService = NotesService();
_textController = TextEditingController();
super.initState();
}
void _textControllerListener() async {
final note = _note;
if (note == null) {
return;
}
final text = _textController.text;
await _notesService.updateNote(
note: note,
text: text,
);
}
void _setupTextControllerListener() {
_textController.removeListener(_textControllerListener);
_textController.addListener(_textControllerListener);
}
Future<DatabaseNotes> createNewNote() async {
final existingNote = _note;
if (existingNote != null) {
return existingNote;
}
final currentUser = AuthService.firebase().currentUser!;
final email = currentUser.email!;
final owner = await _notesService.getUser(email: email);
return await _notesService.createNote(owner: owner);
}
void _deleteNoteIfTextIsEmpty() {
final note = _note;
if (_textController.text.isEmpty && note != null) {
_notesService.deleteNote(id: note.id);
}
}
void _saveNoteIfTextNotEmpty() async {
final note = _note;
final text = _textController.text;
if (note != null && text.isNotEmpty) {
await _notesService.updateNote(
note: note,
text: text,
);
}
}
#override
void dispose() {
_deleteNoteIfTextIsEmpty();
_saveNoteIfTextNotEmpty();
_textController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('New note'),
),
body: FutureBuilder(
future: createNewNote(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
_note = snapshot.data as DatabaseNotes;
_setupTextControllerListener();
return TextField(
controller: _textController,
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: const InputDecoration(
hintText: 'Start typing your note...',
),
);
default:
return const CircularProgressIndicator();
}
},
));
}
}
The following is the code for NotesService:
class DatabaseAlreadyOpenException implements Exception {}
class NotesService {
Database? _db;
List<DatabaseNotes> _notes = [];
static final NotesService _shared = NotesService._sharedInstance();
NotesService._sharedInstance();
factory NotesService() => _shared;
final _notesStreamController =
StreamController<List<DatabaseNotes>>.broadcast();
Stream<List<DatabaseNotes>> get allNotes => _notesStreamController.stream;
Future<DatabaseUser> getOrCreateUser({required String email}) async {
try {
final user = getUser(email: email);
return user;
} on CouldNotFindUser {
final createdUser = createUser(email: email);
return createdUser;
} catch (e) {
rethrow;
}
}
Future<void> _cacheNotes() async {
final allNotes = await getAllNotes();
_notes = allNotes.toList();
_notesStreamController.add(_notes);
}
Future<DatabaseNotes> updateNote({
required DatabaseNotes note,
required String text,
}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
// make sure note exists
await getNote(id: note.id);
// update DB
final updatesCount = await db.update(notesTable, {
textColumn: text,
isSyncedWithCloudColumn: 0,
});
if (updatesCount == 0) {
throw CouldNotUpdateNote();
} else {
final updatedNote = await getNote(id: note.id);
_notes.removeWhere((note) => note.id == updatedNote.id);
_notes.add(updatedNote);
_notesStreamController.add(_notes);
return updatedNote;
}
}
Future<Iterable<DatabaseNotes>> getAllNotes() async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final notes = await db.query(
notesTable,
);
return notes.map((noteRow) => DatabaseNotes.fromRow(noteRow));
}
Future<DatabaseNotes> getNote({required int id}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final notes = await db.query(
notesTable,
limit: 1,
where: 'id = ?',
whereArgs: [id],
);
if (notes.isEmpty) {
throw CouldNotFindNote();
} else {
final note = DatabaseNotes.fromRow(notes.first);
_notes.removeWhere((note) => note.id == id);
_notes.add(note);
_notesStreamController.add(_notes);
return note;
}
}
Future<int> deleteAllNotes() async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final numberOfDeletions = await db.delete(notesTable);
_notes = [];
_notesStreamController.add(_notes);
return numberOfDeletions;
}
Future<void> deleteNote({required int id}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final deletedCount = await db.delete(
notesTable,
where: 'id = ?',
whereArgs: [id],
);
if (deletedCount == 0) {
throw CouldNotDeleteNote();
} else {
_notes.removeWhere((note) => note.id == id);
_notesStreamController.add(_notes);
}
}
Future<DatabaseNotes> createNote({required DatabaseUser owner}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
// make sure the owner exists in the database with the correct id
final dbUser = await getUser(email: owner.email);
if (dbUser != owner) {
throw CouldNotFindUser();
}
const text = '';
// create the note
final noteId = await db.insert(notesTable, {
userIdColumn: owner.id,
textColumn: text,
isSyncedWithCloudColumn: 1,
});
final note = DatabaseNotes(
id: noteId,
userId: owner.id,
text: text,
isSyncedWithCloud: true,
);
_notes.add(note);
_notesStreamController.add(_notes);
return note;
}
Future<DatabaseUser> getUser({required String email}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final results = await db.query(
userTable,
limit: 1,
where: 'email = ?',
whereArgs: [email.toLowerCase()],
);
if (results.isEmpty) {
throw CouldNotFindUser();
} else {
return DatabaseUser.fromRow(results.first);
}
}
Future<DatabaseUser> createUser({required String email}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final results = await db.query(
userTable,
limit: 1,
where: 'email = ?',
whereArgs: [email.toLowerCase()],
);
if (results.isNotEmpty) {
throw UserAlreadyExists();
}
final userId = await db.insert(userTable, {
emailColumn: email.toLowerCase(),
});
return DatabaseUser(
id: userId,
email: email,
);
}
Future<void> deleteUser({required String email}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final deletedCount = await db.delete(
userTable,
where: 'email = ?',
whereArgs: [email.toLowerCase()],
);
if (deletedCount != 1) {
throw CouldNotDeleteUser();
}
}
Database _getDatabaseOrThrow() {
final db = _db;
if (db == null) {
throw DatabaseIsNotOpen();
} else {
return db;
}
}
Future<void> close() async {
final db = _db;
if (db == null) {
throw DatabaseIsNotOpen();
} else {
await db.close();
_db = null;
}
}
Future<void> _ensureDbIsOpen() async {
try {
await open();
} on DatabaseAlreadyOpenException {
//empty block
}
}
Future<void> open() async {
if (_db != null) {
throw DatabaseAlreadyOpenException;
}
try {
final docsPath = await getApplicationDocumentsDirectory();
final dbPath = join(docsPath.path, dbName);
final db = await openDatabase(dbPath);
_db = db;
// create the user table
await db.execute(createUserTable);
// create the notes table
await db.execute(createNotesTable);
await _cacheNotes();
} on MissingPlatformDirectoryException {
throw UnableToGetDocumentsDirectory;
}
}
}
#immutable
class DatabaseUser {
final int id;
final String email;
const DatabaseUser({
required this.id,
required this.email,
});
DatabaseUser.fromRow(Map<String, Object?> map)
: id = map[idColumn] as int,
email = map[emailColumn] as String;
#override
String toString() => 'Person id = $id, email = $email';
#override
bool operator ==(covariant DatabaseUser other) => id == other.id;
#override
int get hashCode => id.hashCode;
}
class DatabaseNotes {
final int id;
final int userId;
final String text;
final bool isSyncedWithCloud;
DatabaseNotes({
required this.id,
required this.userId,
required this.text,
required this.isSyncedWithCloud,
});
DatabaseNotes.fromRow(Map<String, Object?> map)
: id = map[idColumn] as int,
userId = map[userIdColumn] as int,
text = map[textColumn] as String,
isSyncedWithCloud = (map[isSyncedWithCloudColumn]) == 1 ? true : false;
#override
String toString() =>
'Note, ID = $id, userId = $userId, isSyncedWithCloud = $isSyncedWithCloud, text = $text';
#override
bool operator ==(covariant DatabaseNotes other) => id == other.id;
#override
int get hashCode => id.hashCode;
}
You can place the '?' after DatabaseNotes (or DatabaseNote if you are following the FreeCodeCamp tutorial more precisely). Your IDE will probably then tell you the cast to DatabaseNotes is unnecessary. I then removed the 'as DatabaseNotes' entirely and it worked. Final line of code as below.
_note = snapshot.data;
Try this
FutureBuilder<DatabaseNotes>(your code);
I found the mistake and turns out I wasn't handling the null safety after all; I feel like an idiot.
I created an instance of 'DatabaseNotes?' _note, but when I assigned the snapshot's data inside the FutureBuilder in the line _note = snapshot.data as DatabaseNotes, I forgot to add the ? after DatabaseNotes.
The statement should be: _note = snapshot.data as DatabaseNotes?;
Thank you everyone for your answers and suggestions. I highly appreciate your efforts.
After
_note = snapshot.data as DatabaseNotes;
just put
?
This null safety sign. And your code will run errorless. My code so suffers for this damn sign.

displaying only the current user data

I protected data_service with current user to only display the current user's habits.
data_service.dart:
class DataService {...
late final Database db;
Users? _user;
late final StreamData<Map<int, Habit>> habits;
Future<void> init() async {
db = await HabitsDb.connectToDb();
habits = StreamData(initialValue: await _getAllHabits(), broadcast: true);
}
String get userEmail => AuthService.firebase().currentUser!.email;
Future<Map<int, Habit>> _getAllHabits() async {
getOrCreateUser(email: userEmail); //issue
final habits = await _getAllHabitsFromDb();
final map = Map<int, Habit>();
final currentUser = _user;
print(currentUser);
for (final habit in habits) {
if (currentUser != null) {
print(currentUser.id);
print(habit.userId);
if (habit.userId == currentUser.id) {
map[habit.id] = habit;
}
}
//map[habit.userId] = currentUser?.id;
}
return map;
}
Future<List<Habit>> _getAllHabitsFromDb() async {
final habitsMap = await HabitsDb.getAllHabits(db);
final habitsList = habitsMap.map((e) => Habit.fromDb(e)).toList();
return habitsList;
}
Future<Users> getOrCreateUser({
required String email,
bool setAsCurrentUser = true,
}) async {
try {
//we found the user
final user = await getUser(email: email);
if (setAsCurrentUser) {
_user = user;
}
print(_user?.email);
return user;
} on CouldNotFindUser {
//we didn't find the user
final createdUser = await createUser(email: email);
if (setAsCurrentUser) {
_user = createdUser;
}
return createdUser;
} catch (e) {
rethrow;
}
}
...}
in main class:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
final dataService = DataService();
await dataService.init();
GetIt.I.registerSingleton(dataService);
... }
StreamData class:
class StreamData<T> {
List<Habit> _notes = [];
User? _user;
late final StreamController<T> _controller;
Stream<T> get stream => _controller.stream;
late T _value;
T get value => _value;
StreamData({required T initialValue, bool broadcast = true}) {
if (broadcast) {
_controller = StreamController<T>.broadcast();
} else {
_controller = StreamController<T>();
}
_value = initialValue;
}
the problem is that the line getOrCreateUser(email: userEmail); is only called once and it does not work when I switch user and I need to Hot Restart to fix it. I think using Futurebuilder will fix it. but if yes, how do I use it when there is a need to call dataService.init at the beginning of the main?
Since your getOrCreateUser function is declared as async, you'll want to use await when you call it in _getAllHabits:
await getOrCreateUser(email: userEmail)
This ensures the getOrCreateUser code has completed before the rest of the code in _getAllHabits (that depends on the result of getOrCreateUser) executes.

How do you turn a List <dynamic> into a List <Map> >>

I started to learn Flutter because I want to build an app which can handle API-Calls.
But now I'm frustrated because I want to make an infinite Load and don't get it to work.
The Problem is, that the method require an Future<List> but I dont know how to convert the response from the API into an List
Future<List<Map>> _getServerData(int length) async{
String api = data.url +length.toString();
final res=
await http.get("data.url");
if (res.statusCode == 200) {
List<dynamic> resp = jsonDecode(res.body);
return resp;
} else {
throw Exception('Failed to load DATA');
}
}
The whole class is out of an Tutorial from oodavid.
But in his tutorial he dont use an API
Future<List<Map>> _getExampleServerData(int length) {
return Future.delayed(Duration(seconds: 1), () {
return List<Map>.generate(length, (int index) {
return {
"body": WordPair.random().asPascalCase,
"avatar": 'https://api.adorable.io/avatars/60/${WordPair.random().asPascalCase}.png',
};
});
});
}
That was the how he solved it
Down below is the whole class
import 'dart:async';
import 'dart:convert';
import 'package:Kontra/pages/articel_list.dart';
import 'package:http/http.dart' as http;
import 'package:Kontra/api/url.dart' as data;
import 'package:Kontra/api/articelsResponse.dart';
/// Example data as it might be returned by an external service
/// ...this is often a `Map` representing `JSON` or a `FireStore` document
Future<List<Map>> _getServerData(int length) async{
String api = data.url +length.toString();
final res=
await http.get(data.url);
if (res.statusCode == 200) {
List<dynamic> resp = jsonDecode(res.body);
return resp;
} else {
throw Exception('Failed to load DATA');
}
}
/// PostModel has a constructor that can handle the `Map` data
/// ...from the server.
class PostModel {
String sId;
String title;
String text;
String author;
String pictures;
String link;
int postId;
String createdAt;
PostModel({this.title, this.text, this.pictures, this.link, this.postId});
factory PostModel.fromServerMap(Map<String, dynamic> json) {
return PostModel(
title: json['title'],
text: json['text'],
pictures: json['pictures'],
link: json['link'],
postId: json['postId']
);
}
}
/// PostsModel controls a `Stream` of posts and handles
/// ...refreshing data and loading more posts
class PostsModel {
int reload = 0;
Stream<List<PostModel>> stream;
bool hasMore;
bool _isLoading;
List<Map> _data;
StreamController<List<Map>> _controller;
PostsModel() {
_data = List<Map>();
_controller = StreamController<List<Map>>.broadcast();
_isLoading = false;
stream = _controller.stream.map((List<Map> postsData) {
return postsData.map((Map postData) {
return PostModel.fromServerMap(postData);
}).toList();
});
hasMore = true;
refresh();
}
Future<void> refresh() {
return loadMore(clearCachedData: true);
}
Future<void> loadMore({bool clearCachedData = false}) {
if (clearCachedData) {
_data = List<Map>();
hasMore = true;
}
if (_isLoading || !hasMore) {
return Future.value();
}
_isLoading = true;
return _getServerData(reload++).then((postsData) {
_isLoading = false;
_data.addAll(postsData);
hasMore = (_data.length < 30);
_controller.add(_data);
});
}
}
Thanks for your help guys
Try with
return List<Map>.from(resp.whereType<Map>());
Or
return resp.whereType<Map>().toList();
Or
return resp.cast<Map>();

How to get CONTEXT for the provider to work? Flutter

In the Future fetchStudentInfo() function, i would like to use the userId from my Auth class to do filtering. The userId is embedded in the URL and it will retrieve data from database. But, the issue is that the context is lacking in the function itself. However, I couldn't figure out a way to pass in the context. It would be great if any legend could help me. The solution which retrieve data from internet is found on the flutter documentation. And i wouldn't like to hard code the userId.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';
import '../model/student.dart';
import '../provider/auth.dart';
Future<Student> fetchStudentInfo() async {
final auth = Provider.of<Auth>(context);
final response = await http.post(
'https://intermediary-sharpe.000webhostapp.com/Student/read_one.php?userId=$auth.userId');
if (response.statusCode == 200) {
return Student.fromJson(json.decode(response.body));
} else {
throw Exception('Failed');
}
}
class ProfileScreen extends StatefulWidget {
#override
_ProfileScreenState createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
Future<Student> student;
#override
void initState() {
// TODO: implement initState
super.initState();
student = fetchStudentInfo();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<Student>(
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.studentId);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return CircularProgressIndicator();
},
future: student,
),
);
}
}
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import '../model/http_exception.dart';
class Auth with ChangeNotifier {
String _token;
DateTime _expiryDate;
String userId;
Timer _authTimer;
bool get isAuthenticated {
return token != null;
}
String get token {
if (_expiryDate != null &&
_expiryDate.isAfter(DateTime.now()) &&
_token != null) {
return _token;
}
return null;
}
Future<void> _authenticate(
String email, String password, String urlSegment) async {
final url =
'https://identitytoolkit.googleapis.com/v1/accounts:$urlSegment?key=AIzaSyCkNZysDY4PGpScw2jUlBpd0mvpGjgSEag';
try {
final response = await http.post(
url,
body: json.encode(
{
'email': email,
'password': password,
'returnSecureToken': true,
},
),
);
final responseData = json.decode(response.body);
if (responseData['error'] != null) {
throw HttpException(responseData['error']['message']);
}
_token = responseData['idToken'];
userId = responseData['localId'];
_expiryDate = DateTime.now().add(
Duration(
seconds: int.parse(
responseData['expiresIn'],
),
),
);
_autoLogout();
notifyListeners();
final prefs = await SharedPreferences.getInstance();
final userData = json.encode({
'token': _token,
'userId': userId,
'expiryDate': _expiryDate.toIso8601String(),
});
prefs.setString('userData', userData);
} catch (error) {
throw error;
}
}
//Auto Login Function
Future<bool> tryAutoLogin() async {
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('userData')) {
return false;
}
final extractedUserData =
json.decode(prefs.getString('userData')) as Map<String, Object>;
final expiryDate = DateTime.parse(extractedUserData['expiryDate']);
if (expiryDate.isBefore(DateTime.now())) {
return false;
}
_token = extractedUserData['token'];
userId = extractedUserData['userId'];
_expiryDate = expiryDate;
notifyListeners();
_autoLogout();
return true;
}
//SignUp function
Future<void> signUp(String email, String password) async {
return _authenticate(email, password, 'signUp');
}
//Login Function
Future<void> login(String email, String password) async {
return _authenticate(email, password, 'signInWithPassword');
}
//Logout Function
Future<void> logout() async {
_token = null;
userId = null;
_expiryDate = null;
if (_authTimer != null) {
_authTimer.cancel();
_authTimer = null;
}
notifyListeners();
final prefs = await SharedPreferences.getInstance();
prefs.clear();
}
//Auto Logout function
void _autoLogout() {
if (_authTimer != null) {
_authTimer.cancel();
}
final timeToExpiry = _expiryDate.difference(DateTime.now()).inSeconds;
_authTimer = Timer(Duration(seconds: timeToExpiry), logout);
}
//PHP related functions
}
Thank you in advance.
I agree with #lyio, you need to modify the function to pass the context, however after passing context, you cannot call it from initState as stated in documentation of initState
BuildContext.dependOnInheritedWidgetOfExactType from this method. However, didChangeDependencies will be called immediately following this method, and BuildContext.dependOnInheritedWidgetOfExactType can be used there.
Getting provider with Provider.of(context) under the hood is using the inherited widget, so cannot be called using context from initState
So implement instead of initState use didChangeDependencies to call your fetchStudentsInfo(context) method
Wouldn't the easiest solution be to pass the context into fetchStudentInfo?
You would change fetchStudentInfo() to fetchStudentInfo(BuildContext context). And then, when you call the method you pass in the required context. That way, you have the appropriate context available.
If you are not using the `fetchStudentInfo()` outside of the state class, then just move that method into the state class and the issue will be resolved.
Since Any state class has a context getter defined by default./
I just realized how improper this answer was.
Update:
According to the answer by #dlohani, didChangeDependencies should be used in stead of initState.
So what you can do is following:
Pass BuildContext as parameter in the fetchStudentInfo method
Override didChangeDependencies in state class & call fetchStudentInfo from here instead of initState