Saving changing variable value in flutter - flutter

I want to save a variable's value that changes every 5 seconds then read it. I have already tried saving it to shared preferences then reading it but the problem with that was that the value was only saved one time and did not save the changes done to the variable. Is there a way to implement that in flutter?
class _MyAppState extends State<MyApp> {
void initState() {
super.initState();
Future.delayed(Duration.zero, () {
_connect();
});
}
...
void predict(List<double> v) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List<List<double>> L=List<List<double>>.filled(1, [0], growable: true);
L[0]=v;
...
String res=response.body;
Map R = json.decode(res);
var _list = R.values.toList();
print(res);
Proba= double.parse(_list[1]);
await prefs.setDouble('Proba', Proba);
}
....
class Page extends StatefulWidget {
Page({Key key, this.title}) : super(key: key);
final String title;
#override
PageState createState() => PageState();
}
class PageState extends State<Page> {
.....
Future<double> _getProbaFromSharedPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getDouble("Proba") ?? 0;
}
#override
void initState() {
super.initState();
Location1=_getCurrentLocation();
_getStringFromSharedPref();
_getProbaFromSharedPref().then((s) {
Value = s;
});
Future.delayed(Duration.zero, () {
_check();
});
}
}
In the code I tried saving the variable in sharedPreferences then reading it, but I have no clue on how to reload it everytime it changes.

Related

fetching data. for user from firebase for flutter gives null

