-1

Bom dia, estou com um erro que não consigo resolver em minha aplicação, preciso fazer um cálculo com os valores recebidos em determinados atributos, porém o atributo não recebe os valores, recebo o seguinte erro:

I/flutter (22321): The following NoSuchMethodError was thrown while handling a gesture: I/flutter (22321): The setter 'gasolina=' was called on null. I/flutter (22321): Receiver: null I/flutter (22321): Tried calling: gasolina=4.0

Eu preencho o textField com o valor para fazer o cálculo, porém aparentemente o atributo está recebendo null e não o valor que preenchi.

import 'dart:io';
import 'package:combustivel_ideal/model/posto.dart';
import 'package:combustivel_ideal/pages/lsPostos.dart';
import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart';

class PostoPage extends StatefulWidget{    

  final Posto posto;

  PostoPage({this.posto});

  @override
  _PostoPageState createState() =>_PostoPageState();
}

class _PostoPageState extends State<PostoPage>{

  String _melhor = "";
  String _dataAtualizada = "";
  double perc = 0;

  final _postoController = TextEditingController();
  final _alcoolController = TextEditingController();
  final _gasolinaController = TextEditingController();

  final _postoFocus = FocusNode();

  Posto _postoTemp;

  bool _postoEdited = false;

  void _dialogResult(){
    _resetFields();
    Navigator.pop(context);
  }

  void _resetFields(){
    _postoController.text = '';
    _alcoolController.text = '';
    _gasolinaController.text = '';
    perc = 0;
  }

  void _atualizarData() {
    setState(() {
      _dataAtualizada = formatDate(DateTime.now(),
          [dd, '/', mm, '/', yyyy, ' as ', HH, ':', nn, ":", ss]).toString();
    });
  }

  void _verificar() async{
    double gasolina = await _postoTemp.gasolina;
    double alcool = await _postoTemp.alcool;
    String posto = await _postoTemp.nome;
    setState(() {
      perc = alcool/gasolina;
      if(perc >= 0.7){
          _melhor = 'Gasolina';
      }else{
          _melhor = 'Álcool';
      }
    });
    _atualizarData();
    _showAlert();
  }

  void _showAlert(){
    AlertDialog dialog = AlertDialog(
      content: Text(
          _melhor + perc.toStringAsFixed(2),
          textAlign: TextAlign.center,
          style: TextStyle(
              fontSize: 30.0,
              fontFamily: "Cabin",
              fontWeight: FontWeight.normal,
          ),
      ),
      actions:
           <Widget>[
                  FlatButton(
                    onPressed: (){
                      _dialogResult();
                      Navigator.pop(context, _postoTemp);
                    },
                    child: Text("OK"),
                  ),
                  Padding(
                    padding: EdgeInsets.fromLTRB(0.0, 0.0, 90.0, 0.0),
                  ),
                ],
          );
    showDialog(context: context, child: dialog);
    _postoTemp.alcool = double.parse(_alcoolController.text);
    _postoTemp.gasolina = double.parse(_gasolinaController.text);
  }

  Widget buildAppBar(){
    return AppBar(
      title: Text("Combustível Ideal"),
      backgroundColor: Colors.teal[300],
      centerTitle: true,
      actions: <Widget>[
        IconButton(
          icon: Icon(Icons.view_list),
          onPressed: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => LsPostos()
                ),
            );
          },
        ),
      ],
    );
  }

  Widget buildContainerImage(){
    return Container(
      width: 140.0,
      height: 140.0,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/images/posto.png")
        ),
      ),
    );
  }

  Widget buildScaffold(){
    return Scaffold(
      appBar: buildAppBar(),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(10.0),
        child: Column(
          children: <Widget>[
              buildContainerImage(),
              Padding(
                padding: EdgeInsets.only(top: 15),
              ),
              TextField(
                decoration: InputDecoration(
                  labelText: "Posto",
                  border: OutlineInputBorder(),
                ),
                style: TextStyle(
                  fontSize: 25.0,
                  fontFamily: "Cabin",
                  fontWeight: FontWeight.normal,
                ),
                /*onChanged: (text){
                  _postoEdited = true;
                  setState((){
                    _postoTemp.nome = text;
                  });
                },*/
                controller: _postoController,
                focusNode: _postoFocus,
              ),
              Padding(
                padding: EdgeInsets.only(top: 15),
              ),
              TextField(
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  labelText: "Preço Álcool",
                  border: OutlineInputBorder(),
                ),
                style: TextStyle(
                  fontSize: 25.0,
                  fontFamily: "Cabin",
                  fontWeight: FontWeight.normal,
                ),
                /*onChanged: (text){
                  _postoEdited = true;
                  setState((){
                    _postoTemp.alcool = text as double;
                  });
                },*/
                controller: _alcoolController,
              ),
              Padding(
                padding: EdgeInsets.only(top: 15),
              ),
              TextField(
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  labelText: "Preço Gasolina",
                  border: OutlineInputBorder(),
                ),
                style: TextStyle(
                  fontSize: 25.0,
                  fontFamily: "Cabin",
                  fontWeight: FontWeight.normal,
                ),
                /*onChanged: (text){
                  _postoEdited = true;
                  setState((){
                    _postoTemp.gasolina = text as double;
                  });
                },*/
                controller: _gasolinaController,
              ),
              Padding(
                padding: EdgeInsets.only(top: 15),
              ),
              RaisedButton(
                onPressed: () {
                      _verificar();
                  },
                padding: EdgeInsets.all(15.0),
                child: Text(
                    "Verificar",
                    style: TextStyle(
                      fontSize: 20.0,
                      fontFamily: "Cabin",
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    )
                ),
                shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(25.0)),
                color: Colors.teal[300],
              ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return buildScaffold();
  }

}

Acredito que o erro esteja na função "verificar()", porém não consegui resolvê-lo.

1
  • 1
    Complicado analisar para ajudar, pois o seu código está incompleto e não roda. 26/06/2019 às 14:14

1 Resposta 1

0

Acredito que faltou instanciar o objeto _postoTemp.

 Posto _postoTemp = Posto();

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .