Flutter—See Why It’s Worth Testing

3010 VIEWS

· ·

Flutter is an SDK by Google that provides for and facilitates the development of mobile applications, and promises native performance. It also lets you build applications cross-platform and distribute to Android and iOS. In this article, we will prepare an environment to use Flutter and build an application with Flutter that calls an API and shows a list of results. The build and releases will not be shown here.

Installing Flutter

In this article, we will use Mac OS and Visual Studio Code as the development environment. To install Flutter, access the download page and get the installer. Then unzip, export the location inside the $PATH variable, and check if Flutter was installed correctly.

 $ unzip ~/flutter_macos_v0.3.1-beta.zip
$ export PATH=~/flutter/bin:$PATH
$ source ~/.bash_profile
$ flutter --version

Now, run Flutter doctor to verify what else we need to install.

 $ flutter doctor

Because I have a Ruby on Rails environment set up on my computer, I need to run some different commands, and install dependencies with Homebrew: libimobiledevice, ideviceinstaller, and ios-deploy. If you’re following along, remove the current CocoaPods and install with gem. Now, we can set up the pod and run Flutter doctor again to check if everything is okay. In this article, we will only use the iOS Simulator. No configuration of Android will be completed.

 $ sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
$ brew install --HEAD libimobiledevice --overwrite
$ brew install ideviceinstaller
$ brew install ios-deploy
$ sudo gem uninstall cocoapods
$ gem install cocoapods
$ pod setup
$ flutter doctor

All right! We can now test the sample application and check if everything is working. To run the Hello World example, access the sample folder, open the Simulator and run the application.

 $ cd ~/flutter/example/hello_world
$ open -a Simulator.app
$ flutter run

Installing Visual Studio Code

We can use any editor to work with Flutter, but Visual Studio Code is a free editor with support for Dart and Flutter, so we will use it here. Go to the download page, get the installer and install. Now, add the Dart extension. This page contains the information on the extension. Just click Install to add Visual Studio Code.

Creating an application

To create an application, access your selected folder to store the project and run the Flutter command. After creation, access the project folder, open the Simulator, and run the application. We can also run this command inside the Visual Studio Code terminal, except the Flutter run. This command will be replaced by start debugging with the F5 key.

 $ cd ~
$ flutter create player_app
$ cd player_app
$ flutter run

The application code

The main file in the project is called main.dart. It will contain a class called MusicApp as the name of the project and extends from the StatelessWidget class. We also have to include a call of the runApp() method that initializes the object of the MusicApp class.

In this application, we will get a JSON list and show its data inside the application. Therefore, we need to import the async and http package, and import the material to customize the layout. On this page, we can see the options of colors available.

The fetchMusics() method is responsible for calling the API that is running local and returns a list of objects. It uses the async/await that could be used to improve the experience of the app when we add a loader (CircularProgressIndicator). The return of this method calls the getMusics() method that converts the JSON into a CastList that will be used in the visualization of music.

The rest of the code of the MusicApp class is responsible for creating the components of the application including the list of music. The important thing here is where fetchMusics() is called, inside the future property. It will call fetchMusics() when the app is opened. You can see the full main.dart file below.

 import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future fetchMusics() async {
 final response = await http.get('http://127.0.0.1:3000/v1/musics/top_hits');
 final responseJson = json.decode(response.body);

 return getMusics(responseJson['musics']);
}

List getMusics(musicsList) {
 final musics = List.castFrom(musicsList);

 return musics;
}

void main() => runApp(new MusicApp());

class MusicApp extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return new MaterialApp(
     title: 'Top Musics',
     theme: new ThemeData(
       primaryColor: Colors.lightBlue[900],
     ),
     home: new Scaffold(
       appBar: new AppBar(
         title: new Text('Top Musics'),
       ),
       body: new Center(
         child: new FutureBuilder(
           future: fetchMusics(),
           builder: (context, snapshot) {
             if (snapshot.hasError) {
               return new Text("${snapshot.error}");
             } else if (snapshot.hasData) {
               List content = snapshot.data;

               return new ListView.builder(
                 scrollDirection: Axis.vertical,
                 padding: new EdgeInsets.all(6.0),
                 itemCount: content.length,
                 itemBuilder: (BuildContext context, int index) {
                   return new Card(
                     child: new Row(
                       mainAxisSize: MainAxisSize.max,
                       crossAxisAlignment: CrossAxisAlignment.center,
                       children: [
                         new Icon(Icons.play_arrow, size: 28.0, color: Colors.lightBlue[900]),
                         new Text('${content[index]['name']}'.substring(0, 40)),
                       ]
                     ),
                   );
                 }
               );
             }
             return new CircularProgressIndicator();
           },
         ),
       ),
     ),
   );
 }
}

The JSON returned by API has this format:

{"musics":
  [
    {"id":1,
     "name":"Music Name"}
  ]
}

And here, we can see the result in the Simulator:

Conclusion

Flutter is a way to quickly start development of mobile applications, mainly when the developer has JavaScript as the first language. Its mode involving all features inside, including material, and the facility of building offer a huge advantage over React Native.


Brena Monteiro is a Tech Lead passionate about mentoring new developers. A professional who has experience in the hire, mentoring, and leader development teams, and building scalable APIs and integrates it with partners and cloud services. Enthusiastic about architectural improvement using cloud services.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu
Skip to toolbar