Login to Nextcloud server with flutter App.

 In this tutorial, you will learn that how to login to NextCloud server with flutter App.



To implement login functionality to a Nextcloud server in a Flutter app, you'll need to follow these steps:

1. Set Up Nextcloud Server: 

Ensure you have a Nextcloud server running and accessible via a URL.



2. Authenticate and Obtain API Access:

Decide on the authentication method you want to use. Nextcloud supports various authentication methods, including username/password, OAuth, and others. We will use OCS-API for authentication and if you want to see in detail you can check  here.




3. Create Flutter Application:

Set up a new Flutter project or use an existing one.

4. Add Dependencies:

Add dependencies for handling HTTP requests and managing state. You can use the http package for making HTTP requests.

Add these to your pubspec.yaml:

dependencies:
http: ^1.1.0

Then run flutter pub get to install the package.

5. Create a Login Screen:

Create a login screen where users can input their credentials (username and password) or authenticate using another method like OAuth.
// Example of a simple login screen widget

class LoginScreen extends StatefulWidget {

  const LoginScreen({super.key});


  @override

  State<LoginScreen> createState() => _LoginScreenState();

}


class _LoginScreenState extends State<LoginScreen> {

  TextEditingController usernameController = TextEditingController();

  TextEditingController passwordController = TextEditingController();


  bool showError = false;

  String showErrorText = "";

  bool _callFxn = false;

  int retryCount = 0;


  @override

  Widget build(BuildContext context) {

    var appSize = MediaQuery.of(context).size;


    return Scaffold(

      body: Container(

        width: appSize.width,

        height: appSize.height,

        decoration: BoxDecoration(

          gradient: LinearGradient(

            begin: Alignment.topCenter,

            end: Alignment.bottomCenter,

            colors: [

              Color.fromARGB(255, 21, 59, 88),

              Color.fromARGB(255, 7, 106, 91)

            ],

          ),

        ),

        child: SingleChildScrollView(

          child: Column(

            crossAxisAlignment: CrossAxisAlignment.start,

            mainAxisAlignment: MainAxisAlignment.start,

            children: [

              SizedBox(

                height: 120,

              ),

              Row(

                mainAxisAlignment: MainAxisAlignment.spaceBetween,

                children: [

                  Spacer(),

                  Container(

                    child: Text(

                      'Login Screen',

                      style: appnameTextStyle(),

                    ),

                  ),

                  Expanded(

                    child: GestureDetector(

                      child: Container(

                        margin: EdgeInsets.only(left: appSize.width * .24),

                        height: 24,

                        width: 24,

                        decoration: const BoxDecoration(

                          image: DecorationImage(

                            image: AssetImage('assets/images/info.png'),

                          ),

                        ),

                      ),

                      onTap: () {

                      },

                    ),

                  )

                ],

              ),

              SizedBox(

                height: 160,

              ),

              Row(

                mainAxisAlignment: MainAxisAlignment.start,

                children: [

                  SizedBox(width: 40),

                  Text(

                    'Name',

                    style: TextStyle(color: Colors.white),

                  ),

                ],

              ),

              SizedBox(

                height: 10,

              ),

              Container(

                height: 50,

                width: appSize.width,

                margin: EdgeInsets.only(left: 30, right: 30),

                child: TextField(

                  controller: usernameController,

                  decoration: InputDecoration(

                    border: OutlineInputBorder(

                      borderRadius: BorderRadius.circular(25.0),

                    ),

                    fillColor: Colors.white,

                    filled: true,

                  ),

                ),

              ),

              SizedBox(

                height: 30,

              ),

              Row(

                mainAxisAlignment: MainAxisAlignment.start,

                children: [

                  SizedBox(width: 40),

                  Text(

                    'Password',

                    style: TextStyle(color: Colors.white),

                  ),

                ],

              ),

              SizedBox(

                height: 10,

              ),

              Container(

                height: 50,

                width: appSize.width,

                margin: EdgeInsets.only(left: 30, right: 30),

                child: TextField(

                  controller: passwordController,

                  decoration: InputDecoration(

                      border: OutlineInputBorder(

                        borderRadius: BorderRadius.circular(25.0),

                        ),

                    fillColor: Colors.white,

                    filled: true,

                  ),

                ),

              ),

              SizedBox(

                height: 30,

              ),

              Row(

                mainAxisAlignment: MainAxisAlignment.start,

                children: [

                  SizedBox(width: 40),

                  Text(

                    'Password',

                    style: TextStyle(color: Colors.white),

                  ),

                ],

              ),

              SizedBox(

                height: 10,

              ),

              Container(

                height: 50,

                width: appSize.width,

                margin: EdgeInsets.only(left: 30, right: 30),

                child: TextField(

                  controller: passwordController,

                  decoration: InputDecoration(

                      border: OutlineInputBorder(

                        borderRadius: BorderRadius.circular(25.0),

                      ),

                      fillColor: Colors.white,

                      filled: true),

                ),

              ),

              SizedBox(height: appSize.height / 6),

              Container(

                margin: EdgeInsets.only(left: 30, right: 30),

                width: appSize.width * .9,

                height: 50,

                child: ElevatedButton(

                  child: Row(

                    mainAxisAlignment: MainAxisAlignment.center,

                    children: [

                      Text("Login"

                          //.tr,

                          //style: buttonTextStyle(),

                          ),

                    ],

                  ),

                  onPressed: () => {

                    //Helpers.showLoaderDialog(context),

                    loginApi(),

                  },

                  style: ElevatedButton.styleFrom(

                    backgroundColor: Color.fromARGB(255, 236, 98, 88),

                    shape: RoundedRectangleBorder(

borderRadius: BorderRadius.circular(25),

                    ),

                  ),

                ),

              ),

            ],

          ),

        ),

      ),

    );

  }


  TextStyle appnameTextStyle() {

    return TextStyle(color: Colors.white, fontSize: 24);

  }

}

6. Make API Request for Authentication:


Use the http package to make an API request to authenticate the user. The exact API endpoint and parameters will depend on the authentication method you choose.
Here's an example using basic username and password authentication:

Future<void> login(String username, String password) async {
  var serverUrl = '';

    setState(() {

      _callFxn = true;

    });

    if (usernameController.text == '' || passwordController.text == '') {

      setState(() {

        _callFxn = false;

        showError = true;

      });

      Navigator.pop(context);

    } else {

      var folderName = usernameController.text.trim();

      var username = usernameController.text.trim();

      var password = passwordController.text;

      var authn = 'Basic ' + base64Encode(utf8.encode('$username:$password'));


      var headers = {

        'OCS-APIRequest': 'true',

        'Authorization': authn,

        "content_type": "application/json",

      };

      var url = Uri.parse(serverUrl + "ocs/v2.php/core/getapppassword");

      var res = await http.get(url, headers: headers);

      if (res.statusCode == 200) {

        Navigator.pop(context);


        loginRedirection();

      } else {

        setState(() {

          _callFxn = false;

        });

        Navigator.pop(context);

      }

    }

}


7.  After Successful Login:

Once the user is successfully authenticated, navigate them to the main part of your app.

  loginRedirection() {
    // Navigate to the main part of your app
    Navigator.of(context).pushReplacement(

          MaterialPageRoute(

            builder: (context) => HomeScreen(),

          ),

        );

 }



Remember to replace serverUrl like https://your-nextcloud-instance.com with your actual Nextcloud server URL and handle authentication endpoints appropriately.


Please note that security is of utmost importance when dealing with user credentials. Ensure that you are using secure methods for handling passwords, such as encryption or secure storage, and consider using HTTPS for communication with your server.


















 






















































 















Comments