zhyk
zhyk

Reputation: 67

send data to another flutter screen

I need this screen to receive the name (winner X) of the winner that is sent from another screen how can I do this?

on the previous screen I ask the user to type the name and I made an if, if he wins his name appears, I tried with the push navgator and I couldn't

import 'package:flutter/material.dart';

class ganhadorScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Flutter Card Example')),
        backgroundColor: Colors.yellow,
        body: MyCardWidget(),
      ),
    );
  }
}

class MyCardWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return Center(
      child: Container(
        width: 300,
        height: 500,
        padding: const EdgeInsets.all(10.0),
        child: Card(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15.0),
          ),
          color: Colors.red,
          elevation: 10,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              const ListTile(
                title: Text('PARABENS', style: TextStyle(fontSize: 30.0)),
              ),
              Image.asset("assets/images/trofeu.png"),
              Text('winner X',
                  style: TextStyle(fontSize: 18.0))
            ],
          ),
        ),
      ),
    );
  }
}

Upvotes: 0

Views: 83

Answers (2)

DARTender
DARTender

Reputation: 544

You can pass the values through the arguments property of navigation. In the navigation action of the previous page, however you do it,

Navigator.of(context).pushNamed('MyCardWidget', arguments: variable-that-holds-users-name);

In this screen you recieve the text

final name = ModalRoute.of(context)!.settings.arguments.toString();

Now you can use it

Text(name, style: TextStyle(fontSize 17)),

Upvotes: 0

Wouter
Wouter

Reputation: 849

You can pass data as arguments to another class like this:

class MyClass extends StatelessWidget {
  final String data;
  final int number;
  const MyClass({required this.data, required this.number});
  // or like this if you don't like named arguments:
  const MyClass(this.data, this.number);

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

So if the navigator pushes MyClass widget to the screen, you will have to write it like this:

MyClass(data: "some data", number: -1);
// or without named parameters, then like this:
MyClass("some data", -1); //note that without named parameters, the order of the parameters is important!

Upvotes: 4

Related Questions