即使没有引发异常,小吃栏也不会显示

时间:2019-09-25 13:52:43

标签: flutter

我有以下代码发送POST请求,并且在收到响应后必须显示Snackbar,但是屏幕上没有任何显示。此代码有什么问题?

main.dart

import 'package:ahgora/screens/home.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: Home(),
    );
  }
}

home.dart

import 'package:ahgora/models/user.dart';
import 'package:flutter/material.dart';
import 'dart:convert';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  final _user = User();
  final _formKey = GlobalKey<FormState>();
  final _tokenNode = FocusNode();
  final _userNode = FocusNode();
  final _passwordNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      body: Container(
        child: Builder(
          builder: (context) => Form(
            key: _formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  child: Image.asset("assets/images/logo.png",
                      fit: BoxFit.scaleDown,
                      width: 160,
                      alignment: Alignment.center),
                  margin: EdgeInsets.only(top: 100.0),
                ),
                Expanded(
                  child: ListView(
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.all(20.0),
                        child: TextFormField(
                          textInputAction: TextInputAction.next,
                          focusNode: _tokenNode,
                          onFieldSubmitted: (term) {
                            _fieldFocusChange(context, _tokenNode, _userNode);
                          },
                          onSaved: (val) {
                            setState(() {
                              _user.identity = val;
                            });
                          },
                          decoration: InputDecoration(
                            border: OutlineInputBorder(),
                            labelText: 'Chave',
                          ),
                          validator: (value) {
                            return value.isEmpty
                                ? 'Preencha com a chave.'
                                : null;
                          },
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.all(20.0),
                        child: TextFormField(
                          textInputAction: TextInputAction.next,
                          focusNode: _userNode,
                          onFieldSubmitted: (term) {
                            _fieldFocusChange(
                                context, _userNode, _passwordNode);
                          },
                          onSaved: (val) {
                            setState(() {
                              _user.account = val;
                            });
                          },
                          decoration: InputDecoration(
                              border: OutlineInputBorder(),
                              labelText: 'Usuário'),
                          validator: (value) {
                            return value.isEmpty ? 'Preencha o usuário.' : null;
                          },
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.all(20.0),
                        child: TextFormField(
                          textInputAction: TextInputAction.next,
                          focusNode: _passwordNode,
                          onSaved: (val) {
                            setState(() {
                              _user.password = val;
                            });
                          },
                          decoration: InputDecoration(
                              border: OutlineInputBorder(), labelText: 'Senha'),
                          validator: (value) {
                            return value.isEmpty ? 'Preencha a senha.' : null;
                          },
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.all(20.0),
                        child: MaterialButton(
                          color: Colors.redAccent,
                          textColor: Colors.white,
                          onPressed: () {
                            final form = _formKey.currentState;
                            if (form.validate()) {
                              form.save();
                              _user.register().then((response) {
                                if (response.statusCode == 200 && json.decode(response.body).error != true) {
                                  final snackbar = SnackBar(content: Text('Ponto registrado'));
                                  Scaffold.of(context).showSnackBar(snackbar);
                                }
                                else {
                                  final snackbar = SnackBar(content: Text('Erro. Mensagem: ' + json.decode(response.body).message));
                                  Scaffold.of(context).showSnackBar(snackbar);
                                }
                              });
                            }
                          },
                          child: Text('Registrar'),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  _fieldFocusChange(
      BuildContext context, FocusNode currentFocus, FocusNode nextFocus) {
    currentFocus.unfocus();
    FocusScope.of(context).requestFocus(nextFocus);
  }
}

user.dart

import 'dart:io';
import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;

class User {
  final tokenKey = 'token_key';
  final loginKey = 'login_key';
  final passwordKey = 'password_key';

  String identity;
  String account;
  String password;

  read() async {
    final prefs = await SharedPreferences.getInstance();
    identity = prefs.getString(tokenKey);
    account = prefs.getString(loginKey);
    password = prefs.getString(passwordKey);
  }

  Future<http.Response> register() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString(tokenKey, identity);
    prefs.setString(loginKey, account);
    prefs.setString(passwordKey, password);

    final response = await http.post('https://localhost:9000/verifyIdentification',
      headers: {
          HttpHeaders.contentTypeHeader: 'multipart/form-data'
        },
        body: json.encode({
          'identity': this.identity,
          'account': this.account,
          'password': this.password
        })
      );

    return response;
  }
}

0 个答案:

没有答案