BIS Tech
BIS Tech

Reputation: 19444

How to fix this For loop not working error? for loop only work once in Flutter

How to fix this For loop not working error? for loop only work once in Flutter

It's a simple login form. If username and password matched go to user page else go to admin page.

method code:

checkLogin(){
  setState(() {
  for(var c=0;c < global.user_name_arr.length-1 ; c++){
   if(global.user_name_arr[c]==myController.text&&global.user_password_arr[c]==myControllerPwd.text)

        Navigator.push(context, MaterialPageRoute(builder: (context)=>user()),);
      else
        Navigator.push(context, MaterialPageRoute(builder:(context)=>admin()),);   }    
 }); }

RaiseButton code:

new RaisedButton(
                  child:new Text("Click"),
                  onPressed:checkLogin, 
                )

global.dart

library user_login.globlas;

var user_name_arr=['bhanuka','isuru','sampath'];
var user_password_arr=['1234','123','12'];

Upvotes: 0

Views: 1724

Answers (2)

aubykhan
aubykhan

Reputation: 264

First off, let's refactor your code :) Create a user class like so:

class User {
  final String name;
  final String password;

  User(this.name, this.password); 
}

Next, fix your global user collection:

final validUsers = [User('bhanuka', '1234'), User('isuru', '123'), User('sampath', '12')];

Now, use this code to perform correct navigation:

checkLogin() {
  if (validUsers.indexWhere((user) => user.name == myController.text && user.password == myControllerPwd.text) >= 0) {
    Navigator.push(context, MaterialPageRoute(builder: (context)=>user()),);
  } else {
    Navigator.push(context, MaterialPageRoute(builder:(context)=>admin()),);   
  }         
}

There are better ways to do this comparison but I guess it's good enough for your use case.

Upvotes: 1

Viren V Varasadiya
Viren V Varasadiya

Reputation: 27137

here you are using if else so that condition is right or wrong one of the part is executed.

   import 'package:flutter/material.dart';

void main() => runApp(new MaterialApp(
      title: 'Forms in Flutter',
      home: new LoginPage(),
    ));

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _LoginPageState();
}

class _LoginData {
  String email = '';
  String password = '';
}

class _LoginPageState extends State<LoginPage> {
  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  _LoginData _data = new _LoginData();
  var user_name_arr = ['bhanuka', 'isuru', 'sampath'];
  var user_password_arr = ['1234', '123', '12'];
  var p;
  void submit() {
    if (this._formKey.currentState.validate()) {
      _formKey.currentState.save(); // Save our form now.
      if (user_name_arr.contains(_data.email)) {
        p = user_name_arr.indexOf(_data.email);
        if (user_password_arr.elementAt(p) == _data.password) {
          Navigator.push(context, MaterialPageRoute(builder: (context)=>user()),);
        } else {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => admin()),
          );
        }
      } else {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => admin()),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final Size screenSize = MediaQuery.of(context).size;

    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Login'),
      ),
      body: new Container(
          padding: new EdgeInsets.all(20.0),
          child: new Form(
            key: this._formKey,
            child: new ListView(
              children: <Widget>[
                new TextFormField(
                    keyboardType: TextInputType
                        .emailAddress, // Use email input type for emails.
                    decoration: new InputDecoration(
                        hintText: '[email protected]',
                        labelText: 'E-mail Address'),
                    onSaved: (String value) {
                      this._data.email = value;
                    }),
                new TextFormField(
                    obscureText: true, // Use secure text for passwords.
                    decoration: new InputDecoration(
                        hintText: 'Password', labelText: 'Enter your password'),
                    onSaved: (String value) {
                      this._data.password = value;
                    }),
                new Container(
                  width: screenSize.width,
                  child: new RaisedButton(
                    child: new Text(
                      'Login',
                      style: new TextStyle(color: Colors.white),
                    ),
                    onPressed: this.submit,
                    color: Colors.blue,
                  ),
                  margin: new EdgeInsets.only(top: 20.0),
                )
              ],
            ),
          )),
    );
  }
}

class user extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(child: new Text("user")),
      ),
    );
  }
}

class admin extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(child: new Text("admin")),
      ),
    );
  }
}

Upvotes: 0

Related Questions