Once your project is setup, replace the boilerplate code in main.dart with the following:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
// 1
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Workshop App',
theme: ThemeData(visualDensity: VisualDensity.adaptivePlatformDensity),
// 2
home: Navigator(
pages: [],
onPopPage: (route, result) => route.didPop(result),
),
);
}
}
Before we can add pages to our Navigator, we need to create the widgets that will represent each of our pages. Let’s start with the login page which we will put in a new file called login_page.dart in the /lib/ directory, this is the same directory as main.dart.
import 'package:flutter/material.dart';
class LoginPage extends StatefulWidget {
@override
State<StatefulWidget> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
// 1
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
// 2
return Scaffold(
// 3
body: SafeArea(
minimum: EdgeInsets.symmetric(horizontal: 40),
// 4
child: Stack(children: [
// Login Form
_loginForm(),
// 6
// Sign Up Button
Container(
alignment: Alignment.bottomCenter,
child: FlatButton(
onPressed: () {},
child: Text('Don\'t have an account? Sign up.')),
)
])),
);
}
// 5
Widget _loginForm() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Username TextField
TextField(
controller: _usernameController,
decoration:
InputDecoration(icon: Icon(Icons.mail), labelText: 'Username'),
),
// Password TextField
TextField(
controller: _passwordController,
decoration: InputDecoration(
icon: Icon(Icons.lock_open), labelText: 'Password'),
obscureText: true,
keyboardType: TextInputType.visiblePassword,
),
// Login Button
FlatButton(
onPressed: _login,
child: Text('Login'),
color: Theme.of(context).accentColor)
],
);
}
// 7
void _login() {
final username = _usernameController.text.trim();
final password = _passwordController.text.trim();
print('username: $username');
print('password: $password');
}
}
The UI of LoginPage is not finished, let’s add it to the Navigator in main.dart.
... // home: Navigator( (line 21)
pages: [MaterialPage(child: LoginPage())],
... // onPopPage: (route, result) => route.didPop(result),
The pages parameter takes a List<Page
Now we need to import login_page.dart so that LoginPage can be accessed from main.dart.
... // import 'package:flutter/material.dart'; (line 1)
import 'login_page.dart';
Now run the app (F5 in Visual Studio Code), this will usually take a few minutes to launch.