简体   繁体   English

Flutter/Dart:在使用 setState() 时更新一些变量而不是其他变量

[英]Flutter/Dart: update some variables but not others when using setState()

I'm trying to improve my understanding of Flutter, and am struggling with an issue.我正在努力提高我对 Flutter 的理解,并且正在努力解决一个问题。 I am trying to create an app that presents a list of cards which pull data from a list.我正在尝试创建一个应用程序,该应用程序显示从列表中提取数据的卡片列表。 There is a button on the bottom that creates a new card when the user clicks it.底部有一个按钮,当用户单击它时会创建一个新卡。

I am trying to get each card to display a unique 'Round number'.我试图让每张卡显示一个唯一的“轮数”。 So for example each time the user clicks the button, a card will be added that displays sequential numbers next to the word 'Round'.因此,例如,每次用户单击按钮时,都会添加一张卡片,在单词“Round”旁边显示序列号。 Round 1 > Round 2 > Round 3 and so on.第 1 轮 > 第 2 轮 > 第 3 轮等等。

Right now everything works except that every time the button is pressed all the cards are updated with the latest number.现在一切正常,除了每次按下按钮时,所有卡片都会更新为最新的数字。 And so instead of getting a sequential list of cards, every card is updated to the latest round number.因此,不是获取连续的卡片列表,而是将每张卡片更新为最新的回合数。

What am I doing wrong?我究竟做错了什么? Thank you.谢谢你。

Here is my code:这是我的代码:


import 'package:flutter/material.dart';

class Round {

  int roundNumber;
  int firstNumber;
  int secondNumber;

  Round({ this.roundNumber, this.firstNumber, this.secondNumber, });

}

int uid = 1;

List<Round> roundsList = [
  Round(roundNumber: uid, firstNumber: 1, secondNumber: 2),
];


class createLevels extends StatefulWidget {
  @override
  _createLevelsState createState() => _createLevelsState();
}

class _createLevelsState extends State<createLevels> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
          title: Text("Create Rounds",)
      ),
      body: Padding(
        padding: const EdgeInsets.fromLTRB(20, 20, 20.0, 20),
        child: Container(
          child: Column(
              children: <Widget>[
                Expanded(
                  child: ListView.builder(
                    itemCount: roundsList.length,
                      itemBuilder: (BuildContext context, int whatIsThisVariable) {
                      return roundCard(Round(roundNumber: uid, firstNumber: 2, secondNumber: 3,));
                      }
                  ),
                ),
                Text("$roundsList"),
                RaisedButton(
                  onPressed: () {
                    uid++;
                    roundsList.add(Round(roundNumber: uid));
                    setState(() {});
                  },
                    child: Text("Add Round"),
                ),
              ],
          ),
        ),
      ),
    );
  }
}

class roundCard extends StatelessWidget {

  final Round round;

  roundCard(this.round);

  // roundsList.add(Round(roundNumber: 1));

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Card(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Spacer(
                  flex: 1,
                ),
                Expanded(
                  child: Text('Round ${round.roundNumber}:'),
                  flex: 12,
                ),
                Expanded(
                  child: TextFormField(
                      textAlign: TextAlign.center,
                      decoration: InputDecoration(
                        hintText: '${round.firstNumber}',
                      ),
                  ),
                  flex: 3,
                ),
                Spacer(
                  flex: 1,
                ),
                Expanded(
                  child: TextFormField(
                      textAlign: TextAlign.center,
                      decoration: InputDecoration(
                        hintText: '${round.secondNumber}',
                      ),
                  ),
                  flex: 3,
                ),
              ],
            ),
          )
      ),
    );
  }
}

You can copy paste run full code below您可以在下面复制粘贴运行完整代码
You need to pass index not uid您需要传递index而不是uid
You can adjust first and second number you want您可以调整您想要的第一个和第二个数字

code snippet代码片段

itemBuilder: (BuildContext context, int index) {
                  return roundCard(roundsList[index]);
                }),
...
onPressed: () {
                  uid++;
                  firstNumber++;
                  secondNumber++;
                  roundsList.add(
                      Round(roundNumber: uid, firstNumber: firstNumber, secondNumber: secondNumber));
                  setState(() {});
                }

working demo工作演示

在此处输入图片说明

full code完整代码

import 'package:flutter/material.dart';

class Round {
  int roundNumber;
  int firstNumber;
  int secondNumber;

  Round({
    this.roundNumber,
    this.firstNumber,
    this.secondNumber,
  });
}

int uid = 1;
int firstNumber = 2;
int secondNumber = 3;

List<Round> roundsList = [
  Round(roundNumber: uid, firstNumber: 1, secondNumber: 2),
];

class createLevels extends StatefulWidget {
  @override
  _createLevelsState createState() => _createLevelsState();
}

class _createLevelsState extends State<createLevels> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          centerTitle: true,
          title: Text(
            "Create Rounds",
          )),
      body: Padding(
        padding: const EdgeInsets.fromLTRB(20, 20, 20.0, 20),
        child: Container(
          child: Column(
            children: <Widget>[
              Expanded(
                child: ListView.builder(
                    itemCount: roundsList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return roundCard(roundsList[index]);
                    }),
              ),
              Text("$roundsList"),
              RaisedButton(
                onPressed: () {
                  uid++;
                  firstNumber++;
                  secondNumber++;
                  roundsList.add(
                      Round(roundNumber: uid, firstNumber: firstNumber, secondNumber: secondNumber));
                  setState(() {});
                },
                child: Text("Add Round"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class roundCard extends StatelessWidget {
  final Round round;

  roundCard(this.round);

  // roundsList.add(Round(roundNumber: 1));

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Card(
          child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Spacer(
              flex: 1,
            ),
            Expanded(
              child: Text('Round ${round.roundNumber}:'),
              flex: 12,
            ),
            Expanded(
              child: TextFormField(
                textAlign: TextAlign.center,
                decoration: InputDecoration(
                  hintText: '${round.firstNumber}',
                ),
              ),
              flex: 3,
            ),
            Spacer(
              flex: 1,
            ),
            Expanded(
              child: TextFormField(
                textAlign: TextAlign.center,
                decoration: InputDecoration(
                  hintText: '${round.secondNumber}',
                ),
              ),
              flex: 3,
            ),
          ],
        ),
      )),
    );
  }
}

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

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM