How to connect and run Flutter Web Application (Flutter + PHP + Mysql Xampp DB Server)

Viewed 74

i want to connect my flutter web app to database using php-mysql server(xampp). but, it won't show any errors and as well as not getting any kind of output. Please help me to solve this.

1) The below code is fine and not having any errors.

2) The data in the database & the database values are also created and everything is good.

3) I used VS Code IDE to write & develop this application. How to run my Flutter-PHP web app, running from inide the "xampp/htdocs/.." folder (or) outside of the "xampp/htdocs/.." folder ??

4) Where can i put and run the 'login.php' file in my scenario for my/this flutter web application ??

And one more thing is, If I run the "login.php" file DIRECTLY from "xampp/htdocs/.." location in xampp server, then it will show the error in browser like this (Observe last image below).

And My target output is, if i/user enter the login email & password in login page, then it will check & compare the login detail from the DB then the login detail are valid, it will login successfully and redirects to home page of the user, otherwise it show the "Login Failed" error message.

main.dart :

//Flutter code starts from here...
void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SSS - CRM',
      debugShowCheckedModeBanner: false, //to remove 'Debug' tag.
      theme: ThemeData(
        primarySwatch: Colors.blueGrey,
      ),
      home: const MyHomePage(title: 'SSS'),
    );
    //body:const MyCustomForm();
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  //int _counter = 0;
  //bool _isVisible = true;
  //bool passenable = true;
  //bool show = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 35,
        title: Text(widget.title),
        leading: IconButton(
          icon: Image.asset(
            '../lib/assets/images/logo.jpg',
            height: 45,
            width: 45,
          ),
          onPressed: () => exit(0),
        ),
      ),

//Body part starts from here...
      body: Padding(
        padding: const EdgeInsets.only(
          top: 70.0,
        ),
        //  child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Image.asset(
              '../lib/assets/images/logo.png',
              height: 300,
              width: 300,
            ),

//Login button code from here...
            Row(mainAxisAlignment: MainAxisAlignment.start, children: [
              const Padding(
                  padding:
                      EdgeInsets.symmetric(vertical: 60.0, horizontal: 310.0)),
              ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    foregroundColor: Colors.white, 
                    backgroundColor: Colors.blue,
                    minimumSize: const Size(130, 45),
                    maximumSize: const Size(130, 45),
                    shadowColor:
                        Colors.black, //specify the button's elevation color
                    elevation: 6.0,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20.0),
                      side: const BorderSide(width: 1, color: Colors.blueGrey),
                    ),
                  ),
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => const MyLoginPage(
                                title: 'SSS CRM',
                              )),
                    );
                  },
                  child: const Text(
                    'Login',
                    style: TextStyle(fontSize: 18),
                  )),
            ]),
          ],
        ),
        //),
      ),

//'Copyrights' code from here...
      bottomNavigationBar: const BottomAppBar(
          color: Colors.grey,
          child: SizedBox(
            width: 30.0,
            height: 30.0,
            child: Center(
                child: Text(
              "All rights are reserved @SSS - 2022",
              textAlign: TextAlign.center,
            )),
          )),
      //child: CircularProgressIndicator(),
    );
    //});
  }
}

login.dart :

