Как назначить уникальный идентификатор или ключ для SwitchListTile и получить / получить его значение в onChanged в мобильном приложении флаттера - PullRequest
0 голосов
/ 14 февраля 2020

Я строю 9 SwitchListTile, используя для l oop, так как теперь кнопка содержит тот же код, поэтому у меня возникают проблемы с ее onChanged, так как каждая моя кнопка будет иметь конкретное событие c, которое нужно выполнить, как мне его достичь ? Можно ли отправить текст кнопки / идентификатор или что-нибудь уникальное, на основании чего я могу выполнить определенные c задачи?

Здесь _onChanged(value, counter); 'counter' - это ничто, но вы можете принять переменную в течение l oop назначение значений 1-9 для каждой кнопки. Поэтому Onchange, я должен знать, какая кнопка была нажата!.

Я попытался присвоить // key: ValueKey(counter), конструктору SwitchListTile, но не смог получить это значение в onChanged.

class MySwitchListTilesContainer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[800],
      body: ListView(
        children: List.generate(20, (i)=>MySwitchListTile(

        )),
      ),
    );
  }
}
class MySwitchListTile extends StatefulWidget {

  @override
  _MySwitchListTileState createState() => new _MySwitchListTileState();
}

class _MySwitchListTileState extends State<MySwitchListTile> {
  bool _v = false;
  @override
  Widget build(BuildContext context) {
    return  SwitchListTile(
      value:_v,
      onChanged: (value) {
          _onChanged(value, counter);
        },


    );
  }
}

void _onChanged(bool _v, int index) {
    setState(() {
      _v = _v;
      if (index == 1) {

        print(index);

      } else {
       print(index +1);
      }
    });
  }

1 Ответ

0 голосов
/ 14 февраля 2020

Вы можете скопировать и вставить полный код ниже
Вы можете передать callback для использования в onChanged

фрагмент кода

ListView(
        children: List.generate(
            20,
            (i) => MySwitchListTile(
                  v: false,
                  callback: () {
                    print("index is $i");
                    setState(() {
                    });
                  },
                )),
      )
...   
class MySwitchListTile extends StatefulWidget {
  final bool v;
  final VoidCallback callback;

...  
return SwitchListTile(
      value: widget.v,
      onChanged: (value) {
        widget.callback();
      },
    );  

рабочая демонстрация

enter image description here

вывод рабочей демонстрации

I/flutter ( 6597): index is 0
I/flutter ( 6597): index is 2
I/flutter ( 6597): index is 6

полный код

import 'package:flutter/material.dart';

class MySwitchListTilesContainer extends StatefulWidget {
  @override
  _MySwitchListTilesContainerState createState() => _MySwitchListTilesContainerState();
}

class _MySwitchListTilesContainerState extends State<MySwitchListTilesContainer> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[800],
      body: ListView(
        children: List.generate(
            20,
            (i) => MySwitchListTile(
                  v: false,
                  callback: () {
                    print("index is $i");
                    setState(() {
                    });
                  },
                )),
      ),
    );
  }
}

class MySwitchListTile extends StatefulWidget {
  final bool v;
  final VoidCallback callback;

  const MySwitchListTile({Key key, this.v, this.callback}) : super(key: key);

  @override
  _MySwitchListTileState createState() => new _MySwitchListTileState();
}

class _MySwitchListTileState extends State<MySwitchListTile> {
  @override
  Widget build(BuildContext context) {
    return SwitchListTile(
      value: widget.v,
      onChanged: (value) {
        widget.callback();
      },
    );
  }
}

/*void _onChanged(bool _v, int index) {
  setState(() {
    _v = _v;
    if (index == 1) {
      print(index);
    } else {
      print(index + 1);
    }
  });
}*/

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MySwitchListTilesContainer(),
    );
  }
}
...