如何在有状态小部件之间传递随机数据?

问题描述 投票:0回答:2

我有两个有状态的类 - FirstClass和SecondClass。在FirstClass中我有两个按钮; '+'和' - ',将接收随机数(例如1 + 3或5-2)。然后,这些随机数将在SecondClass中显示为文本。

你可以在互联网上找到一些关于如何将数据传递给有状态小部件的例子(这里有一些很好的链接)。

Passing Data to a Stateful Widget

Passing data to StatefulWidget and accessing it in it's state in Flutter

https://medium.com/@maksimrv/reactive-app-state-in-flutter-73f829bcf6a7 The best way to passing data between widgets in Flutter

所有这些例子的共同之处在于他们假设您的数据是最终的。由于我的数字是随机的,我不能使用final-这就是我被卡住的地方......

我在第一个问题中有点不清楚,但目标是得到像2 + 5 = _的输出。用户将在文本字段中填写答案。然后,在按下按钮后,答案将返回总和并查看答案是否正确。如果答案是正确的 - >这样做,否则 - >这样做。

添加了更好的键盘。

非常感谢你。

import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(MyHome());

class MyHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'passing data',
      theme: ThemeData(primarySwatch: Colors.red),
      home: FirstClass(),
    );
  }
}

class FirstClass extends StatefulWidget {
  @override
  _FirstClassState createState() => _FirstClassState();
}

class _FirstClassState extends State<FirstClass> {
  final random = Random();
  int a, b, sum;
  String output;

  void changeData(String buttonName) {
    setState(() {
      a = random.nextInt(10);
      b = random.nextInt(10);

      if (buttonName == '+') {
        sum = a + b;
        output = '$a + $b = ';
      } else if (buttonName == '-') {
        if (a >= b) {
          sum = a - b;
          output = '$a - $b = ';
        } else if (b > a) {
          //sum cannot be negative here
          sum = b - a;
          output = '$b - $a = ';
        }
      }
      print(sum.toString());
      Navigator.of(context).popUntil(ModalRoute.withName('/'));
      Navigator.of(context).push(MaterialPageRoute(
          builder: (context) => SecondClass(
                sum: sum,
                refresh: changeData,
                output: output,
                  )));
        });
      }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Screen'),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            //      Text('$a + $b = $sum'),
            RaisedButton(child: Text('+'), onPressed: () => 
changeData('+')),
            RaisedButton(child: Text('-'), onPressed: () => changeData('- 
   ')),
               ],
            ),
          ),
        );
      }
    }

class SecondClass extends StatefulWidget {
  final int sum;
  final String output;
  final String correction;

  final Function refresh;

  SecondClass({this.sum, this.refresh, this.output, this.correction});

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

class _SecondClassState extends State<SecondClass> {
  String enterAnswer;
  String correct;

  void changeAnswer() {
    if (enterAnswer.isNotEmpty) {
      if (enterAnswer == widget.sum.toString()) {
        correct = 'Correct';
        print('Correct Answer.');
      } else {
         correct = 'Wrong Answer';
         print('Wrong Answer');
      }
    } else {
      correct = 'Enter Value First';
      print('Enter Value First');
    }
  }

  @override
  void initState() {
    super.initState();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Screen'),
      ),
      body: Center(
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                 children: <Widget>[
                  Text(widget.output),
                  Container(
                      width: 50.0,
                      TextField(
                        keyboardType: TextInputType.number,
                        onChanged: (val) {
                          enterAnswer = val;
                         },
                      )),
                ],
              ),
              RaisedButton(
                  child: Text('Check Answer'), onPressed: () => 
changeAnswer()),
              Text('$correct'),
            ],
          ),
        ),
      ),
    );
  }
}

为什么'$ correct'不会显示为文本?我试图在另一个项目中做同样的事情并且它有效,所以我在这里做错了什么?

random flutter parameter-passing
2个回答
2
投票

