Флаттер показывает ошибку Операция не определена - PullRequest
0 голосов
/ 05 мая 2020
• 1000
class _MyHomePageState extends State<MyHomePage> {

  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();
  }


  int index = 0;
  bool shouldShow = false;

  @override
  Widget build(BuildContext context) {
    int size = _questions.length;

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

    double percentage1Calculate() {
      int wouldClick = int.parse(_questions[index]['wouldClick']);
      int ratherClick = int.parse(_questions[index]['ratherclick']);
      double percentage1 = wouldClick / (wouldClick + ratherClick) * 100;
      return percentage1;
    }

    double percentage2Calculate() {
      int wouldClick = int.parse(_questions[index]['wouldClick']);
      int ratherClick = int.parse(_questions[index]['ratherClick']);
      double percentage2 = ratherClick / (wouldClick + ratherClick) * 100;
      return percentage2;
    }

    void percengtageTrigger(){
      setState(() {
        shouldShow = true;
      });
      Timer timer = Timer(Duration(milliseconds: 1350), () {
        setState(() {
          shouldShow = false;
        });
      });
    }

    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: Stack(
          children: [
            GestureDetector(
              onTap: () {
                percengtageTrigger();
              },
              child: Container(
                height: stackHeight * 0.5,
                width: stackWidth,
                color: Colors.blue,
                child: Column(
                  children: <Widget>[
                    shouldShow
                        ? Container(
                            padding: const EdgeInsets.only(top: 10, right: 10),
                            height: stackHeight * 0.1,
                            color: Colors.blue,
                            width: double.infinity,
                            child: Column(
                              mainAxisSize: MainAxisSize.max,
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: <Widget>[
                                Text(
                                  '${percentage1Calculate().toStringAsFixed(0)}%',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 23,
                                    fontFamily: 'NewsCycle',
                                  ),
                                ),
                              ],
                            ))
                        : Container(
                            height: stackHeight * 0.1,
                            color: Colors.blue,
                            width: double.infinity,
                          ),
                    Container(
                        color: Colors.blue,
                        height: stackHeight * 0.4,
                        width: double.infinity,
                        child: Column(
                          children: <Widget>[
                            Padding(
                              padding: const EdgeInsets.only(top: 20),
                              child: Text(
                                _questions[index]['would'],
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 23,
                                  fontFamily: 'NewsCycle',
                                ),
                              ),
                            ),
                          ],
                        )),
                  ],
                ),
              ),
            ),
            GestureDetector(
              onTap: () {
                percengtageTrigger();
              },
              child: Align(
                alignment: Alignment.bottomCenter,
                child: Container(
                  height: stackHeight * 0.5,
                  width: stackWidth,
                  color: Colors.red,
                  child: Column(
                    children: <Widget>[
                      shouldShow
                          ? Container(
                              padding:
                                  const EdgeInsets.only(top: 10, right: 10),
                              height: stackHeight * 0.1,
                              color: Colors.red,
                              width: double.infinity,
                              child: Column(
                                mainAxisSize: MainAxisSize.max,
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: <Widget>[
                                  Text(
                                    '${percentage2Calculate().toStringAsFixed(0)}%',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 23,
                                      fontFamily: 'NewsCycle',
                                    ),
                                  ),
                                ],
                              ))
                          : Container(
                              height: stackHeight * 0.1,
                              color: Colors.red,
                              width: double.infinity,
                            ),
                      Container(
                          color: Colors.red,
                          height: stackHeight * 0.4,
                          width: double.infinity,
                          child: Column(
                            children: <Widget>[
                              Padding(
                                padding: const EdgeInsets.only(top: 40),
                                child: Text(
                                  _questions[index]['rather'],
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 23,
                                    fontFamily: 'NewsCycle',
                                  ),
                                ),
                              ),
                            ],
                          )),
                    ],
                  ),
                ),
              ),
            ),
            Align(
              alignment: Alignment.center,
              child: Container(
                width: stackWidth,
                height: stackHeight * 0.015,
                color: Color(0xff404040),
              ),
            ),
            Align(
              alignment: Alignment.center,
              child: Container(
                  width: stackWidth,
                  height: stackHeight * 0.15,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: Color(0xff404040),
                  ),
                  child: Align(
                    alignment: Alignment.center,
                    child: GestureDetector(
                      onTap: () {
                        nextQuestion();
                      },
                      child: Text(
                        "SKIP",
                        style: TextStyle(
                            color: Colors.white,
                            fontFamily: 'FredokaOne',
                            fontSize: 27),
                      ),
                    ),
                  )),
            ),
          ],
        ));
  }
}

А вот модель. Dart

import 'package:flutter/material.dart';

class Questions {
  String would;
  String rather;
  int wouldClick;
  int ratherClick;

  Questions(int wouldClick, int ratherClick, String would, String rather) {
    this.wouldClick = wouldClick;
    this.ratherClick = ratherClick;
    this.would = would;
    this.rather = rather;
  }

  Questions.fromJson(Map json)
      : wouldClick = json['wouldClick'],
        ratherClick = json['ratherClick'],
        would = json['would'],
        rather = json['rather'];

  Map toJson() {
    return {'wouldClick': wouldClick, 'ratherClick': ratherClick, 'would': would, 'rather': rather};
  }
  @override
  String toString() {
    return "{would: $would, rather: $rather, wouldClick: $wouldClick, ratherClick: $ratherClick}";
  }
}

Я просто показываю данные по значению индекса, печать вопросов

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

Но он показывает ошибку, когда я использую значение, как в коде, я использую _questions [index] ['wouldClick'], здесь отображается ошибка в wouldClick, что операция не определена в вопросе (это модель)

I Думаю, проблема в том, что функция загружается до того, как API извлекает данные. Есть ли возможность запустить функцию или показать ее после получения данных?

...