jeudi 14 février 2019

How do I pass random data between statefull widgets?

I am having two stateful classes - FirstClass and SecondClass. In FirstClass I have two buttons; '+' and '-', wich will recieve random numbers (such as 1+3 or 5-2). Those random numbers are then to be displayed as text in SecondClass.

You can find a few examples on internet on how to pass data to a stateful widget (here are some good links).

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

What all these examples have in common is that they assume that your data is final. Since my numbers are random I cannot use final- and this is where I get stuck...

Below is a simplified version of what I'm trying to achive (just to show the random part). The cruical difference between this snippet and my goal is the passing of data to another class.

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

void main() {
  runApp(MaterialApp(home: ChartPage()));
}

class ChartPage extends StatefulWidget {
  @override
  ChartPageState createState() => ChartPageState();
}

class ChartPageState extends State<ChartPage> {
  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: Center(
        child: Text('$a + $b = $sum'),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.refresh),
        onPressed: changeData,
      ),
    );
  }
}




Aucun commentaire:

Enregistrer un commentaire