首页 > 解决方案 > Flutter 显示数据并在点击时更改它

问题描述

我有一个任务,我需要显示来自 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

标签: flutterdart

解决方案


您可以轻松地执行以下操作,

第一步:声明变量,保持点击次数,保持显示值

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'),
        )
      ],
    ));

推荐阅读