The method 'validate' was called on null. Receiver: null Tried Calling: validate()

Asked

Viewed 1,630 times

1

In the code created in VS Code I am trying to implement the validate when receiving the information of the 02 values fields, for some reason the code is correct more present in DEBUG CONSOLE. Follow MAIN and PUBSPEC code.

My code (main page)

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
//import 'package:async/async.dart';
//import 'dart:core';

void main() {
  runApp(MaterialApp(
    home: Home(),
  ));
}
//acompanhar as alterações e atualizar a interface do usuário com base nessas alterações.
class Home extends StatefulWidget { 
  @override
  _HomeState createState() => _HomeState();
}

//Interface do App
class _HomeState extends State<Home> {
  final _toDoController = TextEditingController();
  final _toDoControllerN = TextEditingController();

  GlobalKey<FormState> _formkey = GlobalKey<FormState>();
  //foi criada uma chave global

  String _infoText = "Lembre da última vez!";

  List _toDoList = [];

  Map<String, dynamic> _lastRemoved;
  int _lastRemovedPos;

  @override
  void initState() {
    super.initState();
    _readData().then((data) {
      setState(() {
        _toDoList = json.decode(data);
        _formkey = GlobalKey<FormState>();
      });
    });
  }

  void _addToDo() {
    setState(() {
      Map<String, dynamic> newToDo = Map();
      newToDo["title"] = _toDoController.text +"  "+ _toDoControllerN.text;
      _toDoController.text = "";
      _toDoControllerN.text = "";
      newToDo["ok"] = false;
      _toDoList.add(newToDo);
      _formkey = GlobalKey<FormState>();
      _saveData();
    });
  }

  //recebe os dados após algum intervalo e representa um processamento assíncrono
  //pode ter êxito ou pode falhar e o código precisa lidar com ambos os casos) 
  Future<Null> _refresh() async {
    await Future.delayed(Duration(seconds: 1));
    setState(() {
      _toDoList.sort((a, b) {
        if (a["ok"] && !b["ok"])
          return 1;
        else if (!a["ok"] && b["ok"])
          return -1;
        else
          return 0;
      });
      _saveData();
    });
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Lista de Compras"),
        backgroundColor: Colors.blueAccent,
        centerTitle: true,
      ),
      body: Column(
        key: _formkey,
        children: <Widget>[
          Container(
            child: Expanded( //input respeite o tamanho da tela
              child: TextFormField(
                controller: _toDoController,
                decoration: InputDecoration(
                    labelText: "  Descrição do Item :",
                    labelStyle: TextStyle(color: Colors.blueAccent, fontSize: 22.0)),
                textAlign: TextAlign.center,
              ),
            ),
          ),

          Image.asset(
              "imagens/logo.jpg",
              fit: BoxFit.cover,
              height: 100.0,
            ),

          Container(
            child: Expanded(
              child:TextFormField(
                controller: _toDoControllerN,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                    labelText: "  Valor :",
                    labelStyle: TextStyle(color: Colors.blueAccent, fontSize: 20.0)),
                textAlign: TextAlign.center,
                validator: (value){
                  if (value.isEmpty){
                    print("vazio");
                    setState(() {
                      _infoText = "vazio";
                    });
                    return "vazio!";
                  }

                },
              ),
            ),
          ),
                RaisedButton(
                  color: Colors.blueAccent,
                  child: Text("ADD"),
                  textColor: Colors.white,
                  onPressed: (){
                    print("ENTROU AQUI");
                      if(_formkey.currentState.validate()){
                        _addToDo();
                        print("ENTROU NO IFPI");

                    }
                  },

                ),

                Text(
                _infoText,
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.blue, fontSize: 20.0),
              ),  

          /////aqui

