Home > Back-end >  reuse Method in Flutter
reuse Method in Flutter

Time:07-24

So it sound like a dumb question but I don't get it. I have a Controller Class that has a method

    import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

import '../utils.dart';

class UserController {
  Future signMeIn(TextEditingController emailController,
      TextEditingController passwordController, context, navigatorKey) async {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => Center(
              child: CircularProgressIndicator(),
            ));
    try {
      await FirebaseAuth.instance.signInWithEmailAndPassword(
          email: emailController.text.trim(),
          password: passwordController.text.trim());
    } on FirebaseAuthException catch (e) {
      print(e);

      Utils.showSnackBar(e.message);
    }

    navigatorKey.currentState!.popUntil((route) => route.isFirst);
  }
}

and I simply want to reuse this method in a stateful widget

so Im importing the file where the method is defined

import "user_controller.dart";

and trying to call it here

ElevatedButton.icon(
            style: ElevatedButton.styleFrom(minimumSize: Size.fromHeight(50)),
            icon: Icon(Icons.lock_open, size: 32),
            label: Text(
              "Sign In",
              style: TextStyle(fontSize: 24),
            ),
            onPressed: signMeIn(parameters),
          ),

but I get the error that it isn't defined what am I doing wrong?

CodePudding user response:

UserController controller = UserController();

ElevatedButton.icon(
            style: ElevatedButton.styleFrom(minimumSize: Size.fromHeight(50)),
            icon: Icon(Icons.lock_open, size: 32),
            label: Text(
              "Sign In",
              style: TextStyle(fontSize: 24),
            ),
            onPressed: controller.signMeIn(parameters),
          ),

CodePudding user response:

When you create a class before you use that you have to instantiate it. That means "allocate a place in memory". So, you have to call like this:

UserController userController = UserController();

  • the name controller can be any name you want.
  • Related