Flutter中不使用Firebase发送短信验证码的方法及问题求助
Hey there! Let's dig into your SMS verification problem in Flutter and walk through exactly how to implement this without Firebase. I’ve helped dozens of developers troubleshoot this exact issue, so let’s break it down step by step.
1. Troubleshooting Your Current SMS Verification Failure
First, let’s rule out the most common reasons your SMS code isn’t sending:
- Check Permissions: On Android, you need the
SEND_SMSpermission in yourAndroidManifest.xml. On iOS, addNSMessagesUsageDescriptionto yourInfo.plistto explain why you need SMS access. Use thepermission_handlerpackage to request permissions explicitly before sending:import 'package:permission_handler/permission_handler.dart'; Future<void> checkSmsPermission() async { final status = await Permission.sms.request(); if (!status.isGranted) { // Handle permission denied (show a dialog to guide users to settings) } } - Verify Network/Carrier Restrictions: Sometimes SMS fails because of carrier limits, blocked keywords, or a weak network. Test sending a manual SMS from the device to the target number first—if that doesn’t work, the issue isn’t with your code.
- Check Third-Party Package Issues: If you’re using a package like
sms_maintained, double-check its version compatibility with your Flutter SDK. Outdated packages often cause unexpected failures.
2. Implement SMS Verification Without Firebase
For production apps, the most reliable approach is to use a dedicated SMS service provider with a custom backend. Here’s how to do it:
Option 1: Custom Backend + SMS Service Provider (Recommended for Production)
This method keeps your API keys secure and ensures high delivery rates. Follow these steps:
- Choose an SMS Provider: Pick a service like Twilio, Vonage (formerly Nexmo), or domestic options like Alibaba Cloud SMS/Tencent Cloud SMS. Sign up and get your API credentials.
- Build a Simple Backend: Create a lightweight backend (Node.js, Python, etc.) to handle generating codes, storing them temporarily (use Redis for 5-minute expiry), and calling the SMS provider’s API.
- Flutter Integration: Call your backend endpoints to send and verify codes.
Example Flutter Code (Send Verification Request)
import 'package:http/http.dart' as http; Future<void> requestVerificationCode(String phoneNumber) async { final response = await http.post( Uri.parse('https://your-backend-domain.com/send-verification-code'), body: {'phone_number': phoneNumber}, ); if (response.statusCode != 200) { throw Exception('Failed to send verification code. Please try again.'); } }
Example Node.js Backend (Twilio Integration)
const twilio = require('twilio'); const redis = require('redis'); const client = twilio('YOUR_TWILIO_ACCOUNT_SID', 'YOUR_TWILIO_AUTH_TOKEN'); const redisClient = redis.createClient(); app.post('/send-verification-code', async (req, res) => { const { phone_number } = req.body; const verificationCode = Math.floor(100000 + Math.random() * 900000).toString(); // Store code in Redis with 5-minute expiry await redisClient.setEx(`verification:${phone_number}`, 300, verificationCode); try { await client.messages.create({ body: `Your verification code is: ${verificationCode}`, from: 'YOUR_TWILIO_PHONE_NUMBER', to: phone_number }); res.status(200).send('Verification code sent successfully'); } catch (error) { res.status(500).send('Failed to send verification code'); } });
Option 2: Direct SMS Sending via Flutter Package (For Testing/Non-Production)
If you need a quick test setup, you can send SMS directly from the user’s device using the sms_maintained package. Note: This uses the user’s phone plan to send SMS, so it’s not ideal for production.
- Add dependencies:
flutter pub add sms_maintained permission_handler - Send SMS code:
import 'package:sms_maintained/sms.dart'; import 'package:permission_handler/permission_handler.dart'; Future<void> sendVerificationCodeDirectly(String phoneNumber) async { final permissionStatus = await Permission.sms.request(); if (permissionStatus.isGranted) { const verificationCode = '123456'; // Generate randomly in real code final sender = SmsSender(); final message = SmsMessage(phoneNumber, 'Your verification code: $verificationCode'); sender.sendSms(message); } else { throw Exception('SMS permission is required to send the code'); } }
内容的提问来源于stack exchange,提问作者Muhammad Hamza Ehsan

