Workshop: Flutter Auth Login #part8 send ScreenArguments to EditProfilePage

Create ScreenArguments.dart

class ScreenArguments {
  final String name;
  final String surname;

  ScreenArguments(this.name, this.surname);
}

ProfilePage.dart

import 'ScreenArguments.dart';
@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('ProfilePage'),
          actions: [
            IconButton(
                onPressed: () {
                  _openEditPage();
                },
                icon: Icon(Icons.edit))
          ],
        ),
...
  _openEditPage() {
    //open EditProfilePage with ScreenArguments
    Navigator.pushNamed(context, '/editprofile',
        arguments: ScreenArguments(
          profile['name'],
          profile['surname'],
        ));
  }

EditProfilePage.dart

import 'ScreenArguments.dart';
@override
Widget build(BuildContext context) {
  final screenAgr =
    ModalRoute.of(context)!.settings.arguments as ScreenArguments;
  return Scaffold(
    appBar: AppBar(
      Text('${screenAgr.name} ${screenAgr.surname}')
    ),

Run & Debug

add FormBuider to EditProfilePage.dart and pull name , surename from ScreenArguments

@override
  Widget build(BuildContext context) {
  final screenAgr =
    ModalRoute.of(context)!.settings.arguments as ScreenArguments;
  ...
  FormBuilder(
        key: _formKey,
        initialValue: {
           'name': screenAgr.name,
           'surname': screenAgr.surname,
        },
  ...

Run & Debug

ProfilePage.dart

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert' as convert;
import 'ScreenArguments.dart';

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

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

class _ProfilePageState extends State<ProfilePage> {
  SharedPreferences? sharePrefs;
  Map<String, dynamic> profile = {'username': '', 'name': '', "surname": ''};

  _getSharedPreferences() async {
    sharePrefs = await SharedPreferences.getInstance();

    var profileString = sharePrefs!.getString('profile');
    print('profileString');
    print(profileString);
    if (profileString != null) {
      setState(() {
        profile = convert.jsonDecode(profileString);
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _getSharedPreferences();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('ProfilePage'),
          actions: [
            IconButton(
                onPressed: () {
                  _openEditPage();
                },
                icon: Icon(Icons.edit))
          ],
        ),
        body: Container(
            padding: const EdgeInsets.all(20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Column(
                  children: [
                    Text('email: ${profile['username']} ',
                        style: TextStyle(fontSize: 20, color: Colors.grey)),
                    SizedBox(height: 20),
                    Text('name: ${profile['name']} ',
                        style: TextStyle(fontSize: 20, color: Colors.grey)),
                    SizedBox(height: 20),
                    Text('surname: ${profile['surname']} ',
                        style: TextStyle(fontSize: 20, color: Colors.grey)),
                    SizedBox(height: 40),
                    MaterialButton(
                      onPressed: () {
                        _logout();
                      },
                      child:
                          Text("Logout", style: TextStyle(color: Colors.blue)),
                    ),
                  ],
                ),
              ],
            )));
  }

  _logout() async {
    sharePrefs = await SharedPreferences.getInstance();
    await sharePrefs!.remove('token');
    await sharePrefs!.remove('profile');

    Navigator.of(context, rootNavigator: true)
        .pushNamedAndRemoveUntil('/login', (route) => false);
  }

  _openEditPage() {
    //open EditProfilePage with ScreenArguments
    Navigator.pushNamed(context, '/editprofile',
        arguments: ScreenArguments(
          profile['name'],
          profile['surname'],
        ));
  }
}

EditProfilePage.dart

import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'ScreenArguments.dart';

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

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

class _EditProfilePageState extends State<EditProfilePage> {
  final _formKey = GlobalKey<FormBuilderState>();

  @override
  Widget build(BuildContext context) {
    final screenAgr =
        ModalRoute.of(context)!.settings.arguments as ScreenArguments;
    return Scaffold(
        appBar: AppBar(title: Text('${screenAgr.name} ${screenAgr.surname}')),
        body: Container(
          child: SingleChildScrollView(
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.all(10),
                  child: FormBuilder(
                    key: _formKey,
                    initialValue: {
                      'name': screenAgr.name,
                      'surname': screenAgr.surname,
                    },
                    child: Column(
                      children: [
                        SizedBox(height: 15),
                        FormBuilderTextField(
                          name: 'name',
                          decoration: InputDecoration(
                            labelText: 'name',
                            filled: true,
                          ),
                          validator: FormBuilderValidators.compose([
                            FormBuilderValidators.required(context,
                                errorText: 'please insert name'),
                          ]),
                        ),
                        SizedBox(height: 15),
                        FormBuilderTextField(
                          name: 'surname',
                          decoration: InputDecoration(
                            labelText: 'surname',
                            filled: true,
                          ),
                          validator: FormBuilderValidators.compose([
                            FormBuilderValidators.required(context,
                                errorText: 'please insert surname'),
                          ]),
                        ),
                        SizedBox(height: 15),
                        Row(
                          children: [
                            Expanded(
                                child: MaterialButton(
                              onPressed: () {
                                if (_formKey.currentState!.validate()) {
                                  print('updateprofile');
                                  _formKey.currentState!.save();
                                  //update profile
                                  // _updateprofile(_formKey.currentState!.value);
                                } else {
                                  print("validation failed");
                                }
                              },
                              child: Text('Save',
                                  style: TextStyle(color: Colors.blue)),
                            ))
                          ],
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
        ));
  }
}
(Visited 23 times, 1 visits today)
Spread the love