Flutter 应用程序不断加载并显示错误

Flutter app keeps loading and showing error

我正在做一个 flutter 项目。目前致力于身份验证。我使用 Strapi,MongoDB 作为数据库。这些是我的代码:

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());
  }
}

这是我的 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()
                        ]))))));
  }
}

我正在使用外部设备通过 USB 调试 运行 应用程序。在 flutter 运行 之后,填写注册并单击提交按钮,应用程序一直在加载并且没有前进。 这些是终端的输出:


IN2010 上的 Observatory 调试器和分析器位于:

http://127.0.0.1:3206/-CqybHQuYBY=/

运行 不完善的空安全 有关详细信息,请参阅 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
***

错误非常明显,您正在尝试访问端口 45772,但我在您的程序中看到您查询端口 1337。

http://localhost:1337/auth/local/register

您必须在您的模拟器 (adb) 上设置正确的转发。打开项目的终端并输入:

adb reverse tcp:1337 tcp:1337

此命令将确保您的模拟器向您的 localhost:1337

发出请求