I am working on a flutter project. Currently working on authentication. I have used Strapi, MongoDB
for database. These are my codes:
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_ecommerce/pages/Dashboard.dart';
import 'package:flutter_ecommerce/pages/login_page.dart';
import 'package:flutter_ecommerce/pages/register_page.dart';
import 'package:flutter_ecommerce/pages/welcome_screen.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter E-Commerce',
routes: {
'/products': (BuildContext context) => Dashboard(),
'/login': (BuildContext context) => LoginPage(),
'/register': (BuildContext context) => RegisterPage()
},
theme: ThemeData(
brightness: Brightness.dark,
primaryColor: Colors.cyan[400],
accentColor: Colors.deepOrange[200],
textTheme: TextTheme(
headline:
TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),
title: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
body1: TextStyle(fontSize: 18.0))),
home: WelcomeScreen());
}
}
And this is my register_page.dart
:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class RegisterPage extends StatefulWidget {
@override
RegisterPageState createState() => RegisterPageState();
}
class RegisterPageState extends State<RegisterPage> {
final _scaffoldKey = GlobalKey<ScaffoldState>();
final _formKey = GlobalKey<FormState>();
bool _isSubmitting, _obscureText = true;
String _username, _email, _password;
Widget _showTitle() {
return Text('Register', style: Theme.of(context).textTheme.headline);
}
Widget _showUsernameInput() {
return Padding(
padding: EdgeInsets.only(top: 20.0),
child: TextFormField(
onSaved: (val) => _username = val,
validator: (val) => val.length < 6 ? 'Username too short' : null,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Username',
hintText: 'Enter username, min length 6',
icon: Icon(Icons.face, color: Colors.grey))));
}
Widget _showEmailInput() {
return Padding(
padding: EdgeInsets.only(top: 20.0),
child: TextFormField(
onSaved: (val) => _email = val,
validator: (val) => !val.contains('@') ? 'Invalid Email' : null,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email',
hintText: 'Enter a valid email',
icon: Icon(Icons.mail, color: Colors.grey))));
}
Widget _showPasswordInput() {
return Padding(
padding: EdgeInsets.only(top: 20.0),
child: TextFormField(
onSaved: (val) => _password = val,
validator: (val) => val.length < 6 ? 'Username too short' : null,
obscureText: _obscureText,
decoration: InputDecoration(
suffixIcon: GestureDetector(
onTap: () {
setState(() => _obscureText = !_obscureText);
},
child: Icon(_obscureText
? Icons.visibility
: Icons.visibility_off)),
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter password, min length 6',
icon: Icon(Icons.lock, color: Colors.grey))));
}
Widget _showFormActions() {
return Padding(
padding: EdgeInsets.only(top: 20.0),
child: Column(children: [
_isSubmitting == true
? CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation(Theme.of(context).primaryColor))
: RaisedButton(
child: Text('Submit',
style: Theme.of(context)
.textTheme
.body1
.copyWith(color: Colors.black)),
elevation: 8.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0))),
color: Theme.of(context).primaryColor,
onPressed: _submit),
FlatButton(
child: Text('Existing user? Login'),
onPressed: () =>
Navigator.pushReplacementNamed(context, '/login'))
]));
}
void _submit() {
final form = _formKey.currentState;
if (form.validate()) {
form.save();
_registerUser();
}
}
void _registerUser() async {
setState(() => _isSubmitting = true);
http.Response response = await http.post(
'http://localhost:1337/auth/local/register',
body: {"username": _username, "email": _email, "password": _password});
final responseData = json.decode(response.body);
setState(() => _isSubmitting = false);
_showSuccessSnack();
_redirectUser();
print(responseData);
}
void _showSuccessSnack() {
final snackBar = SnackBar(
content: Text('User $_username successfully created!',
style: TextStyle(color: Colors.blue)));
_scaffoldKey.currentState.showSnackBar(snackBar);
_formKey.currentState.reset();
}
void _redirectUser() {
Future.delayed(Duration(seconds: 2), () {
Navigator.pushReplacementNamed(context, '/products');
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(title: Text('Register')),
body: Container(
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: Center(
child: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(children: [
_showTitle(),
_showUsernameInput(),
_showEmailInput(),
_showPasswordInput(),
_showFormActions()
]))))));
}
}
I am using external device to run the app through usb debugging. after flutter run, filling the registration and click submit button, app keeps loading and doesn't advance. These are the outputs in terminal:
An Observatory debugger and profiler on IN2010 is available at:
http://127.0.0.1:3206/-CqybHQuYBY=/
Running with unsound null safety For more information see this .
D/ViewRootImpl[MainActivity](25957): windowFocusChanged hasFocus=false inTouchMode=true
D/DecorView(25957): onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@55e66[MainActivity]
D/ViewRootImpl[MainActivity](25957): windowFocusChanged hasFocus=true inTouchMode=true
W/IInputConnectionWrapper(25957): getExtractedText on inactive InputConnection
E/libprocessgroup(25957): set_timerslack_ns write failed: Operation not permitted
E/flutter (25957): [ERROR:flutter/lib/ui/ui_dart_state.cc(184)] Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 45772
***
The error is quite explicit, you are trying to access port 45772 but I see in your program that you query port 1337.
http://localhost:1337/auth/local/register
You have to set a proper forward on your emulator (adb). Open the terminal of your project and enter:
adb reverse tcp:1337 tcp:1337
This command will ensure that your emulator makes the request to your localhost:1337