NX Workspaces enable you to construct Flutter applications utilizing a mono-repo approach. This allows you to design self-contained applications and libraries that can be used in numerous projects.
You may have a whole Flutter app that you’d want to reuse in other projects, but it’s more probable that you’d prefer to reuse a Flutter package.
In this tutorial, we will construct a Flutter app utilizing Nx.
Prerequisites
To proceed, please download and install the necessary software.
- Flutter
- js
- Visual Studio Code or a similar editor.
In addition, you need to equip your editor with the necessary Flutter add-on. How to implement this in Visual Studio Code and Android Studio is as follows:
- Visual Studio Code
- Android Studio & IntelliJ
Creating a new Nx Workspace
Simply typing this command into your terminal to hire flutter developers, you may start a brand new Nx Workspace:
$ npx create-nx-workspace
You’ll need to identify your company by name:
✔ Workspace name (e.g., org name) · developer-school
The next screen will prompt you to choose a template for your new venture:
? What to create in the new workspace …
❯ empty [an empty workspace with a layout that works best for building apps]
npm [an empty workspace set up to publish npm packages (similar to and compatible with yarn workspaces)]
react [a workspace with a single React application]
angular [a workspace with a single Angular application]
next.js [a workspace with a single Next.js application]
gatsby [a workspace with a single Gatsby application]
nest [a workspace with a single Nest application]
express [a workspace with a single Express application]
web components [a workspace with a single app built using web components]
react-native [a workspace with a single React Native application]
react-express [a workspace with a full stack application (React + Express)]
angular-nest [a workspace with a full stack application (Angular + Nest)]
The efforts are given in a variety of examples for your consideration.
Click the “Select None” button here. This will start a blank document for us to fill with our data.
Then, you’ll be prompted to decide whether you wish to include Nx Cloud:
? Use Nx Cloud? (It’s free and doesn’t require registration.) …
Yes Faster builds, run details, Github integration. Learn more at https://nx.app
❯ No
For the sake of this guide, I’ve opted for No; but if you’d want to take advantage of Nx Cloud, you may do so by selecting Yes.
Finally, you should see something that looks like the following:
> NX Nx is creating your workspace.
To make sure the command works reliably in all environments, and that the preset is applied correctly,
Nx will run “npm install” several times. Please wait.
✔ Installing dependencies with npm
✔ Nx has successfully created the workspace.
The above result shows that the workspace was successfully established by Nx. every folder on your workspace will have the same name as your company.
Creating a Flutter app within Nx
To develop a Flutter app using Nx, you must install the nx-flutter package.
Switch to your new working directory, and then type:
$ cd <your-workspace-name>
$ npm install @nxrocks/nx-flutter –save-dev
Build a new Flutter app with the help of the project generator.
To create a new Flutter app, fire up the builder.
$ nx g @nxrocks/nx-flutter:create
You’ll be asked many questions when making a new Flutter app, module, package, or plugin.
✔ What name would you like to use? · hello_flutter
✔ What package name would you like to use? · school.developer.hello
✔ What is the project about? · Hello World project using Flutter
✔ Which type of Flutter project would you like to create? · Flutter application (app)
? Which platforms would you like to use? Android platform, iOS platform, Linux platform, Windows platform, MacOS platform, Web platform
? Which Android language would you like to use? Kotlin
? Which iOS language would you like to use? Swift
Follow the on-screen prompts for answers. Choose “app” as the Flutter project you want to create.
You should see an output like to:
Running “flutter pub get” in hello-flutter… 1,740ms
Wrote 107 files.
All done!
In order to run your application, type:
$ cd apps/hello-flutter
$ flutter run
Your application code is in apps/hello-flutter/lib/main.dart.
At this point, a new Flutter project should be available to you.
Running the Flutter app
The Flutter project has several possible implementations. The following is an example command that may be used to launch the application:
$ cd apps/hello-flutter
$ flutter run
Doing this in an integrated development environment (IDE) or editor is easier. While I prefer Visual Studio Code, other integrated development environments (IDEs) provide equivalent features.
Launch your IDE and load the project:
$ code .
There is a high likelihood of having numerous apps and libraries in a single mono-repo. The the.vscode/launch.json file in Visual Studio Code may be used to start many apps at once.
Your Flutter applications and libraries will be readily available in the IDE.
To do this, first, make the following entries in a file and save it to.vscode/launch.json:
{
“version”: “0.2.0”,
“configurations”: [
{
“name”: “Hello, Flutter – Chrome”,
“request”: “launch”,
“type”: “dart”,
“deviceId”: “chrome”,
“flutterMode”: “debug”,
“program”: “apps/hello-flutter/lib/main.dart”
}
]
}
Please select the program from the Debug tab and run it in Visual Studio Code.
If you created the project using the Web option, it should now load in Chrome.
Check out the Multi-Device Debugging with VS Code in Flutter article to learn more about porting your Flutter app to different platforms.
Creating a new Flutter package within Nx
Nx also allows you to create a whole new Flutter bundle. This is a helpful technique for developing a package for numerous projects.
Building a Shareable Flutter project using modular Dart code is similar to creating a Flutter app, except you will need to pick it instead of the Flutter application.
To create a new Flutter package, run the generator.
$ nx g @nxrocks/nx-flutter:create
Here, you’ll want to create a Flutter project of the Shareable kind, including modular Dart code.
✔ What name would you like to use? · say-hello
✔ What package name would you like to use? · school.developer.say
✔ What is the project about? · Greet the user with a variety of welcoming messages.
✔ Which type of Flutter project would you like to create? · Shareable Flutter project containing modular Dart code (package)
? Which Android language would you like to use? Kotlin
? Which iOS language would you like to use? Swift
A new package named libs/say-hello should have been added to your workspace.
This is not currently available to your apps/hello-flutter project.
Make sure to include it in the apps/hello-flutter/pubspec.YAML file’s requirements section:
dependencies:
flutter:
sdk: flutter
say_hello:
path: ‘../../libs/say-hello’
Verify that you have executed flutter pub get in your apps/hello-flutter project. The Flutter add-on for IDEs like Visual Studio Code should handle this mechanically.
You may now utilize this freshly built Flutter bundle across numerous Nx projects.
Adding package functionality
Make a new file called greet person. Dart within libs/say-hello:
import ‘package:flutter/material.dart’;
class GreetingDialog extends StatelessWidget {
final String name;
const GreetingDialog({
Key? key,
required this.name,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(‘Hello $name!’),
content: const Text(‘Welcome to this Flutter app created with Nx.’),
actions: <Widget>[
TextButton(
child: const Text(‘Hey!’),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
}
}
greetPerson(BuildContext context, String name) {
showDialog(context: context, builder: (context) => GreetingDialog(name: name));
}
The excellent person method and GreetingDialog widget are exported from this example program.
Your other applications can wait to use this. Add it to the say hello—dart in the libs folder of your say-hello project.
This is how things stand right now:
library say_hello;
/// A Calculator.
class Calculator {
/// Returns [value] plus 1.
int addOne(int value) => value + 1;
}
Substitute the exported file we just made for the fictitious Calculator:
library say_hello;
export ‘./greet_person.dart’;
Depending on your setup, you may need to delete the Calculator from the say hello test—Dart file located in the libs/say-hello/test directory to fix a syntax problem
import ‘package:flutter_test/flutter_test.dart’;
void main() {
test(‘TODO’, () {});
}
Now, other packages and applications may use the features you’ve made available.
Using the package in your app
Making a new page at lib/greeting/pages/greeting page within your apps/hello-flutter project is the first step in introducing a greeting to your users. Toss the following information in a dart:
import ‘package:flutter/material.dart’;
import ‘package:say_hello/say_hello.dart’;
class GreetingPage extends StatefulWidget {
const GreetingPage({Key? key}) : super(key: key);
@override
State<GreetingPage> createState() => _GreetingPageState();
}
class _GreetingPageState extends State<GreetingPage> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String name = ”;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(‘Say Hello’),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
TextFormField(
decoration: const InputDecoration(
labelText: ‘Name’,
),
validator: (String? n) => n != null && n.isNotEmpty ? null : ‘Name is required’,
onChanged: (n) => setState(() => name = n),
),
const SizedBox(height: 16),
TextButton(
child: const Text(
‘👋’,
style: TextStyle(fontSize: 40),
),
onPressed: () {
final isValid = _formKey.currentState!.validate();
if (!isValid) {
return;
}
greetPerson(context, name);
},
),
],
),
),
),
);
}
}
The file import ‘package exports the great person method used in the compressed callback: say hello/say hello. Dart’;.
Make that the pubspec. The YAML file in your apps/hello-flutter project has been updated to include the greetPerson or say hello. Dart the package, and then run flutter pub get again.
Just edit apps/hello-flutter/main.dart to read:
import ‘package:flutter/material.dart’;
import ‘package:hello_flutter/greeting/pages/greeting_page.dart’;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: ‘Nx Demo’,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const GreetingPage(),
);
}
}
The Greeting Page should load up on your screen right about now. Fill the TextFormField with a name, then hit the button to bring up the GreetingDialog.
Congratulations, you have just finished developing a Flutter application and package that may be used in other projects.
Resources
The Nx Workspace Plugin is compatible with many different editors, allowing you to utilize a graphical user interface (GUI) instead of the command line.
As an illustration, consider this VS Code example:
Downloading it and using it in your Nx projects is something I strongly suggest.
Additionally, a wealth of information on Nx is available on the site’s corresponding website.
Conclusion
By the end of this guide, you should have a working Flutter package that you may include in other initiatives. When you construct your apps in this fashion, you may easily reuse parts of them in different places.