1

so i'm trying to send an email in flutter as a background process without having to navigate through the gmail app and i followed this tutorial https://www.youtube.com/watch?v=RDwst9icjAY and every thing is working except 'onpressed(){}'function on the iconbutton it showes an erorr of 'Local variable 'sendEmail' can't be referenced before it is declared. Try moving the declaration to before the first use, or renaming the local variable so that it doesn't hide a name from an enclosing scope.' with no quick fixes so what seems to be the problem?, i tried initialising it in multiple places but i guess i'm new to these types of funtions. here is my code

    import 'package:flutter/material.dart';
    import 'package:mailer/mailer.dart';
    import 'package:mailer/smtp_server.dart';
    import 'package:google_sign_in/google_sign_in.dart';

    import 'google_auth_api.dart';

    class emailsend extends StatefulWidget {
    const emailsend({Key? key}) : super(key: key);

    @override
    State<emailsend> createState() => _MainPageState();
    }
    class _MainPageState extends State<emailsend> {

    @override
      Widget build(BuildContext context) {
      return Scaffold(
      appBar: AppBar(
        title: Text('email'),
        centerTitle: true,
      ),
      body: Center(
        child: IconButton(
          icon: Icon(Icons.circle_rounded),
          splashColor: Colors.red,
          color: Colors.red,
          iconSize: 250,
          onPressed:(){ sendEmail},
        ),
      ),
    );

    Future sendEmail() async {
      final user = await GoogleAuthApi.signIn();
      if (user == null) return;
      final email = 'khaledkandli55@gmail.com';
      final auth = await user.authentication;
      final accessToken = '';
      final smptServer = gmailSaslXoauth2(email, accessToken);
      final message = Message()
        ..from = Address(email, 'Khaled')
        ..recipients = ['khaledkandli55@gmail.com']
        ..subject = 'Hello'
        ..text = 'this is atext email';
      try {
        await send(message, smptServer);
        showSnackBar('sent successfully');
      } on MailerException catch (erorr) {
        print(erorr);
      }
    }
  }
    void showSnackBar(String text) {
    final snackBar = SnackBar(
      content: Text(
        text,
        style: TextStyle(fontSize: 20),
      ),
      backgroundColor: Colors.green,
    );
    ScaffoldMessenger.of(context)
      ..removeCurrentSnackBar()
      ..showSnackBar(snackBar);
  }
}    

// the second page

import 'package:google_sign_in/google_sign_in.dart';
 class GoogleAuthApi {
 static final _googleSignIn =
  GoogleSignIn(scopes: ['https://mail.google.com/']);
 static Future<GoogleSignInAccount?> signIn() async {
  if (await _googleSignIn.isSignedIn()) {
  return _googleSignIn.currentUser;
   } else {
   return await _googleSignIn.signIn();
 }
} 
}
Khaled
  • 11
  • 2

2 Answers2

1

You are missing an actual call to a function.

onPressed: () { sendEmail(); }

Or if you want to use a reference.

onPressed: sendEmail
user18309290
  • 5,777
  • 2
  • 4
  • 22
0

try to make sendEmail function before build and call it in onPressed like this code


import 'package:flutter/material.dart';
import 'package:mailer/mailer.dart';
import 'package:mailer/smtp_server.dart';
import 'package:google_sign_in/google_sign_in.dart';

class EmailSend extends StatefulWidget {
 const EmailSend({Key? key}) : super(key: key);

 @override
 State<EmailSend> createState() => _MainPageState();
}

class _MainPageState extends State<EmailSend> {
 Future sendEmail() async {
   final user = await GoogleAuthApi.signIn();
   if (user == null) return;
   final email = 'khaledkandli55@gmail.com';
   final auth = await user.authentication;
   final accessToken = '';
   final smptServer = gmailSaslXoauth2(email, accessToken);
   final message = Message()
     ..from = Address(email, 'Khaled')
     ..recipients = ['khaledkandli55@gmail.com']
     ..subject = 'Hello'
     ..text = 'this is atext email';
   try {
     await send(message, smptServer);
     showSnackBar('sent successfully');
   } on MailerException catch (erorr) {
     print(erorr);
   }
 }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       title: Text('email'),
       centerTitle: true,
     ),
     body: Center(
       child: ElevatedButton(
         child: Text("Send Email"),
         onPressed: () {
           sendEmail();
         },
       ),
     ),
   );
 }

 void showSnackBar(String text) {
   final snackBar = SnackBar(
     content: Text(
       text,
       style: TextStyle(fontSize: 20),
     ),
     backgroundColor: Colors.green,
   );
   ScaffoldMessenger.of(context)
     ..removeCurrentSnackBar()
     ..showSnackBar(snackBar);
 }
}

class GoogleAuthApi {
 static final _googleSignIn =
     GoogleSignIn(scopes: ['https://mail.google.com/']);
 static Future<GoogleSignInAccount?> signIn() async {
   if (await _googleSignIn.isSignedIn()) {
     return _googleSignIn.currentUser;
   } else {
     return await _googleSignIn.signIn();
   }
 }
}

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 30 '22 at 01:11