Home > front end >  how to send Data to other screen?
how to send Data to other screen?

Time:04-08

import 'package:flutter/material.dart';
import 'package:flutter_bmi_app/second_screen.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class BmiCalc extends StatefulWidget {
  const BmiCalc({Key? key}) : super(key: key);

  @override
  State<BmiCalc> createState() => _BmiCalcState();
}

class _BmiCalcState extends State<BmiCalc> {
  Color colorOfLittleBox = Color.fromARGB(255, 27, 28, 48);
  Color colorOfLittleBox2 = Colors.pink;
  bool isMale = true;

  double _value = 150;
  int weight = 60;
  int age = 25;
  double answer = 10;
  String calc = "CALCULATE";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromARGB(255, 12, 9, 34),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              Row(
                children: [
                  FemaleBox("MALE", Icons.male),
                  FemaleBox("FEMALE", Icons.female),
                ],
              ),
              Column(children: [
                Container(
                    padding: EdgeInsets.all(32),
                    margin: EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      color: Color.fromARGB(255, 27, 28, 48),
                      borderRadius: BorderRadius.circular(15),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Text("HEIGHT",
                            style: TextStyle(color: Colors.grey, fontSize: 20)),
                        const SizedBox(
                          height: 10,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(_value.toStringAsFixed(0),
                                style: const TextStyle(
                                    fontSize: 45,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w900)),
                            const Text(
                              "cm",
                              style:
                                  TextStyle(fontSize: 20, color: Colors.grey),
                            ),
                          ],
                        ),
                        Slider(
                          min: 100,
                          max: 230,
                          thumbColor: Colors.pink,
                          value: _value,
                          onChanged: (value) {
                            setState(() {
                              _value = value;
                            });
                          },
                        ),
                      ],
                    ))
              ]),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Operation("Weight"),
                  Operation("Age"),
                ],
              ),
              Container(
                decoration: BoxDecoration(
                  color: Colors.pink,
                  borderRadius: BorderRadius.circular(15),
                ),
                padding: EdgeInsets.only(bottom: 5),
                width: MediaQuery.of(context).size.width,
                child: TextButton(
                  child: Text(
                    calc,
                    style: const TextStyle(
                        fontSize: 22,
                        color: Colors.white,
                        fontWeight: FontWeight.w900),
                  ),
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => SecondScreen()),

                    );
                  },
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  void calculate() {
    answer = (weight / (_value * _value)) * 10000;
    Text(answer.toString(),
        style: const TextStyle(fontSize: 40, color: Colors.white));
    if (calc == "CALCULATE") {
      calc = answer.toStringAsFixed(1);
    } else {
      calc = "CALCULATE";
    }
    setState(() {});
  }

}

I made bmi calculator, I wanna have answer on other screen. I want to send this function calculate() to the second screen, where I will have the answer of this calculation. I gave Navigator.push( context, MaterialPageRoute(builder: (context) => SecondScreen()), but how to make it work? Thank you in advance.

CodePudding user response:

Make the SecondScreen constructor take a parameter for the type of data that you want to send to it.

 const SecondScreen(
          {Key? key,required this.answer, })
          : super(key: key);
      final String? answer; //define value you want to pass
    
      @override
      _SecondScreenScreenState createState() => _SecondScreenState();
    }

And pass data when navigate

Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => SecondScreen(answer: 'Hello',),
    ));

CodePudding user response:

here is the example:

import 'package:flutter/material.dart';

class Todo {
  final String title;
  final String description;

  const Todo(this.title, this.description);
}

void main() {
  runApp(
    MaterialApp(
      title: 'Passing Data',
      home: TodosScreen(
        todos: List.generate(
          20,
          (i) => Todo(
            'Todo $i',
            'A description of what needs to be done for Todo $i',
          ),
        ),
      ),
    ),
  );
}

class TodosScreen extends StatelessWidget {
  const TodosScreen({Key? key, required this.todos}) : super(key: key);

  final List<Todo> todos;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Todos'),
      ),
      body: ListView.builder(
        itemCount: todos.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(todos[index].title),
            // When a user taps the ListTile, navigate to the DetailScreen.
            // Notice that you're not only creating a DetailScreen, you're
            // also passing the current todo through to it.
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => DetailScreen(todo: todos[index]),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

class DetailScreen extends StatelessWidget {
  // In the constructor, require a Todo.
  const DetailScreen({Key? key, required this.todo}) : super(key: key);

  // Declare a field that holds the Todo.
  final Todo todo;

  @override
  Widget build(BuildContext context) {
    // Use the Todo to create the UI.
    return Scaffold(
      appBar: AppBar(
        title: Text(todo.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Text(todo.description),
      ),
    );
  }
}

I can't get the FemaleBox and Operation in your project so I can't run that try the above example or share you full code include second screen also

CodePudding user response:

add a constructor in your second screen and pass it while calling second screen

const SecondScreen(
      {Key? key,required this.answer, })
      : super(key: key);
  final String? answer; //define value you want to pass

  @override
  _SecondScreenScreenState createState() => _SecondScreenState();
}
Navigator.push(
context,
MaterialPageRoute(
  builder: (context) => SecondScreen(answer: 'Hello',),
));

CodePudding user response:

There is another way to do that.

  1. Create a class as given below and use static keyword to define any variable.

  2. Now you can call this variable at your entire app via- Common.sharedData

  3. So you can modified it according to you

    Class Common{ static int sharedData=0; //Other function }

CodePudding user response:

There are different ways to solve this

  1. Sending parameters through constructor (Good solution).
  2. Use a State Management package and hold the state in its class and access tit everywhere (Recommended way).
  3. declare variable globally and use it anywhere in the app (not Recommended)
  • Related