skip to Main Content

I was trying to add a dropdown menu for a project that I’m currently making and I ran into an issue with my code. I was following a tutorial on YouTube to build a simple one, but I’ve run into the following error; "The method ‘setState’ isn’t defined for the type ‘Options’.:21"

Here is the code:

import 'package:flutter/material.dart';

class Options extends StatelessWidget
{
  const Options({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context)
  {
    List<String> ratings = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
    String? selectedRating = '1';
    return Container(
      child: DropdownButton<String>(
        value: selectedRating,
        items: ratings
            .map((item) => DropdownMenuItem<String>(
              value: item,
              child: Text(item, style: const TextStyle(fontSize: 24)),
        ))
            .toList(),
            onChanged: (item) => setState(() => selectedRating = item),
      ),
    );
  }
}

I was looking into the documentation on Flutter’s website, and I couldn’t find something relevant to the error I’m currently facing.

2

Answers


  1. You are using a stateless widget, you should use a Stateful widget in order to use setState

    Login or Signup to reply.
  2. setState is used in StatefulWidgets to do something that triggers the build method to be called again. Try converting your StatelessWidget to a StatefulWidget.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search