Listview с флажком, используя StatefulWidget (setState) - PullRequest
0 голосов
/ 01 мая 2020

Я пытаюсь разработать приложение во флаттере, в котором есть темы, которые пользователь может выбрать, и состояние флажка изменится, когда я прокручиваю по списку. Состояние флажка не исчезнет, ​​и, наконец, пользователь предоставит отправку, значение будет выведено .i пытался я не могу это сделать.

сообщение об ошибке показывает: Метод 'setState' не определен для класса 'ItemDepletionList'. Попробуйте исправить имя с именем существующего метода или определить метод с именем 'setState'

class ItemDepletion extends StatefulWidget {
  @override
  _GetShaftsState createState() => _GetShaftsState();

}

class _GetShaftsState extends State<ItemDepletion> {
  ItemDepletionBloc _bloc;
  String json =
      '{"RECORD_ID": "0", "REQTYPE": "ITEMDEPELTION", "CLINIC_ID": "1012"}';

  @override
  void initState() {
    super.initState();
    _bloc = ItemDepletionBloc(json);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        automaticallyImplyLeading: false,
        title: Text('Chucky Categories',
            style: TextStyle(color: Colors.white, fontSize: 20)),
        backgroundColor: Color(0xFF333333),
      ),
      backgroundColor: Color(0xFF333333),
      body: RefreshIndicator(
        onRefresh: () => _bloc.fetchCategories(json),
        child: StreamBuilder<Response<List<Idepeltion>>>(
          stream: _bloc.chuckListStream,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              switch (snapshot.data.status) {
                case Status.LOADING:
                  return Loading(loadingMessage: snapshot.data.message);
                  break;
                case Status.COMPLETED:
                  return ItemDepletionList(
                      itemdepletionlst: snapshot.data.data);
                  break;
                case Status.ERROR:
                  return Error(
                    errorMessage: snapshot.data.message,
                    onRetryPressed: () => _bloc.fetchCategories(json),
                  );
                  break;
              }
            }
            return Container();
          },
        ),
      ),
    );
  }

  @override
  void dispose() {
    _bloc.dispose();
    super.dispose();
  }
}



class ItemDepletionList extends StatelessWidget {
  // final Itemdepeltion categoryList;
  final List<Idepeltion> itemdepletionlst;
  const ItemDepletionList({Key key, this.itemdepletionlst}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new Myappbar(title: new Text("Home Page")),
        body: Column(children: [
          Expanded(
            child: ListView.builder(
              itemCount: itemdepletionlst.length,
              itemBuilder: (context, index) {
                return ListTile(
                    title: new Container(
                        child: Row(
                  children: <Widget>[
                    new Checkbox(
                        value: itemdepletionlst[index].isCheck,
                        onChanged: (bool value) {
                         setState(() {
                            itemdepletionlst[index].isCheck = value;
                          });
                        }),
                    new Expanded(
                      child: new Container(
                        padding: new EdgeInsets.only(left: 8.0, right: 8.0),
                        child: new Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: <Widget>[
                            new Text(
                              '${itemdepletionlst[index].itemName}',
                              style: new TextStyle(
                                color: Colors.black,
                                fontWeight: FontWeight.w600,
                                fontSize: 16.0,
                              ),
                            ),
                            new Text(
                              '${itemdepletionlst[index].category}',
                              style: new TextStyle(color: Colors.grey),
                            ),
                          ],
                        ),
                      ),
                    ),
                    new Expanded(
                        child: GestureDetector(
                      onTap: () {
                        selectedItem(
                            context, itemdepletionlst[index].suggQtyUnit);
                      },
                      child: new Container(
                        padding: new EdgeInsets.only(left: 8.0, right: 8.0),
                        child: new Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: <Widget>[
                            new Text(
                              '${itemdepletionlst[index].suggReorderQty} ${itemdepletionlst[index].suggQtyUnit}',
                              style: new TextStyle(
                                color: Colors.black,
                                fontWeight: FontWeight.w600,
                                fontSize: 16.0,
                              ),
                            ),
                            new Text(
                              '${itemdepletionlst[index].manuf}',
                              style: new TextStyle(color: Colors.grey),
                            ),
                          ],
                        ),
                      ),
                    )),
                  ],
                )));
              },
            ),
          ),
          RaisedButton(
           // onPressed: getCheckboxItems,
            textColor: Colors.white,
            padding: const EdgeInsets.all(0.0),
            child: Container(
              decoration: const BoxDecoration(
                gradient: LinearGradient(
                  colors: <Color>[
                    Color(0xFF09a3c8),
                    Color(0xFF39B9B4),
                    Color(0xFF0fb188),
                  ],
                ),
              ),
              padding: const EdgeInsets.all(10.0),
              child: const Text('Submit',
                  style: TextStyle(fontSize: 20, color: Colors.white)),
            ),
          ),
        ])

        );
  }

}

1 Ответ

1 голос
/ 01 мая 2020

Ваш ItemDepletionList класс не имеет состояния , и вы пытаетесь вызвать в нем settate из-за того, что вы получаете эту ошибку. сделайте это Stateful тогда он будет работать.

замените следующую строку.

class ItemDepletionList extends StatelessWidget {

этим

class ItemDepletionList extends StatefulWidget {
  final List<Idepeltion> itemdepletionlst;
  ItemDepletionList({this.itemdepletionlst});
  @override
  _ItemDepletionListState createState() => _ItemDepletionListState();
}

class _ItemDepletionListState extends State<ItemDepletionList> {

А теперь для доступа к itemdepletionlst you есть виджет использования.

 widget.itemdepletionlst
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...