简体   繁体   中英

how can i pass data inside mainlocal or mainforeign screen's profilescreen in flutter?

i have a first screen which is the myinputpage. the user will enter its info. if they submit it, and chose foreign or local then the app will direct them to another screen which is either local or forign, depends on the selected radio button. both local and foreign screen has an action button which is the profilescreen. my problem is i don't know how to pass the data of myinputpage into the profilescreen. how can i pass those data into a screen which has an another screen? i only know how to pass data into the second screen but not into the screen where it has another screen to pass it on

main.dart

import 'package:flutter/material.dart';
import 'package:my_app/screens/userdata.dart';
import 'package:my_app/screens/mainscreenforeign.dart';
import 'package:my_app/screens/mainscreenlocal.dart';
import 'package:my_app/screens/mainscreenprofile.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.deepOrange,
      ),
      initialRoute: '/',
      routes: {
        '/': (context) => MyInputPage(),
        '/mainForeign': (context) => MainScreenForeign(),
        '/mainLocal': (context) => MainScreenLocal(),
        '/mainProfile': (context) => MainScreenProfile(),
      },
    );
  }
}

myinputpage.dart

import 'package:flutter/material.dart';
import 'package:my_app/mainscreenprofile.dart';

class MyInputPage extends StatefulWidget {
  MyInputPage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyInputPageState extends State<MyInputPage> {
  final _formKey = GlobalKey<FormState>();

  String usernameVal = '', fullNameVal = '', ageVal = '', selectLocalOrForeign = '', selectError = '';

  void _setValue() {
    setState(() {
      if (!_formKey.currentState.validate() && selectLocalOrForeign.isEmpty) {
        if (selectLocalOrForeign.isEmpty) {
          selectError = 'Please select your Recipe';
        } else {
          selectError = '';
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      autovalidateMode: AutovalidateMode.disabled,
      key: _formKey,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          backgroundColor: Colors.black,
          title: Text(
            'Local and Foreign',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          elevation: 0,
        ),
        body: SingleChildScrollView(
          child: Container(
            child: Column(children: [
              Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(
                  vertical: 20.0,
                  horizontal: 10.0,
                ),
                child: Column(
                  children: [
                    SizedBox(height: 15.0),
                    TextFormField(
                        keyboardType: TextInputType.text,
                        textCapitalization: TextCapitalization.words,
                        decoration: InputDecoration(
                            labelText: 'Username',
                            labelStyle: TextStyle(
                              fontWeight: FontWeight.bold,
                            ),
                            hintText: 'Enter your Username here',
                            ),
                        onChanged: (value) {
                          usernameVal = value;
                        },
                        validator: (value) {
                          if (value.isEmpty) {
                            return 'Please Enter your Username.';
                          } else {
                            return null;
                          }
                        }),
                    SizedBox(
                      height: 15.0,
                    ),
                    TextFormField(
                        keyboardType: TextInputType.text,
                        textCapitalization: TextCapitalization.words,
                        decoration: InputDecoration(
                            labelText: 'Full Name',
                            labelStyle: TextStyle(
                              fontWeight: FontWeight.bold,
                            ),
                            hintText: 'Enter your Full Name here',
                            ),
                        onChanged: (value) {
                          fullNameVal = value;
                        },
                        validator: (value) {
                          if (value.isEmpty) {
                            return 'Please Enter your Full Name.';
                          } else {
                            return null;
                          }
                        }),
                    SizedBox(
                      height: 15.0,
                    ),
                    TextFormField(
                        keyboardType: TextInputType.text,
                        textCapitalization: TextCapitalization.words,
                        decoration: InputDecoration(
                            labelText: 'Age',
                            labelStyle: TextStyle(
                              fontWeight: FontWeight.bold,
                            ),
                            hintText: 'Enter your Age here',
                            ),
                        onChanged: (value) {
                          ageVal = value;
                        },
                        validator: (value) {
                          if (value.isEmpty) {
                            return 'Please Enter your Age.';
                          } else {
                            return null;
                          }
                        }),
                    SizedBox(height: 10.0),
                    Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                      SizedBox(width: 10.0),
                      Text(
                        'Please Choose',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 18.0,
                        ),
                      ),
                    ]),
                    SizedBox(height: 15.0),
                    Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                      Radio(
                        value: 'Foreign',
                        groupValue: selectLocalOrForeign,
                        onChanged: (value) {
                          setState(() {
                            selectLocalOrForeign = value;
                          });
                        },
                      ),
                      SizedBox(width: 10.0),
                      Text(
                        'Foreign',
                      ),
                      SizedBox(width: 40.0),
                      Radio(
                        value: 'Local',
                        groupValue: selectLocalOrForeign,
                        onChanged: (value) {
                          setState(() {
                            selectLocalOrForeign = value;
                          });
                        },
                      ),
                      SizedBox(width: 10.0),
                      Text(
                        'Local',
                      ),
                    ]),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        SizedBox(width: 11.0),
                        Text(
                          selectError,
                          style: TextStyle(
                            color: Colors.red[700],
                          ),
                        ),
                      ],
                    ),
                    
                    SizedBox(
                      height: 15.0,
                    ),
                    SizedBox(
                      height: 40.0,
                      width: double.infinity,
                      child: ElevatedButton(
                          onPressed: () {
                            _setValue();
                            if (_formKey.currentState.validate() && !selectLocalOrForeign.isEmpty) {
                              if (selectLocalOrForeign == 'Foreign') {
                                Navigator.pushNamed(context, '/mainForeign');
                              }
                              if (selectLocalOrForeign == 'Local') {
                                Navigator.pushNamed(context, '/mainLocal');
                              }
                            }
                          },
                          child: Text(
                            'Proceed',
                            style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20),
                          )),
                    ),
                    SizedBox(
                      height: 15.0,
                    ),
                  ],
                ),
              ),
            ]),
          ),
        ),
      ),
    );
  }
}

