Home > Net >  Flutter Shared Preferences
Flutter Shared Preferences

Time:09-27

Guys how to transfer data when I login.. For example when I login the transfer data are User ID, email and password.. So if I want to add something that requires the user id how do I call it?

This is my login method

 void login() async {
if(passController.text.isNotEmpty && emailController.text.isNotEmpty) {
  var response = await http.post(
      Uri.parse("url"),
      body: ({
        'email': emailController.text,
        'password': passController.text,
      }));
  if (response.statusCode == 200) {
    final body = jsonDecode(response.body);
    print(body.toString());
    List<dynamic> data = body["Details"];
    print(data[0]['email']);
    pageRoute(data[0]['name']);
  } else {
    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text("Wrong password")));
  }
} else {
    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text("Sila isi tempat kosong")));
  }
}

void pageRoute(data) async { //STORE VALUE IN SHARED PREFERENCES

SharedPreferences pref = await SharedPreferences.getInstance();
await pref.setString("login", data);
Navigator.of(context).pushAndRemoveUntil(
    MaterialPageRoute(builder: (context) => nav()),
        (route) => false);

This is where I want to take the user id without put it on the textfield.

    import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;

import '../Utils/lib.dart';

class CarList extends StatefulWidget {
  const CarList({Key? key}) : super(key: key);

  @override
  State<CarList> createState() => _CarListState();
}

class _CarListState extends State<CarList> {

  var userController = TextEditingController();
  // late SharedPreferences logindata;
  //  String? Email;
  final pref = Pref();

  // late String name;
  // late String registeration_no;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initial();
  }

  void initial() async {
    if (pref.isLogin()) {
      final body = jsonDecode(pref.getLogin());
      print(body['Details']['user_id'].toString());
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
          children: <Widget>[
            Container(
          padding: const EdgeInsets.all(10),
          child: TextField(
            controller: userController,
            decoration: const InputDecoration(
              border: OutlineInputBorder(),
              suffixIcon: Icon(Icons.email),
              labelText: 'User ID',
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.all(25),
          child: TextButton(
            child: Text('test',
              style: TextStyle(fontSize: 20.0,
                  color: Colors.blueAccent,
                  backgroundColor: Colors.white),
            ),
            onPressed: () {
              list();
            },
          ),
        )
    ]
      )
    );
  }

  void list() async {
    {
      var response = await http.post(
          Uri.parse("url"),
          body: ({
            'user_id': userController.text,
          }));
      if (response.statusCode == 200) {
        final body = jsonDecode(response.body);
        // final SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
        // sharedPreferences.setString('email', emailController.text);
        pref.saveLogin(true, response.body);
        print(body.toString());
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text("Successfully Login")));
      }
    }
  }
}

Im kinda new with this flutter so might thankful with your help

CodePudding user response:

You can do something like this:

This is store data in pageRoute.

void login() async {
    if (passController.text.isNotEmpty && emailController.text.isNotEmpty) {
      var response = await http.post(
          Uri.parse("http://servisjer.me-tech.com.my/api/Login"),
          body: ({
            'email': emailController.text,
            'password': passController.text,
          }));
      if (response.statusCode == 200) {
        final body = jsonDecode(response.body);
        print(body.toString());
        List<dynamic> data = body["Details"];
        print(data[0]['email']);
        pageRoute(Data(data[0]['email'], data[0]['user_id']));
      } else {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text("Wrong password")));
      }
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text("Sila isi tempat kosong")));
    }
  }

  void pageRoute(Data data) async {
    MySharedPreferences().storeUser(data);
    Navigator.of(context).pushAndRemoveUntil(
        MaterialPageRoute(builder: (context) => nav()), (route) => false);
  }

MySharedPreferences

class MySharedPreferences {
  Future<void> storeUser(Data data) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString("email", data.email);
    prefs.setInt("user_id", data.userId);
  }

  Future getUserId() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var userId = prefs.getInt("user_id");
    return userId;
  }
}

In CarList, retrieve data using this way

  @override
  void initState() {
    MySharedPreferences().getUserId().then((value) {
      setState(() {
        userController.text = value.toString();
      });
    });
    //TODO: IMPLEMENT INITSTATE
    super.initState();
  }   

Data

class Data {
  var email;
  var userId;

  Data(this.email,this.userId);
}
  • Related