This is a login, that catch user data and write in the other pages, like his name, etc
I set sharedPreference here:
Future<bool> login() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
SharedPreferences nome = await SharedPreferences.getInstance();
var email = _emailController.text;
var senha = _senhaController.text;
var auth = 'Basic ' base64Encode(utf8.encode('$email:$senha'));
var url = Uri.parse("http://177.70.102.109:3005/autenticacao");
var resposta = await http.get(
url,
headers: (<String, String>{'authorization': auth}),
);
// List campos = [];
if (resposta.statusCode == 200) {
await sharedPreferences.setString(
'token', "Token ${jsonDecode(resposta.body)['token']}");
await nome.setString(
'nome', "${jsonDecode(resposta.body)['result'][0]['nome']}");
print(nome);
return true;
} else {
return false;
}
}
And i want to receive and pass the 'nome' to a TextWidget in another class.
CodePudding user response:
In the other page you can write something like that:
class ExamplePage extends StatefulWidget {
const ExamplePage({Key? key}) : super(key: key);
@override
State<ExamplePage> createState() => _ExamplePageState();
}
class _ExamplePageState extends State<ExamplePage> {
final _controller = TextEditingController();
@override
void initState() {
initNome();
super.initState();
}
Future<void> initNome() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
String _nome = sharedPreferences.getString("nome", "");
_controller.text = _nome;
}
@override
Widget build(BuildContext context) {
return Text(_controller.text)
}
}
CodePudding user response:
To read the value in some other widget you can use
Implementation would be similar to this:
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
Text(sharedPreferences.getString("nome");
See this post for example: Flutter Shared Preference in Text Widget