After i have created the sign in and signup in flutter and i have connect it to firebase, i added a textfield for the name of the user. So if the user register his name also will be stored, then this data is saved into firebase with the id of the user. The problem is when i try to fetch this data my these method it gives me null ,
This is the way how i am fetching the data of the user :
class WelcomePage extends StatefulWidget {
String email;
WelcomePage ({Key? key, required this.email}) : super(key: key);
#override
State<WelcomePage> createState() => _WelcomePageState();
}
class _WelcomePageState extends State<WelcomePage> {
ScrollController? _scrollcontroller;
final FirebaseAuth _auth =FirebaseAuth.instance;
String? _name ;
String? _uid;
#override
void initState() {
super.initState();
_scrollcontroller = ScrollController();
_scrollcontroller?.addListener(() {
setState(() {});
});
getData();
}
void getData() async{
User? user = _auth.currentUser;
_uid = user!.uid;
final DocumentSnapshot userDoc =
await FirebaseFirestore.instance.collection('users').doc(user.uid).get();
_name = userDoc.get('name');
}

"'key' is required, but there's no corresponding argument" flutter error

How to solve this error?
The named parameter 'key' is required, but there's no corresponding argument. (Documentation) Try adding the required argument.
error
Future<void> onJoin() async {
// update input validation
setState(() {
_channelController.text.isEmpty
? _validateError = true
: _validateError = false;
});
if (_channelController.text.isNotEmpty) {
await _handleCameraAndMic(Permission.camera);
await _handleCameraAndMic(Permission.microphone);
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoCall(
channelName: _channelController.text,
role: _role,
),
),
);
}
}
class VideoCall
class VideoCall extends StatefulWidget {
final String channelName;
final ClientRole role;
const VideoCall({Key key, required this.channelName, required this.role})
: super(key: key);
#override
_VideoCallState createState() => _VideoCallState();
}
class _VideoCallState extends State<VideoCall> {
final _users = <int>[];
final _infoStrings = <String>[];
bool muted = false;
late RtcEngine _engine;
#override
void dispose() {
// clear users
_users.clear();
// destroy sdk
_engine.leaveChannel();
_engine.destroy();
super.dispose();
}
#override
void initState() {
super.initState();
// initialize agora sdk
initialize();
}
this is the videoCall class in there no any error shows.
when add "key" show this
When remove required property from key in video call class
show this error
In VideoCall class, key property set as a required, change it to optional:
class VideoCall extends StatefulWidget {
final String? channelName;
final ClientRole? role;
const VideoCall({Key? key, this.channelName, this.role})
: super(key: key);
#override
_VideoCallState createState() => _VideoCallState();
}

LateError (LateInitializationError: Field 'gP1' has not been initialized.)

Can someone explain to me where I am wrong? I am programming this application and, working with sqflite, I have had this kind of problem several times when I use the readPlayer() function.
class matchesRow extends StatefulWidget {
final List matches;
final List results;
final int index;
matchesRow({
Key? key,
required this.index,
required this.matches,
required this.results,
}) : super(key: key);
#override
State<matchesRow> createState() => _matchesRowState();
}
class _matchesRowState extends State<matchesRow> {
late Player gP1;
late Player gP2;
bool ripescato = false;
PlayersDatabase pb = PlayersDatabase.instance;
#override
void initState() {
super.initState();
getPlayers();
}
#override
void dispose() {
PlayersDatabase.instance.close();
super.dispose();
}
Future getPlayers() async {
List<dynamic> duel = widget.matches[widget.index];
gP1 = await pb.readPlayer(duel[0]);
print(gP1);
gP2 = await pb.readPlayer(duel[0]);
if (duel[1] == "R") {
ripescato = true;
} else {
gP2 = await pb.readPlayer(duel[1]);
}
}
#override
Container build(BuildContext context) {
var icon = Icons.code_sharp;
return Container(child: Text(gP1.name));
}}
This is the function ReadPlayer()
Future<Player> readPlayer(int id) async {
final db = await instance.database;
final maps = await db.query(
tablePlayers,
columns: PlayerFields.values,
where: '${PlayerFields.id} = ?',
whereArgs: [id],
);
if (maps.isNotEmpty) {
return Player.fromJson(maps.first);
} else {
throw Exception('ID $id not found');
}
I don't understand why even if I declare the value of gP1 and gP2 in getPlayers() the error still pop up.
gP1 and gP2 getting from future method. It will take some time to fetch data from future method getPlayers. Use FutureBuilder or make it nullable
For nullable case it will be
Player? gP1;
Player? gP2;
#override
void initState() {
super.initState();
getPlayers().then((value) {
//update Ui after getting data
setState(() {});
});
}
And use case with default value on null case
Text(gP1?.name??"didnt get yet")

Problems with shared preference-flutter

I wanna ask how to save state from textfield? cause i can't saving this state, after hot restart my value always reset, i just want to save state after hot restart, can i know my problem where it's wrong?
it's my code:
class HomePage extends StatefulWidget {
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
TextEditingController nameController = TextEditingController();
var nama = 'nama';
void setPref() async {
var prefs = await SharedPreferences.getInstance();
prefs.setString(nama, nameController.text);
}
void load() async {
var prefs = await SharedPreferences.getInstance();
setState(() {
nama = prefs.getString(nameController.text) ?? '';
nameController.text = nama;
});
}
#override
void initState() {
// TODO: implement initState
super.initState();
load();
}
#override
Widget build(BuildContext context) {
.....
}
}
There is a problem in your code:
In shared Prefrences you have to use key to store and get value.
But you are using it in wrong way:
Here is correct code:
void load() async {
var prefs = await SharedPreferences.getInstance();
String value = '';
setState(() {
value= prefs.getString(nama) ?? '';
nameController.text = value;
});
}
The nama is a key name and you are also using it to receive value. And the key you are using is nameController.text is also wrong.
Bonus
The convection of writing keys in Flutter is Following:
String nameKey = 'NAMEKEY';

how to access to variable from StatefulWidget to State class flutter

I try to pass data from page one to page two data is pass OK but I have one problem now.
this is my code:
class SecondScreen extends StatefulWidget {
final int itemHolder ;
SecondScreen({Key key, #required this.itemHolder}) : super(key: key);
#override
State<StatefulWidget> createState() {
return new mainState();
}
}
class mainState extends State <SecondScreen> {
bool value = false ;
MyPreferences _myPreferences = MyPreferences();
#override
void initState() {
// TODO: implement initState
super.initState();
initial();
}
void initial() async {
setState(() {
});
}
final String apiURL = 'http://xxxxxxxxx/getFlowersList.php';
Future<List<Flowerdata>> fetchFlowers() async {
var response = await http.get(apiURL);
if (response.statusCode == 200) {
final items = json.decode(response.body).cast<Map<String, dynamic>>();
List<Flowerdata> listOfFruits = items.map<Flowerdata>((json) {
return Flowerdata.fromJson(json);
}).toList();
return listOfFruits;
}
else {
throw Exception('Failed to load data from Server.');
}
}
I try to use var (itemHolder ) in the link like that:
final String apiURL = 'http://xxxxxxx/getFlowersList.php?id=' +itemHolder;
but I get error:
Undefined name 'itemHolder'. Try correcting the name to one that is defined, or defining the name.
I can access to itemHolder. So how can I access to it?
try this:
...
String apiURL;
#override
void initState() {
super.initState();
apiURL = 'http://xxxxxxx/getFlowersList.php?id=' +widget.itemHolder.toString();
}
...
To use the variables declared in the SecondScreen you have to access it with the prefix 'widget' and the dot operator, not directly. Here is the code:
final String apiURL = 'http://xxxxxxx/getFlowersList.php?id=' + widget.itemHolder;
And when you make the variable final, you have to initialize it while declaration or through constructor else delete keyword final: