0

I wanted to program a initial start up for new users, simply for them to input their initial Username, Email, possibly a password, and maybe a login through Patreon if this other StackOverview question works out. However, I have been having issues figuring out how to make it work. The code I have currently have is a pretty basic home screen and the main.dart file that launches it. I don't know in which file or how to code a screen that would only launch if the user has visited for the first time or hasn't submitted the proper information yet.

I will happily program and decorate another startup/new user screen, but I just need to know where to implement the code when launching it? Would I add it to the main.dart that launches the home screen or on the home.dart file?

Thanks for your help!

main.dart

import 'package:bit/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:bit/saved_data.dart';
import 'package:bit/themes.dart';
import 'package:bit/pages/home.dart';

void main() {
  runApp(MaterialApp(
    title: 'App',
    themeMode: ThemeMode.system,
    theme: MyThemes.lightTheme,
    darkTheme: MyThemes.darkTheme,
    home: MyApp(),
  ));
}

home.dart

import 'package:bit/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:bit/saved_data.dart';
import 'package:bit/themes.dart';

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    /* final theme = MediaQuery.of(context).platformBrightness == Brightness.dark
        ? 'Dark Theme'
        : 'Light Theme'; */

    var scaffold = Scaffold(
      appBar: AppBar(
        title: const Text('Bible Info & Tech'),
      ),
// Body Home Page Beginning
      body: SingleChildScrollView(
          child: Padding(
              padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
              child: Center(
                  child: Column(
                children: [
                  Visibility( //visible: ,
                  child: Padding(padding: const EdgeInsets.fromLTRB(0, 6, 0, 6),
                    child: Container(
                    width: double.infinity,
                    decoration: const BoxDecoration(
                        color: Color.fromRGBO(155, 205, 255, 0.8),
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    child: Column(
                      children: [
                        Text('Welcome!!!',
                            style: TextStyle(
                              fontSize: 17.0,
                              fontWeight: FontWeight.bold,
                            )),
                      ],
                    ),
                  ),)),
                  Visibility( //visible: ,
                  child: Padding(padding: EdgeInsets.fromLTRB(0, 6, 0, 6),
                    child: Container(
                    width: double.infinity,
                    decoration: const BoxDecoration(
                        color: Color.fromRGBO(155, 205, 255, 0.8),
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    child: Column(
                      children: [
                        Text('My Classroom',
                            style: TextStyle(
                              fontSize: 17.0,
                              fontWeight: FontWeight.bold,
                            )),
                      ],
                    ),
                  ),)),
                  Visibility( //visible: ,
                  child: Padding(padding: EdgeInsets.fromLTRB(0, 6, 0, 6),
                    child: Container(
                    width: double.infinity,
                    decoration: const BoxDecoration(
                        color: Color.fromRGBO(155, 205, 255, 0.8),
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    child: Column(
                      children: [
                        Text('Current Lesson',
                            style: TextStyle(
                              fontSize: 17.0,
                              fontWeight: FontWeight.bold,
                            )),
                            Padding(padding: EdgeInsets.fromLTRB(6, 0, 6, 0),
                        child: LinearProgressIndicator(
                          //value: _lessonprogress,
                        ),),

                        Text('Current Personal Lesson',
                            style: TextStyle(
                              fontSize: 17.0,
                              fontWeight: FontWeight.bold,
                            )),
                      ],
                    ),
                  ),)),
                  Visibility( //visible: ,
                  child: Padding(padding: EdgeInsets.fromLTRB(0, 6, 0, 6),
                    child: Container(
                    width: double.infinity,
                    decoration: const BoxDecoration(
                        color: Color.fromRGBO(155, 205, 255, 0.8),
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    child: Column(
                      children: [
                        Text('Awards',
                            style: TextStyle(
                              fontSize: 17.0,
                              fontWeight: FontWeight.bold,
                            )),
                      ],
                    ),
                  ),)),
                ],
              )))),
// Body Home Page End
      drawer: Drawer(
        // Drawer Beginning
        child: ListView(
          children: [
// Drawer Header
            DrawerHeader(
              decoration: const BoxDecoration(
                color: Color.fromRGBO(6, 145, 248, 1),
              ),
              child: Stack(
                children: [
                  const Align(
                      alignment: Alignment.centerLeft,
                      child: CircleAvatar(
                        foregroundImage:
                            AssetImage('assets/images/Untitled_Artwork.png'),
                        radius: 55.0,
                      )),
                  Align(
                      alignment: Alignment.centerRight,
                      child: FutureBuilder<SettingsModal>(
                        future: PreferencesService.getSettings(),
                        builder: (context, snapshot) {
                          if (snapshot.hasData && snapshot.connectionState == ConnectionState.done) {
                            return Text(
                              snapshot.data!.username,
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 20.0,
                              ),
                            );
                          }
                          return const CircularProgressIndicator();
                        },
                      )),
                  const Align(
                      alignment: Alignment(1, 0.3),
                      child: Text(
                        'Student',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 15.0,
                        ),
                      ))
                ],
              ),
            ),
// Drawer List            
            ListTile(
              title: const Text('Settings'),
              subtitle: const Text('Account Info & Settings'),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => Settings()),
                );
              },
              trailing: const Icon(Icons.arrow_forward_ios_rounded),
            ),
            /* ListTile(
              title: const Text('Test'),
              subtitle: const Text('Testing Page'),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => Test1()),
                );
              },
              trailing: const Icon(Icons.arrow_forward_ios_rounded),
            ),*/
          ],
        ),
      ),
// Drawer End
    );
    return MaterialApp(
      title: 'BIT',
      themeMode: ThemeMode.system,
      theme: MyThemes.lightTheme,
      darkTheme: MyThemes.darkTheme,
      home: scaffold,
    );
  }
}

// Settings Page & Account Information
class Settings extends StatefulWidget {
  Settings({Key? key}) : super(key: key);

  @override
  State<Settings> createState() => _SettingsState();
}

class _SettingsState extends State<Settings> {
  final _preferencesService = PreferencesService();
  final _usernameController = TextEditingController();
  void initState() {
    super.initState();
    _populateFields();
  }

  void _populateFields() async {
    final settings = await PreferencesService.getSettings();
    setState(() {
      _usernameController.text = settings.username;
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = MediaQuery.of(context).platformBrightness == Brightness.dark
        ? 'Dark Theme'
        : 'Light Theme';

    return Scaffold(
        appBar: AppBar(
          title: const Text(
              'Settings'), /* actions: <Widget>[
          IconButton(
              onPressed: () async {
                _saveSettings;
              },
              icon: const Icon(Icons.save),
              tooltip: 'Save Settings')
        ] */
        ),
        body: SingleChildScrollView(
            child: Padding(
          padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
          child: Column(
            children: [
              Column(
                // Account
                children: [
                  const Padding(
                      padding: EdgeInsets.fromLTRB(0, 12, 0, 0),
                      child: Text('Account Information',
                          style: TextStyle(
                            fontSize: 17.0,
                            fontWeight: FontWeight.bold,
                          ))),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(12, 0, 12, 6),
                    child: TextField(
                      controller: _usernameController,
                      inputFormatters: [LengthLimitingTextInputFormatter(15)],
                      decoration: InputDecoration(
                        hintText: 'Username',
                        labelText: 'Username',
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0)),
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(12, 0, 12, 6),
                    child: TextField(
                      // controller: _usernameController,
                      // inputFormatters: [LengthLimitingTextInputFormatter(15)],
                      decoration: InputDecoration(
                        hintText: 'email@outlook.com',
                        labelText: 'Email',
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0)),
                      ),
                    ),
                  ),
                ],
              ),
              Container(
                child: Column(
                  // App Settings
                  children: [
                    // SwitchListTile(value: DarkMode, onChanged: Light => Dark => Light)
                    // ChangeThemeButtonWidget(),
                    TextButton(
                      onPressed: _saveSettings,
                      child: const Text('Save Settings'),
                    ),
                  ],
                ),
              ),
            ],
          ),
        )));
  }

  void _saveSettings() {
    final newSettings = SettingsModal(
      username: _usernameController.text,
    );

    print(newSettings);
    print(_usernameController.text);
    _preferencesService.saveSettings(newSettings);
  }
}
Jared
  • 189
  • 12

3 Answers3

4

I think you need a Wrapper class and a Welcome Screen. When the user first started using the app. Welcome Screenwill pop up with two buttons. One of them will navigate to the Login and the other one will navigate to SingUp. Also, you need to create a boolean that will test the user if he/she is already signed in such that isSignedIn. Initially, it will be false. When the user signed up or signed in then it will be set to true and save this variable in the shared preferences. Every time, when the user starts the application you need to check this condition. If isSignedIn is true then navigate to the Home Screen. If it is false then navigate to the Welcome Screen.Consider the following diagram.

enter image description here

If you are planning to use Firebase for authentication. There is another method you can do to check whether the user is logged in or not in your MaterialApp without using the Wrapper class. FirebaseAuth returns the current user with the following method. To do that, you need to also consider state management in your project.

initialRoute:FirebaseAuth.instance.currentUser != null ? '/home' : '/welcome',
Demir
  • 799
  • 3
  • 16
3

I couldn't quite get your issue but as I understand, I advice that below code,so you can controll check new user by this approach firstly, set a bool by the sharedPreferences package

TextButton get isNewUserButton=> TextButton(onPressed: ()async{
  final prefs = await SharedPreferences.getInstance();
  prefs.setBool('isNewUser',true);
}, child: const Text("Get Started"));

then,

void main()async {
final prefs = await SharedPreferences.getInstance();
final showHomePage = prefs.getBool('isNewUser') ?? false;
  runApp(MaterialApp(
    title: 'App',
    themeMode: ThemeMode.system,
    theme: MyThemes.lightTheme,
    darkTheme: MyThemes.darkTheme,
    home: showHomePage ? MyApp() : NewUserSignPage ,
  ));
}

if user sign out you can use this code

TextButton get signOutButton=> TextButton(onPressed: ()async{
  final prefs = await SharedPreferences.getInstance();
  prefs.setBool('isNewUser',false);
}, child: const Text("Sign Out"));
Zekai Demir
  • 143
  • 1
  • 10
2

You can use named routing. In your MaterialApp, you can set a boolean whether if the user is logged in or not.Such that;

 initialRoute: isUserLoggedIn == null ? '/login-screen' : '/home-screen';