Home > database >  Flutter - How can I redirect the screen if the json response is null?
Flutter - How can I redirect the screen if the json response is null?

Time:05-02

I have this code I want to redirect the screen in login page if the result is null, the current user will match in my database.

My logic is if Firebase current user email is equal to email from local data render the results IF no match it will redirect to login screen.

Future<Album> fetchAlbum(String email) async {
final response = await http.get(Uri.parse(
    'http://localhost/devph.io/api/student_auth/?student=${email}'));

if (response.statusCode == 200) {
  return Album.fromJson(jsonDecode(response.body));

  //redirect the screen in login page if the result is null

} else {
  
  throw Exception('Failed to load album');
}}

Thank you guys.

CodePudding user response:

You can simply navigate to the new screen with the replacement method so that the user cannot go back to the previous screen.

Future<Album> fetchAlbum(String email) async {
final response = await http.get(Uri.parse(
    'http://localhost/devph.io/api/student_auth/?student=${email}'));

if (response.statusCode == 200) {
  var data = jsonDecode(response.body);
  if (data["studentEmail"] == "") {
    Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) => LoginPage()));
  }
  return Album.fromJson(data);

  //redirect the screen in login page if the result is null

} else {
  throw Exception('Failed to load album');
}}

CodePudding user response:

My API

$sql = "SELECT *  FROM `student` WHERE `student_email` = '$email' ";
$result = $connect->query($sql);

$json = array();
if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
                $theuser = array(
                        'id' => $row['id'],
                        'studentEmail' => $row['student_email'],
                );
                array_push($json, $theuser);
        }
} else {
        $theuser = array(
                'id' => 0,
                'studentEmail' => '',
                
        );
}


header('Content-type: application/json');
$jsonstring = json_encode($theuser, JSON_NUMERIC_CHECK);
echo $jsonstring;

$connect->close();
  • Related