The method 'setState' isn’t defined for the type 'Myapp'

Asked

Viewed 175 times

-2

I’m starting in flutter, but I came across this mistake in setState.

Widget build(BuildContext context) {
return MaterialApp(
  home: Scaffold(
      appBar: AppBar(
        title: Text('Horímetro'),
      ),
      body: Column(
        children: <Widget>[
          TextField(
            decoration: InputDecoration(labelText: 'Nome do operador:'),
          ),
          TextField(
            decoration: InputDecoration(labelText: 'Prefixo Trator:'),
          ),
          TextField(
            decoration: InputDecoration(labelText: 'Prefixo Implemento:'),
          ),
          new FlatButton(
            child: new Row(
              children: <Widget>[
                new Text(
                  '${formatDate(_data, [dd, '-', mm, '-', yyyy])}',
                  style: new TextStyle(color: Colors.blue),
                ),
                new Icon(Icons.calendar_today),
              ],
            ),
            onPressed: () async {
              final dtPick = await showDatePicker(
                  context: context,
                  initialDate: new DateTime.now(),
                  firstDate: new DateTime(1900),
                  lastDate: new DateTime(2100));

              if (dtPick != null && dtPick != _data) {
           --->  setState(() {
                  _data = dtPick;
                });
              }
            },
          ),

I don’t understand very well what I’m missing, and it keeps giving this error ("The method 'setState' isn’t defined for the type 'Myapp'"). I want to know how to fix it. Thanks in advance!

  • Oops, all good? A tip is that you take a look at documentation, already that it is starting. This problem may be because you are trying to use the setState((){}) within a Statelesswidget which is a Widget static. The Setstate only works in the Statefulwidget.

  • 1

    Thanks for the tip, it helped a lot!

1 answer

1


You need to import the.Dart material library and use a Stateful widget to use setState.

import 'package:flutter/material.dart';

class MeuWidget extends StatefulWidget {
  @override
  _MeuWidgetState createState() => _MeuWidgetState();
}

class _MeuWidgetState extends State<MeuWidget> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
  • Thanks for the help! It worked!

Browser other questions tagged

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