class MyLoginPage extends StatefulWidget {
  const MyLoginPage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyLoginPage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyLoginPage> {
  //int _counter = 0;
  //bool _isVisible = false;
  //bool passenable = true;
  //bool show = true;
  TextEditingController email = TextEditingController();
  TextEditingController pass = TextEditingController();

  Future login() async {
    var url = Uri.http(
        '',
        'C:/xampp/htdocs/sss/lib/database/logics/login.php',
        {'q': '{http}'});
    var http;
    var flutterToast;
    var toast;
    var response = await http.post(url, body: {
      "email": email.text,
      "password": pass.text,
    });

    var data = json.decode(response.body);
    if (data.toString() == "Success") {
      flutterToast.showToast(
        msg: 'Login Successfull...!',
        backgroundColor: Colors.green,
        textColor: Colors.white,
        toastLength: toast.LENGTH_SHORT,
      );
      // ignore: use_build_context_synchronously
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => const HomePage(title: 'Prem'),
        ),
      );
    } else {
      flutterToast.showToast(
        msg: 'Email or Password is Invalid...!',
        backgroundColor: Colors.green,
        textColor: Colors.white,
        toastLength: toast.LENGTH_SHORT,
      );
    }
  }

  final scaffoldKey = GlobalKey<ScaffoldState>();
  final formKey = GlobalKey<FormState>();

  late String _email, _pass;

  _showSnackbar() {
    var snackBar = new SnackBar(content: Text("Login Successful"));

    //scaffoldKey.currentState.showSnackBar(snackBar);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
//AppBar code starts from here...
        key: scaffoldKey,
        appBar: AppBar(
          toolbarHeight: 35,
          title: Text(widget.title),
          leading: IconButton(
            icon: Image.asset(
              '../lib/assets/images/sss_logo.jpg',
              height: 45,
              width: 45,
            ),
            onPressed: () => exit(0),
          ),
        ),

//Body part starts from here...
        body: Padding(
          key: formKey,
          padding: const EdgeInsets.only(top: 120.0, bottom: 25.0),
          child: Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
//Box container code from here...
                  Column(
                    children: <Widget>[
                      Container(
                        height: 300.0,
                        width: 550.0,
                        decoration: BoxDecoration(
                            color: Colors.grey[300],
                            shape: BoxShape.rectangle,
                            borderRadius: BorderRadius.circular(20.0),
                            boxShadow: const [
                              BoxShadow(
                                  color: Colors.black,
                                  blurRadius: 2.0,
                                  offset: Offset(2.0, 2.0))
                            ]),

//'Login' heading code from here...
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            const Text("Login",
                                style: TextStyle(
                                    fontSize: 25,
                                    color: Colors.blue,
                                    fontFamily: 'Arial',
                                    fontWeight: FontWeight.bold,
                                    decoration: TextDecoration.underline,
                                    shadows: [
                                      Shadow(
                                          color: Colors.tealAccent,
                                          offset: Offset(2, 1),
                                          blurRadius: 5)
                                    ])),

//Email Input Box code from here...
                            Padding(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 50, vertical: 16),
                              child: TextFormField(
                                validator: (val) => val!.contains("@")
                                    ? "Email Id is not Valid"
                                    : null,
                                onSaved: (val) => _email = val!,
                                controller: email,
                                style: const TextStyle(color: Colors.black87),
                                decoration: const InputDecoration(
                                  //fillColor: Colors.red,
                                  border: OutlineInputBorder(),
                                  prefixIcon: Align(
                                    widthFactor: 1.0,
                                    heightFactor: 1.0,
                                    child: Icon(
                                      Icons.person,
                                    ),
                                  ),
                                  labelText: 'Email',
                                  //labelStyle: Style(),
                                  hintText: "Enter Email Id here",
                                  hintStyle: TextStyle(
                                    fontFamily: 'Lexend Deca',
                                    fontStyle: FontStyle.italic,
                                    color: Colors.grey,
                                    fontSize: 14,
                                    //fontWeight: FontWeight.normal,
                                  ),
                                ),
                              ),
                            ),

//Pasword Input Box code from here...
                            Padding(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 50, vertical: 16),
                              child: TextFormField(
                                onSaved: (val) => _pass = val!,
                                validator: (val) => val!.length < 6
                                    ? "Password length should be Greater than 6"
                                    : null,
                                controller: pass,
                                obscureText:
                                    true, //Remove this line to enable psw visibility
                                style: const TextStyle(color: Colors.black87),
                                decoration: const InputDecoration(
                                  border: OutlineInputBorder(),
                                  prefixIcon: Align(
                                    widthFactor: 1.0,
                                    heightFactor: 1.0,
                                    child: Icon(
                                      Icons.lock,
                                    ),
                                  ),
                                  labelText: 'Password',
                                  hintText: "Enter Password here",
                                  hintStyle: TextStyle(
                                    fontFamily: 'Lexend Deca',
                                    fontStyle: FontStyle.italic,
                                    color: Colors.grey,
                                    fontSize: 14,
                                    //fontWeight: FontWeight.normal,
                                  ),
                                ),
                              ),
                            ),

//Sign In button code from here...
                            Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: [
                                  ElevatedButton(
                                      style: ElevatedButton.styleFrom(
                                        foregroundColor: Colors.white,
                                        backgroundColor: Colors.blue,
                                        minimumSize: const Size(130, 45),
                                        maximumSize: const Size(130, 45),
                                        shadowColor: Colors
                                            .black, //Specify the button's elevation color
                                        elevation: 6.0,
                                        shape: RoundedRectangleBorder(
                                          borderRadius:
                                              BorderRadius.circular(20.0),
                                          side: const BorderSide(
                                              width: 1, color: Colors.blueGrey),
                                        ),
                                      ),
                                      onPressed: () {
                                        if (formKey.currentState!.validate()) {
                                          formKey.currentState?.save();
                                          _showSnackbar();
                                        }
                                      },
                                      child: const Text(
                                        'Sign In',
                                        style: TextStyle(fontSize: 18),
                                      )),
                                ]),

//'Forgott Psw' code from here...
                            Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: [
                                  RichText(
                                    text: const TextSpan(
                                        text: 'Forgot Password?',
                                        style: TextStyle(
                                            color: Colors.black,
                                            fontSize: 16,
                                            height: 3.0),
                                        children: <TextSpan>[
                                          TextSpan(
                                              text: '  Click me ',
                                              style: TextStyle(
                                                  color: Colors.blueAccent,
                                                  fontSize: 16,
                                                  height: 3.0))
                                        ]),
                                  ),
                                ]),
                          ],
                        ),
                      ),
                    ],
                  ),
                ]),
          ),
        ),

//'Copyrights' code from here...
        bottomNavigationBar: const BottomAppBar(
            color: Colors.grey,
            child: SizedBox(
              width: 30.0,
              height: 30.0,
              child: Center(
                  child: Text(
                "All rights are reserved @SSS - 2022",
                textAlign: TextAlign.center,
              )),
            )));
  }
}

login.php :

<?php
    $db = mysqli_connect('localhost','root','','login');

    $email = $_POST['email'];
    $password = $_POST['password'];

    $sql = "SELECT * FROM login WHERE email='".$email."' AND password='".$password."'";
    $result = mysqli_query($db, $sql);
    $count = mysqli_num_rows($result);

    if($count >= 1) {
        echo json_encode("Success..! ");
    }
    else {
        echo json_encode("Error..! ☹");
    }

?>

Screenshots :

Folder Tree Structure in VS Code IDE

Flutter UI 1

Flutter UI 2

Database Values in PhpMysql DB

'login.php' error in Browser

0 Answers
Related