mainscreenforeign.dart

import 'package:flutter/material.dart';

class MainScreenForeign extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.grey[850],
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          automaticallyImplyLeading: false,
          title: Text('Foreign'),
          actions: <Widget>[
            Padding(
                padding: EdgeInsets.only(
                  right: 15.0,
                ),
                child: IconButton(
                  icon: Icon(
                    Icons.account_circle,
                    color: Colors.white,
                    size: 25.0,
                  ),
                  onPressed: () {
                    Navigator.pushNamed(context, '/mainProfile');
                  },
                ))
          ],
        ),
        body: Text(
          'Main Screen for Foreign',
          style: TextStyle(color: Colors.white),
        ));
  }
}

mainscreenlocal.dart

import 'package:flutter/material.dart';

class MainScreenLocal extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.grey[850],
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          automaticallyImplyLeading: false,
          title: Text('Local'),
          actions: <Widget>[
            Padding(
                padding: EdgeInsets.only(
                  right: 15.0,
                ),
                child: IconButton(
                  icon: Icon(
                    Icons.account_circle,
                    color: Colors.white,
                    size: 25.0,
                  ),
                  onPressed: () {
                    Navigator.pushNamed(context, '/mainProfile');
                  },
                ))
          ],
        ),
        body: Text(
          'Main Screen for Local',
          style: TextStyle(color: Colors.white),
        ));
  }
}

mainscreenprofile.dart

import 'package:flutter/material.dart';

class MainScreenProfile extends StatelessWidget {
  final String username, fullName, age;
  MainScreenProfile({this.username, this.fullName, this.age});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Profile'),
      ),
      body: Container(
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          SizedBox(height: 10.0),
          Text(username),
          Text(fullName),
          Text(age),
          SizedBox(height: 10.0),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: Text('Return'),
          ),
        ]),
      ),
    );
  }
}

What you're looking for is to send data across ur Navigator fro pushNamed. Here is the link for it:

https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments

The button onPressed in the inputPage would look like:

Navigator.pushNamed(context, '/mainLocal', arguments: [
    usernameVal,
    ageVal]
  ));

And you'll have to change the the mainScreenLocal to use ur values obviously but this is a sample:

class MainScreenLocal extends StatelessWidget {
  final args = ModalRoute.of(context)!.settings.arguments as List;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Container(
        child: Text(args[0])
      )
    );
  }

You can even create ur own class to handle arguments:

class ScreenArguments {
  final String title;
  final String message;
  
  //constructor 
  ScreenArguments(this.title, this.message);
}

//inputPage on pressed: 
Navigator.pushNamed(context, '/mainLocal', arguments: ScreenArguments(
    usernameVal,
    ageVal)
));

//then MainScreenLocal would look like 
class MainScreenLocal extends StatelessWidget {
  final args = ModalRoute.of(context)!.settings.arguments as ScreenArguments;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Container(
        child: Text(args.title)
      )
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM