Search code examples
flutterdartuser-input

How can I reference user inputted data in a different file?


I am creating an app in Flutter and I would like to store and reference a user's name in future dart files. I am currently working on the account setup, and the first dart file contains a textfield where the user must enter in their name. I want to be able to show that user inputted name in a different file, but I am unsure of how to do so. Any help is greatly appreciated!

Where the user inputs their name

Where I want their name to go in a new dart dile


Solution

  • Update: I figured it out! A linked post gave me a hint. (How can I navigate between 2 classes, one of them requires passing data? in flutter)

    Since I already had a controller defined for a different application, I couldn't use TextController(). Instead, I created an empty string and stored the textfield input in it. I then saved it as an argument in RouteSettings(), then used an if/else statement and ModalRoute() to pull the user-inputted value. Thank you everyone for your help!

    I've attached chunks of my code :)

    class _NamePageState extends State<NamePage> {
      String _nickname = "";
    }
    
    // Creation of TextField
    TextField(
                            onChanged: (val) {
                              setState(() {
                                _nickname = val;
                              });
                            },
    )
    
    // Elevated Button info
    ElevatedButton(onPressed: isButtonActive
                    ? () {
                      Navigator.push(context,
                      PageTransition(
                        type: PageTransitionType.rightToLeftJoined,
                        duration: const Duration(milliseconds: 650),
                        child: const SelectionScreen(),
                        childCurrent: widget,
                        settings: RouteSettings(
                          arguments: _nickname)
                      ),);
    
    // Second dart file calling TextField parameter
     Widget build(BuildContext) {
        double _height = MediaQuery.of(context).size.height;
        final data = ModalRoute.of(context)!.settings;
    
        String retrieveString;
    
        if (data.arguments == null) {
          retrieveString = "empty";
        } else {
          retrieveString = data.arguments as String;
        }
    
    // Text being shown
    Text('Hello there $retrieveString!)