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

时间:2019-02-14 10:14:33

标签: random flutter parameter-passing

我有两个有状态的类-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'不会显示为文本?我试图在另一个项目中执行相同的操作,但它确实起作用了,那么我在这里做错了什么?

2 个答案:

答案 0 :(得分: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'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

答案 1 :(得分: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值,则将重新创建使用它们的所有小部件。因此,第二类将使用新数据进行刷新。