I'm trying to have an initial text (of my choice) at first and if the user changes it, it should save in Shared Preferences and load as initial text next time in a TextField.
Edited code a bit but it's still same, I think I'm going wrong somewhere with Shared Preferences.
String initialSignatureText = 'Sent from Mail';
TextEditingController _signatureController = TextEditingController();
String signatureText;
void convertSignature(){
String convertedSignature = _signatureController.text;
setSignature(convertedSignature);
}
void setSignature(String convertedSignature) async{
SharedPreferences signPrefs = await SharedPreferences.getInstance();
signPrefs.setString('signatureTextKey', convertedSignature);
}
Future<String> getSignature() async {
SharedPreferences signPrefs = await SharedPreferences.getInstance();
signatureText = signPrefs.get('signatureTextKey');
print(signatureText);
return signatureText;
}
#override
Widget build(BuildContext context) {
_signatureController.text = signatureText;
TextField(
maxLines: 1,
style: TextStyle(
color: Theme.of(context).textTheme.title.color,
fontSize: 18
),
controller: _signatureController,
showCursor: true,
),
FlatButton(
child: Text('Ok'),
onPressed: (){
convertSignature();
Navigator.pop(context);
},
)
You can assign any string to the text property of your controller
_signatureController.text = "any string";
The second way to do this would be to use TextFormField, It provides you with intialValue property.
I got it. I've not implemented to load initialSignatureText for first time, I'll do it later.
TextEditingController _signatureController = TextEditingController();
String initialSignatureText = 'Sent from Mail.';
var signatureText;
void convertSignature(){
String convertedSignature = _signatureController.text;
setSignature(convertedSignature);
}
void setSignature(String convertedSignature) async{
SharedPreferences signPrefs = await SharedPreferences.getInstance();
signPrefs.setString('signatureTextKey', convertedSignature);
}
Future<String> getSignature() async {
SharedPreferences signPrefs = await SharedPreferences.getInstance();
signatureText = signPrefs.get('signatureTextKey');
return signatureText;
}
void initState() {
super.initState();
getSignature();
WidgetsBinding.instance.addPostFrameCallback((_) async {
_signatureController.text = await getSignature();
});
}
Related
I am having a widget in the flutter which can be dismissed by watching a rewarded video. But I don't want the widget to be completely dismissed. Say for 3 days.
So if the user clicks on the specific widget then the ads will be disabled for 3 days. Is it possible to do? Could someone help me with references or ideas to get this done?
Please help
First, Get shared preferences Package to make local storage to track the Date shared_preferences: ^2.0.5
Make A Local Storage like this -
import 'package:shared_preferences/shared_preferences.dart';
class SetUserLocalStorage {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
void date(String valueOfDate) async {
final SharedPreferences prefs = await _prefs;
prefs.setString(UserStorageKey().valueOfDate, valueOfDate);
}
void clear() async { // For Your Further Operation, If needed
final SharedPreferences prefs = await _prefs;
prefs.clear();
}
}
class GetUserLocalStorage {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<String> date() async {
final SharedPreferences prefs = await _prefs;
return prefs.getString(UserStorageKey().valueOfDate);
}
}
class UserStorageKey {
String get valueOfDate => "valueOfDate";
}
Now, in your page / Screen, Define Variable -
bool _showTheAd = false;
DateTime _now = DateTime.now();
DateTime _date = DateTime.now();
and In InitState, Start Checking the Condition on the base of Time,I am making it in three part for better understanding
#override
void initState() {
super.initState();
_initialPoint();
}
in _initialPoint() -
void _initialPoint() async {
await GetUserLocalStorage().date().then((value) {
setState(() {
_date = DateTime.parse(value);
});
}).then((value) {
_conditionCheck();
});
}
In _conditionCheck -
void _conditionCheck() {
if (_date == null) {
setState(() {
_showTheAd = true;
});
} else {
setState(() {
_now = DateTime.now();
});
if (_now.isAfter(_date)) {
setState(() {
_showTheAd = true;
});
}
}
}
I know that,these are like "dirty code", but I think that will help you understand the scenario.
in body, show the add based on the _showTheAd condition, and use some interceptor / listener of kind to sense when the video is end,I am using an inkwell, and execute the code in onTap(), full scenario -
Container(
child: Column(
children: [
if (_showTheAd)
InkWell(
onTap: () {
setState(
() {
_date = _now.add(
Duration(seconds: 5),
); // to add Date _now.add(Duration(days:3));
},
);
SetUserLocalStorage().date(_date.toIso8601String());
},
child: Center(
child: Container(
height: 120,
width: 120,
color: Colors.red,
child: Text("the ad"),
),
),
)
],
),
),
SharedPreferences prefs;
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Above is how it is initialized
prefs.setString('emailPrefs1', email).then((bool success) {
print('${prefs.getString('emailPrefs1')}');
});
Value is set successfully after this
_getPrefs() async {
prefs = await _prefs;
String emailPrefs1 = prefs.getString('emailPrefs1');
if (emailPrefs1 != null) {
setState(() {
emailController.text = emailPrefs1;
});
}
print(emailPrefs1);
}
But it returns null after initializing this activity in init state.
#override
void initState() {
super.initState();
_getPrefs();
}
I am using shared_preferences: ^0.5.6 version.
if you are sure your 'emailPref' is set, this should work:
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _emailController;
SharedPreferences _prefs;
Future<SharedPreferences> _getPrefs() async{
return await SharedPreferences.getInstance();
}
#override
void initState(){
super.initState();
_emailController = TextEditingController();
_getPrefs().then((prefs){
_prefs = prefs; //If you need your SharedPreference Object later on
_emailController.text = prefs.getString('emailPrefs1');
setState(() {});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(child: Text(_emailController.text))
);
}
#override
void dispose() {
super.dispose();
_emailController.dispose();
}
}
How is the private _prefs being initialized? You can either share more of your code or just pull the value from what you definitely saved to.
void getPrefs() async {
prefs = await SharedPreferences.getInstance(); // this is what you saved to
String emailPrefs1 = prefs.getString('emailPrefs1');
print(emailPrefs1);
if (emailPrefs1 != null) {
setState(() {
emailController.text = emailPrefs1;
});
}
}
You can also print the value straight from the instance when you do save to confirm a successful save.
prefs.setString('emailPrefs1', email).then((bool success) {
print('${prefs.getString('emailPrefs1')}');
});
Hello I try to use this timeline package.
https://github.com/softmarshmallow/flutter-timeline
It's work fine to create timeline after press button but I don't success to save events with sharedpreference. I would like to restore history of the timeline at the initState.
TimelineEventDisplay get plainEventDisplay {
return TimelineEventDisplay(
child: TimelineEventCard(
title: Text("just now"),
content: Text("someone commented on your timeline ${DateTime.now()}"),
),
indicator: TimelineDots.of(context).circleIcon);
}
List<TimelineEventDisplay> events;
Widget _buildTimeline() {
return TimelineTheme(
data: TimelineThemeData(lineColor: Colors.blueAccent),
child: Timeline(
indicatorSize: 56,
events: events,
));
}
void _addEvent() {
setState(() {
events.add(plainEventDisplay);
});
}
#override
void initState() {
events = [
plainEventDisplay,
];
}
Create a SharedPref class so that it would be easy for you to manage things.
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
class SharedPref {
read(String key) async {
final prefs = await SharedPreferences.getInstance();
if(prefs.getString(key) == null){
return null;
}
final map = jsonDecode(prefs.getString(key));
return map;
}
save(String key, value) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(key, jsonEncode(value));
}
remove(String key) async {
final prefs = await SharedPreferences.getInstance();
prefs.remove(key);
}
}
In your Flutter widget, create initState as follows:
SharedPref _prefs = SharedPref();
final events;
#override
void initState() async {
super.initState();
events = await _prefs.read('events');
}
void _addEvent() async {
setState(() {
events.add(plainEventDisplay);
});
await _prefs.save('events', events);
}
i was able to get current location using geolocator, but i want to cache and restore the string address without using lastKnownLocation in geolocator. im using shared preferences but cannot make it work. i used shared preference several times on my other codes, but with geolocator its kind of complicated. and im super new to flutter/dart
code:
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
Position _currentPosition;
String _currentAddress;
String _locationCache;
String key = "location_cache";
#override
void initState() {
super.initState();
_getCurrentLocation();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("current location = " + _currentAddress),
Text("last location = " + __locationCache) // HERE GET STORED DATA ISNT WORKING
],
),
),
);
}
_getCurrentLocation() {
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
_getAddressFromLatLng();
}).catchError((e) {
print(e);
});
}
_getAddressFromLatLng() async {
try {
List<Placemark> p = await geolocator.placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
_currentAddress = "${place.country}";
});
saveAddress();
} catch (e) {
print(e);
}
}
Future<bool> saveAddress() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return await prefs.setString(key, _currentAddress);
}
Future<String> retrieveAddress() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return String
return prefs.getString(key) ?? "";
}
loadAddress() {
retrieveAddress().then((value) {
setState(() {
_locationCache = value;
});
});
}
}
heres the working code without _locationCache:
Thank you for your time
If I understood you correctly, what you want to accomplish is to store the last address you caught and retrieve it if you don't have gps active.
To do so you could use SharedPreferences or SQLite, just check the documentation on how to use them.
found the solution. just replace loadAddress() function with
void save() {
String address = _currentAddress;
saveAddress(address);
}
void _updateName(String address) {
setState(() {
this.locationCache = address;
});
}
and then put retrieveAddress().then(updateName) inside initState()
I am new in flutter.I try to learn SharedPreferences and i have this exception.
How can i solve this?
class _MyAppState extends State {
Future<SharedPreferences> prefs = SharedPreferences.getInstance();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
RaisedButton(
onPressed: () {addStringToSF();},
),
Text(getStringValuesSF()),
],
),
);
}
addStringToSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('stringValue', "abc");
}
getStringValuesSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String stringValue = prefs.getString('stringValue');
return stringValue;
}
}
default async function return dynamic we have to do type casting
Future<String> getStringValuesSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String stringValue = prefs.getString('stringValue');
return stringValue;
}
I will just extend answer from #Abhishek as I needed similar but didn't work as epxected on TextFormField.
So I made up a bare loadString method to get any kind of key from sharedPrefs:
Future<String> loadString(String key) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString(key) ?? '';
}
Next in the same class I created init form void to use above method (I still think this way of working with Future is bit not optimal in Dart, anyway..), this will load data into controller:
Future<void> _initForm() async {
final clientBusinessRegistrationID = await loadString('clientBusinessRegistrationID');
_clientBusinessRegistrationIDController.value =
_clientBusinessRegistrationIDController.value.copyWith(
text: clientBusinessRegistrationID);
}
I also added this block in same class:
SharedPreferences? preferences;
Future<void> initializePreference() async{
preferences = await SharedPreferences.getInstance();
}
and finally in initState() I call it and it works:
#override
void initState() {
super.initState();
// setupLocator();
initializePreference().whenComplete((){
setState(() {});
});
_clientBusinessRegistrationIDController.text = 'Initial';
_initForm();
}