I want to store two data(user,password) from two textfields using shared preference package in flutter
I created a function
saveData(String Name, String pass) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(Name, pass);
}
Now I want to get the data from two textFields
class Login extends StatefulWidget {
const Login({super.key});
@override
State<Login> createState() => _LoginState();
}
class _LoginState extends State<Login> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('LOGIN'),
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(25.0),
child: Container(
height: 300,
width: 500,
color: Colors.black12,
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Column(
children: [TextField(), TextField()],
),
),
),
)
],
),
);
}
}
4
Answers
try initialize 2x controller
final nameController = TextEditingController();
final psswdController = TextEditingController();
in nex step add this controller to Text area like:
…
And when need get data from this areas call:
nameController.text
psswdController.text
like simple:
First of all, to store data in shared preference, you have to store it like a key value pair. Your saveData method should look like this,
To get the value from textField you have to use textEditingController. To get more information you can follow this link
How to get the TextField value in flutter
I’m Trying to Solve your problem :
Create a button to save the data and two TextFields for users to enter their usernames and passwords:
You can use the getString() method to get the saved data Like This :
You can’t saved name and password like that.
prefs.setString
have parameter key and value. Key for accessing the value of sharedprefs.ex:
so, from your code above you need to adjust
and add TextFieldController for each textfield
then you can call
saveData()
from buttonso when you access name and pass