DavidCZ2051
DavidCZ2051

Reputation: 107

Flutter: Use setState in a function?

is there any way I can use setState() in a function (line 26)? I am trying to call the function item (which includes the setState) from my main.dart file and Flutter doesn't like that. Also, the item function is in a different file than the main.dart. Can someone please help me?

item function:

    item(itemName, color, itemVariable) {
  return Container(
    color: color ? Colors.grey[200] : Colors.white,
    child: Row(
      children: [
        Flexible(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text(
              "${itemVariable}x",
              style: const TextStyle(fontSize: 25),
            ),
          ),
        ),
        Text(
          itemName,
          style: const TextStyle(fontSize: 25),
        ),
        Flexible(
          child: Padding(
            padding: const EdgeInsets.fromLTRB(30, 5, 0, 10),
            child: TextField(
              onSubmitted: (value) {
                itemVariable = int.parse(value);
                print("Hodnota pro ${itemName} nastavena na: ${itemVariable}");
                setState(() {});
              },
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                filled: true,
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(15),
                  borderSide: const BorderSide(color: Colors.blue),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(15),
                  borderSide: const BorderSide(color: Colors.blue, width: 2),
                ),
              ),
            ),
          ),
        ),
      ],
    ),
  );
}

main.dart file:

import 'package:flutter/material.dart';
import 'package:intr_obleceni/items.dart';
import 'package:intr_obleceni/functions.dart';

void main() => runApp(
      const MaterialApp(
        home: Main(),
        title: "Intr - seznam oblečení",
      ),
    );

class Main extends StatefulWidget {
  const Main({Key? key}) : super(key: key);

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

class _MainState extends State<Main> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Internát - seznam oblečení"),
        elevation: 2,
      ),
      body: ListView(
        children: [
          category("Bundy", false),
          item("Bunda", false, Bundy.bunda),
          item("Softčílová bunda", false, Bundy.softcilovaBunda),
          category("Ostatní", true),
          item("Ručník", true, Ostatni.rucnik)
        ],
      ),
    );
  }
}

Upvotes: 2

Views: 2602

Answers (2)

KyleDev
KyleDev

Reputation: 31

For those that still need an answer to this, here's what worked for me:

The safest bet is going to be to instead of using a function, to rather use a class based on the StatefulWidget class. My implementation went something like this:

class MyClass extends StatefulWidget {
    final SomeType someVariable1;
    final SomeType someVariable2;
    final SomeType someVariable3;

    const MyClass({
        required this.someVariable1,
        required this.someVariable2,
        required this.someVariable3,
        super.key,
    });

    @override
    State<MyClass> createState() => _MyClassState();

class _MyClassState extends State<MyClass> {
    @override
    Widget build(BuildContext context) {
    return SomeWidget(
        // you can call setState() here as needed.
        );
    }

This should allow you to call setState() as much as you need to within the widget that you were generating within your item.

The class can also then be placed into another file without causing any issues.

Hope this helps someone out somewhere.

Upvotes: 0

Francis Nduba Numbi
Francis Nduba Numbi

Reputation: 3050

instead of calling the setState() function in your function, include a callback function in your params like this :

item(itemName, color, itemVariable {Function? callback}) {

// where you used setState(), use callback()
}

then in your main.dart file, where you called that item function, wrap setState in the callback function.

Upvotes: 2

Related Questions