mducc
mducc

Reputation: 743

Navigator.push() loop forever

I'm making a LoginScreen, in LoginScreen i check data in database for know user logged or not for each times open app. If user logged, the app will switched to HomeScreen.

I have a problem, i had logged in LoginScreen and then the app switched to HomeScreen. But my app's not standing in HomeScreen, it's continuing push new HomeScreen and looping this push action.

My code:

goToHomeIfAvailable() async {
    // Go to HomeScreen if available
    if (await this._databaseProvider.tokenTableIsEmpty() == false) {
      print('Logged');
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => HomeScreen()),
      );
    }
  }

@override
  Widget build(BuildContext context) {
    // In first times user open app=> create DB and go to HomeScreen if available
    _databaseProvider.openOrCreate().then((_) async {
      await goToHomeIfAvailable();
    });

    /* Return a widget bellow */
}

DatabaseProvider.dart:

class DatabaseProvider {
  String _path = 'O2_DB.db';
  Database _database;
  Map _tableName = {'token': 'token_tbl'};

  Future openOrCreate() async {
    this._database = await openDatabase(this._path, version: 1,
        onCreate: (Database db, version) async {
      await db.execute('CREATE TABLE IF NOT EXISTS ' +
          this._tableName['token'] +
          ' (token_id integer primary key autoincrement, token text)');
    });
  }
}

Upvotes: 1

Views: 698

Answers (1)

anmol.majhail
anmol.majhail

Reputation: 51186

Build is called many times during the app life cycle - & its better to always put our logic outside build method. Its normal Behavior.

In your case - As build was called each time the method - goToHomeIfAvailable() was called hence multiple push.

Moving goToHomeIfAvailable() out of build to initState() will solve the issue.

Upvotes: 2

Related Questions