          Expanded(
            child: RefreshIndicator(
                onRefresh: _refresh,
                child: ListView.builder(
                    padding: EdgeInsets.only(top: 5.0),
                    itemCount: _toDoList.length,
                    itemBuilder: buildItem)),
          )
        ],
      ),
    );
  }

  Widget buildItem(context, index) {
    return Dismissible(
      key: Key(DateTime.now().millisecondsSinceEpoch.toString()),
      background: Container(
        color: Colors.red,
        child: Align(
          alignment: Alignment(-0.9, 0.0),
          child: Icon(Icons.delete, color: Colors.white),
        ),
      ),
      direction: DismissDirection.startToEnd,
      child: CheckboxListTile(
        title: Text(_toDoList[index]["title"]),
        value: _toDoList[index]["ok"],
        secondary: CircleAvatar(
          child: Icon(_toDoList[index]["ok"] ? Icons.check : Icons.error),
        ),
        onChanged: (c) {
          setState(() {
            _toDoList[index]["ok"] = c;
            _saveData();
          });
        },
      ),
      onDismissed: (direction) {
        setState(() {
          _lastRemoved = Map.from(_toDoList[index]);
          _lastRemovedPos = index;
          _toDoList.removeAt(index);
          _saveData();

          final snack = SnackBar(
            content: Text("Tarefa \"${_lastRemoved["title"]}\"removida!"),
            action: SnackBarAction(
              label: "Desfazer",
              onPressed: () {
                setState(() {
                  _toDoList.insert(_lastRemovedPos, _lastRemoved);
                  _saveData();
                });
              },
            ),
            duration: Duration(seconds: 2),
          );
          Scaffold.of(context).removeCurrentSnackBar();
          Scaffold.of(context).showSnackBar(snack);
        });
      },
    );
  }

  Future<File> _getFile() async {
    final directory = await getApplicationDocumentsDirectory();
    return File("${directory.path}/data.json");
  }

  Future<File> _saveData() async {
    String data = json.encode(_toDoList);
    final file = await _getFile();
    return file.writeAsString(data);
  }
}

Future<String> _readData() async {
  try {
    final file = await _getFile();
    return file.readAsString();
  } catch (e) {
    return null;
  }
}


_getFile() {}

My used Packages (Pubspec)

name: lista_tarefas
description: A new Flutter application.

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  path_provider: ^1.1.5

dev_dependencies:
  flutter_test:
    sdk: flutter


# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
  - imagens/logo.jpg
  #  - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

inserir a descrição da imagem aqui

  • Try using a print to show the values being validated, it may be that some value is null when validating the information of the fields.

1 answer

3

What you need is to use a Form, follows an example of how you can do:

GlobalKey<FormState> _formKey = GlobalKey<FormState>();

@override
Widget build(BuildContext context) {
    DateTime _nextMaintenanceValue;
    return SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              TextFormField(
                keyboardType: TextInputType.text,
                textInputAction: TextInputAction.next,
                validator: (value){ return value == "" ? "Obrigatório!" : null;},
                onSaved: (value) => dataObject.name = value,
              ),
              TextFormField(
                keyboardType: TextInputType.text,
                textInputAction: TextInputAction.next,
                validator: (value){ return value == "" ? "Obrigatório!" : null;},
                onSaved: (value) => dataObject.description = value,
              ),
            ]
          ),
        )
    )
}

void onSave(BuildContext context) async {
    var form = _formKey.currentState;
    if(form.validate()){
      form.save();

      SalvarDados();
    }
}

You are also wrong in creating several times a GlobalKey<FormState> leaving her always with NULL values... Create her only once and then link her to Form.

You can take a look at this one too example that I made available in my Github.

To see the complete project

  • Still persists in DEBUG!

  • Have you modified your class as I said? You are creating your GlobalKey<FormState> three times... Instate her only once, leave only this creation GlobalKey<FormState> _formkey = GlobalKey<FormState>();&#xA; //foi criada uma chave global

Browser other questions tagged

You are not signed in. Login or sign up in order to post.