Home > front end >  Turning Flutter Arguments into Usable Variables on another dart file
Turning Flutter Arguments into Usable Variables on another dart file

Time:12-31

My final goal is to have a userName variable from one dart file transferred to the other dart file.

Firebase Authentication will only take the email and password inputs so I need to pass the userName variable as an argument into another file that is called after the users email has been verified.

I have been trying to find videos and documentation online, most of what I found is trying to put the data into a list (which I would like to avoid). I don't understand the "this." getter function in flutter yet, I don't know if it's necessary to solve this problem. Let me know if there's anything I can clarify, I hope I'm overlooking something simple.

Dart File #1

onPressed: () => signUp(_email, _password).then((_) {
    Navigator.of(context).pushReplacement(
    MaterialPageRoute(builder: (context) => Verify(_userName)));
}),

Dart File #2

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

class Verify extends StatefulWidget {
  const Verify(String _userName, {Key? key}) : super(key: key);

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

class _VerifyState extends State<Verify> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child:
            Text('Here is your variable $_userName please verify'),
      ),
    );
  }

CodePudding user response:

I guess you're asking about passing arguments(any object) between different screens. You can do this easily by passing it in RouteSettings, you can pass any object (String, int, map) and then fetch it in the build method of another Screen.

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
  return TextButton(
    onPressed: () => Navigator.push(
    context, MaterialPageRoute(
      builder: (context) => HomeScreen(), 
      settings: const RouteSettings(arguments: 'username')),), //arguments
    child: Text('Hello, World!', 
              style: Theme.of(context).textTheme.headline4,
    ),
  );
}
}

class HomeScreen extends StatelessWidget {
  @override
Widget build(BuildContext context) {
final args = ModalRoute.of(context)!.settings.arguments as String; //arguments
  return TextButton(
    onPressed: () {},
    child: Text(args, 
              style: Theme.of(context).textTheme.headline4,
    ),
  );
}
}
  • Related