Flutter показывает данные и меняет их при нажатии - PullRequest
0 голосов
/ 05 мая 2020

У меня есть задание, мне нужно показать значение из Apis, а затем при нажатии на поднятую кнопку появится следующее значение

Вот мой код

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {

    var _questions = new List<Questions>();

    _getQuestions() {
      API.getUsers().then((response) {
        setState(() {

          Iterable list = json.decode(response.body);
          print(list);
          print(list);
          _questions = list.map((model) => Questions.fromJson(model)).toList();
          print(_questions);
        });
      });
    }
    initState() {
      super.initState();
      _getQuestions();
    }


    final PrimaryColor = const Color(0xff404040);

    final PreferredSizeWidget appBar = AppBar(
      centerTitle: true,
      title: Text(
        'Would you Rather',
        style: TextStyle(fontFamily: 'FredokaOne'),
      ),
      backgroundColor: PrimaryColor,
    );
    double stackHeight = (MediaQuery.of(context).size.height -
        appBar.preferredSize.height -
        MediaQuery.of(context).padding.top);
    double stackWidth = MediaQuery.of(context).size.width;
    return Scaffold(
        backgroundColor: Color(0xff404040),
        appBar: appBar,


        body: Column(
          children: <Widget>[
            Container(
              child: Text('need to show value here'),
            ),
            RaisedButton(
              onPressed: on this press i need to change value,
              child: Text('next'),
            )
          ],
        ));
  }
}

Как видите в _questions здесь массив в формате json, мне нужно распечатать значение, и при нажатии будет отображаться следующее значение.

Получение данных из api выглядит следующим образом

[
  {
    "rather": "Tea",
    "would": "Coffe",
    "wouldClick": 15,
    "ratherClick": 12
  },
  {
    "rather": "Oil",
    "would": "Soap",
    "wouldClick": 50,
    "ratherClick": 12
  },
  {
    "rather": "Soap",
    "would": "Shaving Cream",
    "wouldClick": 15,
    "ratherClick": 12
  }
]

Мне нужно для отображения значения rather из данных и при щелчке мыши необходимо изменить другое значение rather

1 Ответ

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

Вы можете легко сделать это следующим образом:

Шаг 1: Объявите переменные, чтобы сохранить счетчик кликов и сохранить отображаемое значение

int currentValue = 0;

String value = "";

Шаг 2: В событии Click поместите if-else и выполните следующие действия:

if (currentValue >= _questions.length) {
    currentValue = 0;

    setState(() {
       value = items[currentValue].rather;
    });

} else {
     setState(() {
         value = items[currentValue].rather;
     });
     currentValue ++;
}

Шаг 3: Установите объявленную переменную внутри display Text ()

child: Text(value)

Полноразмерные виджеты должны выглядеть так:

 body: Column(
      children: <Widget>[
        Container(
          child: Text(value),
        ),
        RaisedButton(
          onPressed: (){
              if (currentValue >= items.length) {
                 currentValue = 0;

                 setState(() {
                    value = items[currentValue];
                 });

               } else {
                 setState(() {
                   value = items[currentValue];
                 });
                 currentValue ++;
               }
          }
          child: Text('next'),
        )
      ],
    ));
...