By Brian De Sousa
Translation: Crazy geek
Original text: blog.logrocket.com/flutter-web…
Reproduced without permission
A number of cross-platform application development frameworks allow you to write code once and run it on multiple platforms like Android, iOS, and even desktop. You’ve probably heard of some popular frameworks, such as Ionic, Xamarin, and React Native. Another relatively new framework is the Flutter.
In this article, you will learn about Flutter, especially its Web support, which was recently made available as a technical preview in V1.9. You will be able to add Web support to your existing Flutter application and run it with a simple API on a Node.js server.
Flutter briefly
Flutter is one of Google’s cross-platform development solutions. Although it hasn’t been around for a long time, its feature set makes it a formidable competitor in the field.
It compiles your program into native code that runs on iOS or Android for incredible performance and frame rates. It supports stateful hot restarts during development, which means you can make changes to code and watch them applied on emulators or physical devices at any time without restarting the program or losing the state of the program.
Flutter focuses on iOS and Android. Web support has been added as a technical preview in version 1.9. It is still in its infancy and may not be ready yet, but it is certainly exciting and promising. As you will soon see, existing Flutter applications can be used and compiled into HTML, CSS and JS packages with just a few modifications.
Why run the Flutter Web application on Node.js?
The Flutter Web application can run on any Web server. So why host the Flutter Web application on your Node.js server? Well, let’s be honest, node.js was chosen for the same reason other Web applications and apis are: it’s very good at serving a large number of simple requests, and you can write front-end and back-end code in JavaScript, etc.
You may already have a Node.js API that provides data to Flutter iOS or Android applications. Compiling the Flutter program as a Web application and hosting it on an existing Node.js server could be a logical extension of the current solution without additional hosting costs.
demonstration
Now it’s time to dig into the code and see Flutter Web in action. You will need the following tools:
- Android Studio (Android SDK Manager and Simulator)
- Visual Studio Code + Flutter Extension (Android Studio)
- Node.js 12
Flutter has an excellent developer documentation. If this is your first time developing a Flutter application, follow the “Getting Started” guide to setup the Flutter.
The examples and instructions in this article are based on Visual Studio Code, but you can continue if you choose to use Android Studio.
Node.js 12 is required to run the Web version of the Flutter Weather application and the back-end Weather API.
Step 1: Explore the sample code
To demonstrate how to add Web support to an existing Flutter application, we will start with a simple weather application that has been tested on Android 10 (API Level 29).
The Weather app allows users to view the current weather for predefined cities. Weather data is retrieved from a back-end server running on Node.js.
Copy the weather App and server source from GitHub:
- briandesousa/weather_app_flutter
- briandesousa/weather-app-nodejs-server
Tip: The weather-app-nodejs-server project library has a Flutter-web-support branch, which contains the full version of Flutter that can run on the server with Flutter Web support enabled.
It is best to clone the repositories for both projects into the same parent folder. The contents of the weather_app_FLUTTER repository will be created and copied to a folder within the weather-app-nodejs-server repository.
Explore the Flutter weather app
Open weather_app_FLUTTER in the editor. Let’s take a closer look at the main.dart file. It contains the scaffolding and widgets that make up the program’s user interface. The Home widget class has the fetchWeatherData function, which calls the back-end weather API to retrieve data and update the widget’s state:
fetchWeatherData({String location}) async {
var url = WEATHER_API_URL + location;
final response = await http.get(url);
if (response.statusCode == 200) {
var jsonResponse = convert.jsonDecode(response.body);
setState(() {
this._weatherData = WeatherData(
jsonResponse\['weather'\] ['location'],
jsonResponse\['weather'\] ['temperature'],
jsonResponse\['weather'\] ['weatherDescription']);this._apiError = null;
});
} else {
setState(() {
this._apiError =
'Unable to retrieve weather data from API (HTTP ${response.statusCode})'; }); }}Copy the code
The fetchWeatherData function uses Dart’s HTTP package to connect to the server over HTTP. There are other Dart packages you can use, but this is the official recommended package if you plan to add Web support to the Flutter application.
Also note down the WEATHER_API_URL constant. Before running the program, update the value of this constant so that it can connect to the API running on the local Node.js server. The url must contain the host name of your computer. The Android emulator or physical device cannot access the localhost URL.
Explore the Node.js server and weather API
Open the weather-app-nodejs-server project code in the editor.
Among them are some important files and directories:
public/api-test.html
Files can be used to quickly test whether or not the server after start work as expected (for example, ` ` ` http://localhost:3000/api-test.htmlroutes/weather.js
The file contains a simple GET API that takes the PATH parameter and returns weather data (for example,http://localhost:3000/api/weather/londonon
)- You can be in
public-flutter
Copy the compiled Web version of the weather program in the folder. Set up the Node.js server to serve files from this directory to the root context (for example,http://localhost:3000
)
Step 2: Add Web support to the Flutter application
Since web support is still in technical preview, the latest version of Flutter development, also known as the Master Channel, is required. In the root folder of the weather_app_FLUTTER repository, run the following command:
flutter channel master
flutter upgrade
Copy the code
Tip: When you run the Flutter command in Visual Studio Code’s bash shell on Windows, You may encounter the error “Unknown Operating System. Cannot install Dart SDK.” Try running commands in a normal Windows Command shell.
The upgrade process may take several minutes. Next you will need to enable Web support in the Flutter installation:
flutter config --enable-web
flutter devices
Copy the code
With Web support enabled, you’ll see a new Chrome device in the device list. If you do not see Chrome, restart Visual Studio Code after running the following command to refresh the Device list menu.
To add networking support to the Weather app, you need to run the following command in the top level folder of your weather_Flutter_app project:
flutter create .
Copy the code
The create command will make some changes to the program, as you can see in this commit. The most notable change is the addition of a subfolder web containing index.html:
Start the Node.js server by running the following command in the root directory of weather-app-nodejs-server:
npm start
Copy the code
Select Chrome from the List of devices in Visual Studio Code and start debugging. Alternatively, you can run the following flutter command:
flutter run -d chrome
Copy the code
Since Flutter requires instant downloads of other dependencies, it may take some time for you to launch the app in Chrome for the first time. Eventually you’ll see the weather app running in your browser. There may be some styles that are slightly different from what you might see on an emulator or physical device.
You’ll notice that the app doesn’t display any data from the weather API. If you open Chrome DevTools, you will see a cross-domain resource sharing error.
Browsers do not allow the Flutter Web server to make requests to the Node.js server because they run on different ports. You can solve this problem by enabling cross-domain resource sharing on your server or by installing the Chrome plugin to disable CORS.
We will ignore this error for now because in the next step we will run the pre-compiled Flutter Web code directly on the Node.js server to completely eliminate cross-domain requests.
Try modifying some code in the main.dart file and then have Flutter recompile your program. You will notice that your changes do not immediately show up in the browser. This is because Flutter Web does not yet support hot restarts. Hopefully this support will be available soon.
Tip: Detailed instructions for each Flutter command in this section can be found on Flutter. Dev.
Step 3: Run the Flutter Web application on Node.js
Now you can use Flutter to run the Weather App in a browser. The next step is to build and copy it to the Node.js server to run with the API.
To build the Flutter Web application bundle, run the following command:
flutter build web
Copy the code
The build command generates the build/ Web folder that contains all the static files that make up the weather application.
Copy the contents of weather_app_flutter/build/web to weather-app-nodejs-server/public-flutter. If your Node.js server is still running, please restart it.
See the program running on Node.js by visiting http://localhost:3000 in your browser. This time your application will display weather data retrieved from the weather API without cross-domain resource sharing errors.
Final thoughts
It is incredibly easy to take an existing Flutter application and compile it into a Web application that can be deployed to a Web server. The user interface rendered in the browser looks almost identical to the interface in Android.
But Flutter should not be considered a cross-platform application framework just because of its Web support. The Flutter team was well aware that Web support lacked functionality, had known performance issues and was not yet fully supported in production environments.
One thing is certain: the future of Flutter for Web looks promising. You can learn more about Flutter Web support and the Hummingbird project here.