你需要的是callback函数再次得到random值。

我假设你想在第二个random sum value单独类中显示screen()

这是与Navigator和类Constructors

码:

import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(MyHome());

class MyHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'passing data',
      theme: ThemeData(primarySwatch: Colors.red),
      home: FirstClass(),
    );
  }
}

class FirstClass extends StatefulWidget {
  @override
  _FirstClassState createState() => _FirstClassState();
}

class _FirstClassState extends State<FirstClass> {
  final random = Random();
  int a, b, sum;
  String output;

  void changeData(String buttonName) {
    setState(() {
      a = random.nextInt(10);
      b = random.nextInt(10);

      if (buttonName == '+') {
        sum = a + b;
        output = '$a + $b = ';
      } else if (buttonName == '-') {
        if (a >= b) {
          sum = a - b;
          output = '$a - $b = ';
        } else if (b > a) {
          //sum cannot be negative here
          sum = b - a;
          output = '$b - $a = ';
        }
      }
      print(sum.toString());
      Navigator.of(context).popUntil(ModalRoute.withName('/'));
      Navigator.of(context).push(MaterialPageRoute(
          builder: (context) => SecondClass(
                sum: sum,
                refresh: changeData,
                output: output,
              )));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Screen'),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            //      Text('$a + $b = $sum'),
            RaisedButton(child: Text('+'), onPressed: () => changeData('+')),
            RaisedButton(child: Text('-'), onPressed: () => changeData('-')),
          ],
        ),
      ),
    );
  }
}

class SecondClass extends StatefulWidget {
  final int sum;
  final String output;

  final Function refresh;

  SecondClass({this.sum, this.refresh, this.output});

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

class _SecondClassState extends State<SecondClass> {
  String enterAnswer;

  @override
  void initState() {
    super.initState();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Screen'),
      ),
      body: Center(
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(widget.output),
                  Container(
                      width: 50.0,
                      child: TextField(
                        onChanged: (val) {
                          enterAnswer = val;
                        },
                      )),
                ],
              ),
              RaisedButton(
                onPressed: () {
                  if (enterAnswer.isNotEmpty) {
                    if (enterAnswer == widget.sum.toString()) {
                      print('Correct Answer.');
                    } else {
                      print('Wrong Answer');
                    }
                  } else {
                    print('Enter Value First');
                  }
                },
                child: Text('Check Answer'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

0
投票

您可以通过第二类的构造函数将数据传递给第二类,并使用widget.your_data访问它。应该使用最终版

因为StatefulWidget继承了标记为@immutable的Widget,所以StatefulWidget的任何子类也必须是不可变的(即所有字段都是final)。

我根据你的问题创建了简单的用例,看看它是否是你想要的:

    class FirstClass extends StatefulWidget {
      @override
      FirstClassState createState() => FirstClassState();
    }

    class FirstClassState extends State<FirstClass> {
      final random = Random();
      int a, b, sum;

      void changeData() {
        setState(() {
          a = random.nextInt(10);
          b = random.nextInt(10);
          sum = a + b;
        });
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: SecondClass(
            a: a,
            b: b,
            sum: sum,
          ),
          floatingActionButton: FloatingActionButton(
            child: Icon(Icons.refresh),
            onPressed: changeData,
          ),
        );
      }
    }

和第二类获取数据是:

     class SecondClass extends StatefulWidget {
      final int a;
      final int b;
      final int sum;

      SecondClass({this.a, this.b, this.sum});

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

    class _SecondClassState extends State<SecondClass> {
      @override
      Widget build(BuildContext context) {
        return Container(
          child: Center(
            child: Text('${widget.a} + ${widget.b} = ${widget.sum}'),
          ),
        );
      }
    }

这里,如果通过setState()方法在第一类中更改a,b和sum值,则将重新创建使用它们的所有小部件。因此,第二类用新数据刷新。

© www.soinside.com 2019 - 2024. All rights reserved.