setState при нажатии создает новый объект - PullRequest
0 голосов
/ 28 мая 2020

До нажатия есть только 3 кнопки, но после нажатия любой кнопки, как вы можете видеть, есть 6 кнопок

enter image description here

Я пытаюсь создать рейтинговая система для моего приложения, но всякий раз, когда я нажимаю кнопку, создается новая кнопка, и я не совсем уверен, почему это происходит.

Если я попытаюсь запустить его без setState() и нажму кнопку, новый объект не будет создан, и это именно то, что я хочу в итоге.

import 'package:flutter/material.dart';

class Rating extends StatefulWidget {
  @override
  _RatingState createState() => _RatingState();
}

class _RatingState extends State<Rating> {
  final List<IconData> iconsImage = [
    Icons.star,
    Icons.star,
    Icons.star,
    Icons.star,
  ];
  List<ButtonTheme> buttonsList = new List<ButtonTheme>();

  List<Widget> _buildButtons() {
    for (int i = 0; i < 3; i++) {
      buttonsList.add(ButtonTheme(
        height: 20,
        minWidth: 40,
        child: FlatButton(
          onPressed: () {
            //When i press button new star is created not sure why
            setState(() {
              print(i);
            });
          },
          child: Icon(Icons.star),
        ),
      ));
    }
    return buttonsList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[900],
      body: Container(
        child: Column(
          children: <Widget>[
            Container(
              child: Text('Rate the homework',
                  style: TextStyle(
                    color: Colors.white,
                  )),
            ),
            Divider(
              height: 30,
              color: Colors.red,
            ),
            Row(
              children: _buildButtons(),
            )
          ],
        ),
      ),
    );
  }
}

1 Ответ

0 голосов
/ 28 мая 2020

Поместите свой метод _buildButtons в функцию build .

Reason : State Class in Stateful Widget are meant to hold and persist the state even during rebuild so that old state is remembered.

Здесь buttonList - это ваше состояние, которое не будет перезаписано. Таким образом, нажатие кнопки (которая установит состояние) приведет к появлению sh новой кнопки в существующем списке кнопок (а не во вновь созданном списке).

Решение : If you initialize you buttonsList inside a build function,it will also be reinitialized during re-build. So Clicking button (which will set state) will push new button to an newly created button list(not to a existing created list).

import 'package:flutter/material.dart';

class Rating extends StatefulWidget {
  @override
  _RatingState createState() => _RatingState();
}

class _RatingState extends State<Rating> {
  @override
  Widget build(BuildContext context) {
    List<ButtonTheme> buttonsList = new List<ButtonTheme>();

    List<Widget> _buildButtons() {
      for (int i = 0; i < 3; i++) {
        buttonsList.add(ButtonTheme(
          height: 20,
          minWidth: 40,
          child: FlatButton(
            onPressed: () {
              //When i press button new star is created not sure why
              setState(() {
                print(i);
              });
            },
            child: Icon(Icons.star),
          ),
        ));
      }
      return buttonsList;
    }

    return Scaffold(
      backgroundColor: Colors.grey[900],
      body: Container(
        child: Column(
          children: <Widget>[
            Container(
              child: Text('Rate the homework',
                  style: TextStyle(
                    color: Colors.white,
                  )),
            ),
            Divider(
              height: 30,
              color: Colors.red,
            ),
            Row(
              children: _buildButtons(),
            )
          ],
        ),
      ),
    );
  }
}
...