user_manager
a tutorial for creating an ubuntu linux flutter app, using the yaru theme.
introduction
what you’ll learn
- setting up a flutter development environment in ubuntu
- building a flutter app for the linux desktop, using the yaru theme
- using json-server as a local backend to store data
what you’ll build
set up your flutter environment
install flutter on ubuntu and enable flutter linux desktop support
sudo snap install flutter
flutter channel beta
flutter upgrade
flutter config --enable-linux-desktop
install and setup visual studio code
to install vs code in ubuntu fire up a terminal and run the following command:
sudo snap install code --classic
launch vs code quick open (ctrl+p), paste the following command …
ext install dart-code.flutter
… and press enter to install the official flutter vs code extension.
get started
open a terminal or the vs code integrated terminal and run the following command to create a new flutter project for the fictional organization org.flutterfans
flutter create --org org.flutterfans user_manager
open the project directory user_manager
you’ve just created with vs code.
you should now see the following directories (1) and the “linux (linux-x64)” (2) device in use, which is the default on linux after you’ve enabled the linux desktop support:
let’s make a small test if the application launches, by opening the lib
directory (1) and clicking on the small run
label above void main()
(2)
using the yaru theme
open pubspec.yaml
– the file for managing of the lifecycle of your app – and add yaru: ^0.0.6
under the dependencies section, so you end up with the following dependencies (check that yaru
is on the same column as flutter
):
dependencies:
flutter:
sdk: flutter
yaru: ^0.0.6
you can now import the yaru theme by adding
import 'package:yaru/yaru.dart' as yaru;
at the top of main.dart
. use the yaru theme in your app by setting the theme
property of materialapp
to yaru.lighttheme
and the darktheme
property to yaru.darktheme
so you end up with the following class definition – your app now follows your system’s theme.
class myapp extends statelesswidget {
@override
widget build(buildcontext context) {
return materialapp(
title: 'flutter demo',
theme: yaru.lighttheme,
darktheme: yaru.darktheme,
home: myhomepage(title: 'flutter demo home page'),
);
}
}
building the app
organize your project structure
you might want to organize your project’s directory structure a little bit. start by creating a view
directory under lib
by right-clicking the lib
directory and click the new folder
menu entry and type in view
into the textfield that pops out.
repeat this step with a model
and a service
directory to end up with the following directory tree above main.dart
:
a simple user model
to easily send user data across your app and to the server you want to have a user class, containing only the data properties of your user.
right-click on the model
directory and click on new file
and name it user.dart
:
insert the following code
class user {
int? id;
string name;
user({required this.id, required this.name});
user.empty() : this(id: null, name: "");
factory user.fromjson(map<string, dynamic> json) =>
user(id: json['id'], name: json['name']);
map<string, dynamic> tojson() => {"id": id, "name": name};
}
the user service
to let your app communicate via http with your server, add http: ^0.13.1
in your pubspec.yaml
under the dependencies
section, create user_service.dart
in the service
directory and paste the following code into:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:user_manager/model/user.dart';
class userservice {
userservice({required this.uri});
final string uri;
future<list<user>> getusers() async {
final response = await http.get(uri.http(uri, 'users'));
if (response.statuscode == 200) {
var usersjson = jsondecode(response.body.tostring()) as list;
return usersjson.map((json) => user.fromjson(json)).tolist();
} else {
throw exception(response.statuscode.tostring() + ': ' + response.body);
}
}
future saveuser(user user) async {
for (var auser in await getusers()) {
if (auser.id == user.id) {
await updateuser(user);
return;
}
}
await adduser(user);
}
future<http.response> adduser(user user) async {
return await http.post(uri.http(uri, 'users'),
headers: <string, string>{
'content-type': 'application/json; charset=utf-8',
},
body: jsonencode(user.tojson()));
}
future updateuser(user user) async {
return await http.put(uri.http(uri, 'users/${user.id}'),
headers: <string, string>{
'content-type': 'application/json; charset=utf-8',
},
body: jsonencode(user.tojson()));
}
future removeuser(user user) async {
await http.delete((uri.http(uri, 'users/${user.id}')));
}
}
the ui
one card for each user
each user that will be managed is represented by a card inside the ui.
create user_card.dart
in the view
directory and paste in the following code
import 'package:flutter/material.dart';
import 'package:user_manager/model/user.dart';
class usercard extends statefulwidget {
final user user;
final voidcallback ondelete;
final voidcallback onedit;
usercard({required this.user, required this.ondelete, required this.onedit});
@override
_usercardstate createstate() => _usercardstate();
}
class _usercardstate extends state<usercard> {
@override
widget build(buildcontext context) {
return card(
child: column(
mainaxissize: mainaxissize.min,
children: <widget>[
listtile(
leading: icon(icons.person),
title: text(widget.user.name),
),
row(
mainaxisalignment: mainaxisalignment.end,
children: <widget>[
textbutton(
child: const text('edit'),
onpressed: () => widget.onedit(),
),
const sizedbox(width: 8),
textbutton(
child: const text('remove'),
onpressed: () => widget.ondelete(),
),
const sizedbox(width: 8),
],
),
],
),
);
}
}
a dialog to edit users in
a user will be edited inside a dialog, spawned from clicking on the either the big green floating action button or the edit button of your user card.
create the file user_edit_dialog.dart
inside the view
directory and copy/paste the following code into:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class usereditdialog extends statefulwidget {
final texteditingcontroller namecontroller;
final asynccallback edituser;
usereditdialog({required this.namecontroller, required this.edituser});
@override
_usereditdialogstate createstate() => _usereditdialogstate();
}
class _usereditdialogstate extends state<usereditdialog> {
@override
widget build(buildcontext context) {
return dialog(
child: container(
height: 150,
width: 200,
child: padding(
padding: const edgeinsets.all(10.0),
child: column(
mainaxisalignment: mainaxisalignment.start,
crossaxisalignment: crossaxisalignment.start,
children: [
padding(
padding: const edgeinsets.all(8.0),
child: textfield(
autofocus: true,
controller: widget.namecontroller,
decoration: inputdecoration(hinttext: 'user name'),
),
),
row(
children: [
padding(
padding: const edgeinsets.all(8.0),
child: elevatedbutton(
onpressed: () async =>
navigator.of(context).pop(widget.edituser()),
child: text(
"save",
style: textstyle(color: colors.white),
),
),
),
padding(
padding: const edgeinsets.all(8.0),
child: textbutton(
onpressed: () => navigator.of(context).pop(),
child: text("cancel"),
),
)
],
),
],
),
),
),
);
}
}
the new home page
the old home page won’t be enough anymore so you need a new one to load the user cards into. the home page uses the user service to manage the user data.
open your pubspec.yaml
file again and add injector: ^2.0.0
in the dependencies
section. create the file home_page.dart
in the view
directory and paste the following code:
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:injector/injector.dart';
import 'package:user_manager/model/user.dart';
import 'package:user_manager/service/user_service.dart';
import 'package:user_manager/view/user_card.dart';
import 'package:user_manager/view/user_edit_dialog.dart';
class homepage extends statefulwidget {
@override
_homepagestate createstate() => _homepagestate();
}
class _homepagestate extends state<homepage> {
late texteditingcontroller _namecontroller;
final _userservice = injector.appinstance.get<userservice>();
@override
void initstate() {
_namecontroller = texteditingcontroller();
super.initstate();
}
@override
widget build(buildcontext context) {
return scaffold(
appbar: appbar(
title: const text('home'),
),
body: center(
child: padding(
padding: const edgeinsets.all(8.0),
child: scrollbar(
child: futurebuilder(
future: _userservice.getusers(),
builder: (context, asyncsnapshot<list<user>> snapshot) {
if (snapshot.hasdata) {
return listview(
children: snapshot.data!
.map((user) => usercard(
user: user,
ondelete: () {
_userservice
.removeuser(user)
.then((value) => setstate(() {
_showsnackbar(
'deleted user: ' + user.name);
}))
.onerror((error, stacktrace) =>
_showsnackbar(error.tostring()));
},
onedit: () => edituser(user, context)))
.tolist(),
);
}
return circularprogressindicator();
}),
),
),
),
floatingactionbutton: floatingactionbutton(
child: icon(icons.add),
onpressed: () {
_namecontroller.text = "";
edituser(new user.empty(), context);
},
),
);
}
void edituser(user user, buildcontext context) {
_namecontroller.text = user.name;
showdialog(
context: context,
barrierdismissible: false,
builder: (buildcontext context) {
return usereditdialog(
namecontroller: _namecontroller,
edituser: () async {
user.name = _namecontroller.text;
_userservice
.saveuser(user)
.then((value) => setstate(() {
_showsnackbar('saved user: ' + user.name);
}))
.onerror(
(error, stacktrace) => _showsnackbar(error.tostring()));
});
});
}
void _showsnackbar(string message) {
scaffoldmessenger.of(context).showsnackbar(
snackbar(duration: const duration(seconds: 1), content: text(message)));
}
}
finish up your main.dart
the ui of the test app is no longer needed. remove all widgets except myapp
, change the home
property to homepage()
, change your main()
function to by asynchronous, returning a future<void>
and register your userservice
with the injector
class before you run your app. to be sure you’ve imported everything correctly, replace all code inside main.dart
with the following new version:
import 'package:flutter/material.dart';
import 'package:injector/injector.dart';
import 'package:user_manager/service/user_service.dart';
import 'package:user_manager/view/home_page.dart';
import 'package:yaru/yaru.dart' as yaru;
future<void> main() async {
final userservice = userservice(uri: 'localhost:3000');
injector.appinstance.registerdependency<userservice>(() => userservice);
runapp(myapp());
}
class myapp extends statelesswidget {
@override
widget build(buildcontext context) {
return materialapp(
title: 'flutter demo',
theme: yaru.lighttheme,
darktheme: yaru.darktheme,
home: homepage(),
);
}
}
create a local server to process client requests
create mock data
create db.json
inside the root folder of your application and insert some fictional users in the json format:
{
"users": [
{
"id": 1,
"name": "carlo"
},
{
"id": 2,
"name": "mads"
},
{
"id": 3,
"name": "frederik"
},
{
"id": 4,
"name": "stuart"
},
{
"id": 5,
"name": "paul"
},
{
"id": 6,
"name": "muq"
}
]
}
install node-js and json-server
we will use a fantastic local mock server to let our client talk to. to do so we need the node snap. enter the following commands to install node and json-server.
sudo snap install node --classic
sudo npm install -g json-server
entering the user management 🙂
start your json-server by running the following command
json-server --watch db.json
start your app again! done 🙂 you can now manage users inside a ubuntu linux app, using the yaru theme:
Comments are closed.