Флаттер показывает значения из массива JSON и при нажатии меняет индекс - PullRequest
0 голосов
/ 23 апреля 2020

Я новичок ie в трепетании. У меня есть простое приложение, мне нужно показать значение JSON в моем контейнере, и при нажатии отобразится второе значение.

class _MyHomePageState extends State<MyHomePage> {
  final List _questions = [
    {'would': 'Coffe', 'rather': 'Tea'},
    {'would': 'Coffe', 'rather': 'Tea'},
    {'would': 'Coffe', 'rather': 'Tea'},
  ];

  @override
  Widget build(BuildContext context) {
    final PrimaryColor = const Color(0xff404040);

    final PreferredSizeWidget appBar = AppBar(
      centerTitle: true,
      title: Text(
        'Would you Rather',
        style: TextStyle(fontFamily: 'FredokaOne'),
      ),
      backgroundColor: PrimaryColor,
    );

    return Scaffold(
        backgroundColor: Color(0xff404040),
        appBar: appBar,
        body: Column(
          children: <Widget>[
            InkWell(
              onTap: () => print("And after click here it will change both question"),
              child: Container(
                child: Text(_questions[0].would,),

              ),
            ),
            InkWell(
              onTap: () => print("And after click here it will change both question"),
              child: Container(
                child: Text(_questions[0].rather,),

              ),
            ),
          ],
        ));
  }
}

Здесь у меня есть список вопросов. В 1 массиве есть 2 значения. Мне нужно показать эти 2 значения в каждом контейнере, и когда я нажму на контейнер, появится следующий массив.

1 Ответ

0 голосов
/ 23 апреля 2020

Создайте переменную index, которая будет увеличиваться в nextQuestion. Функция запускается при касании одного из контейнеров. Приращение остановится, как только оно достигнет последнего элемента _questions List. Наконец, используйте индекс при назначении значений Text внутри Контейнеров для изменения при изменении index.

class _MyHomePageState extends State<MyHomePage> {
  final List _questions = [
    {'would': 'Coffe', 'rather': 'Tea'},
    {'would': 'Blue', 'rather': 'Red'},
    {'would': 'Green', 'rather': 'Yellow'},
  ];
  int index = 0;

  @override
  Widget build(BuildContext context) {
    final PrimaryColor = const Color(0xff404040);
    int size = _questions.length;

    void nextQuestion(){
      if(index < size - 1)
      setState(() {
        index++;
      });
      print(index);
    }

    final PreferredSizeWidget appBar = AppBar(
      centerTitle: true,
      title: Text(
        'Would you Rather',
        style: TextStyle(fontFamily: 'FredokaOne'),
      ),
      backgroundColor: PrimaryColor,
    );

    return Scaffold(
        backgroundColor: Color(0xff404040),
        appBar: appBar,
        body: Column(
          children: <Widget>[
            InkWell(
              onTap: nextQuestion,
              child: Container(
                height: 100,
                child: Text(_questions[index]['would']),
              ),
            ),
            InkWell(
              onTap: nextQuestion,
              child: Container(
                height: 100,
                child: Text(_questions[index]['rather']),
              ),
            ),
          ],
        ));
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...