- How to use a Flutter to build an app with bottom navigation
- Joseph Cherry
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: geniusq1981
- Proofreader: DateBro
If you’re in mobile development, you’ve probably heard of Google’s cross-platform SDK, Flutter. The beta version of Flutter was released on 27 February and the first preview version was recently released. To help you get started with Flutter, this tutorial introduces you to some of the basics of the SDK. It also shows you how to set up the bottom navigation bar. To help you along, the code for this tutorial is available on GitHub.
What is Flutter?
Before we start writing the code, let’s talk about what Flutter is. The Flutter SDK inherits a complete development framework, including widgets and tools needed to build native mobile apps on Android and iOS. It differs from other cross-platform frameworks such as React Native and Xamarin in that it doesn’t use platform-native widgets or webViews. Instead, Flutter has its own rendering engine written in C/C++, and the Dart code used to write Flutter applications can be compiled to the underlying code on all platforms. This allows for high performance applications on every platform. Not only is the application experience very fast, but development time is also greatly accelerated through the thermal overload characteristics of Flutter. Hot overloading allows developers to immediately display the effects of changes on their devices or emulators, thereby reducing the time wasted waiting for code to compile.
How to create a Flutter application
Now that we know what Flutter is, let’s start creating our application. If you do not have a development environment ready, follow the steps on the Flutter website to install the Flutter SDK. To create the application, run “flutter create my_app”. If you want your application to use Swift or Kotlin as platform-specific code, then you can run “flutter create -i Swift -a Kotlin my_app” from a terminal or command line. To open your new project, you can use VS Code with the Dart plugin installed or Android Studio with the Flutter and Dart plugin installed. If you need help with editor installation, refer to the help documentation for Flutter.
The first step is to define the entry point
Let’s start by opening the main.dart file, which is located in the lib/ directory. Next, since we’re writing the application from scratch, delete all the code in the file. This file is the entry point for our application. At the beginning of the document:
import 'package:flutter/material.dart';
Copy the code
This imports the Material Design Widgets provided by the Flutter SDK. If you want to see all the widgets provided, you can do so in the Widgets directory.
After importing the statement, we need to add the main method.
void main() => runApp(App());
Copy the code
If you see some errors after adding the main method, don’t worry. This is because we have not yet created the App Widget class that we pass to the runApp function. The runApp function takes a class of type Widget and runs it as a root Widget.
Now we will create our App Widget. Dart again, add the following code under the main method.
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Flutter App', home: Home(), ); }}Copy the code
This creates a new stateless Widget App. It is a stateless widget because nothing in its build method depends on status updates. All StatelessWidgets need to implement the Build method, because that’s where we create the user interface. In our App Widget, we simply create a new MaterialApp and set the Home property to the first page or widget we want to display. In this case, we set it as the Home Widget, which we will create next.
Step 2 Create the home page
In the lib directory, create a new file and name it home_widget.dart. In the header of this file, we need to import the Material Widgets again.
import 'package:flutter/material.dart';
Copy the code
Next, we will create the widget that will serve as our home page. To do this, we will create a new StatefulWidget. The StatefulWidget comes in handy when the user interface needs to change based on the current state of the application. For example, now that we’re going to use the bottom navigation bar, our Home Widget will render different widgets based on the currently selected TAB. First, add the following code under the import statement.
class Home extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return_HomeState(); }}Copy the code
You may notice that the Widget class does not implement the Build method we mentioned earlier. When it comes to StatefulWidgets, the Build method is implemented in the State class corresponding to the widget. In StatefulWidget, the only method required is the createState method we implemented above, and we only return an instance of the _HomeState class. The “_” before the class name indicates that Dart marks a class or class attribute as private. We now need to create the State class for the Home Widget. Add this code at the end of the home_Widget. dart file:
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Flutter App'),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: 0, // this will be set when a new tab is tapped
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: new Text('Home'),
),
BottomNavigationBarItem(
icon: new Icon(Icons.mail),
title: new Text('Messages'),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
Title: Text('Profile'() [(), (); }}Copy the code
There’s a lot of stuff here, so let’s take a look. In the _HomeState class, we implement the build method of the Home Widget. The widget we return from the Build method is called Scaffold. This widget has some great properties that help us decorate the home screen, including adding bottom navigation bars, sliders, and tabs. We’ll just use its appBar and bottomNavigationBar properties for now. In our bottom navigation bar, we return a list of items that we want to appear in the bottom bar. As you can see, we have three tabs, Home, Message, and Profile. We also set the current index to 0 as an attribute. We’ll associate it with the current TAB later. The current index lets the navigation bar know which icon to use for the currently selected TAB.
At this point, we are almost ready to run the Flutter application for the first time. Let’s see what we have achieved. Back in the main.dart file, at the top, we need to import the newly created Home Widget. We can do this by adding the following import statement under the current import statement.
import 'home_widget.dart';
Copy the code
We should now be able to run our application. You can press F5 in VS Code, in any Dart file, or click the Run button in Android Studio, or enter Flutter Run in terminal. Please refer to the help documentation for Flutter if you need help installing the simulator or emulating the application. If all goes well, your application should look like this.
That’s great! We now have an application with a nice bottom navigation bar. However, there is a problem. Our navigation bar doesn’t lead anywhere! Now let’s solve this problem.
Step 3 Prepare the navigation
Going back to the home_Widget. dart file, we need to make some changes to the _HomeState class. At the top of the class, we need to add two new instance attributes.
class _HomeState extends State<Home> { int _currentIndex = 0; final List<Widget> _children = []; .Copy the code
The first is the index of the currently selected TAB, and the other is the list of widgets that the TAB corresponds to that you want to render.
Next, we need to use these properties to tell our widget what to display when a new TAB is selected. To do this, we need to make some changes to the scaffold Widget returned by the Build method. This is our new build method.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Flutter App'),
),
body: _children[_currentIndex], // new
bottomNavigationBar: BottomNavigationBar(
onTap: onTabTapped, // new
currentIndex: _currentIndex, // new
items: [
new BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
new BottomNavigationBarItem(
icon: Icon(Icons.mail),
title: Text('Messages'),
),
new BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text('Profile'() [(), (); }Copy the code
The three lines changed in our build method are commented with // new. First, we added the scaffold’s body property, which is the widget displayed between the application bar and the bottom navigation bar. We set the body to the widget corresponding to the _children Widget list. Next, we add the onTap property to the bottom navigation bar. We set it up as a function called onTabTap, which will take the index of the selected TAB and decide what to do with it. We’re going to implement this function in a second. Finally, we set currentIndex in the bottom navigation bar to the _currentIndex property in the State class.
Step 4 Deal with navigation
Now we will add the onTabTap function mentioned in the previous step. Add the following function at the bottom of the _HomeState class.
void onTabTapped(int index) {
setState(() {
_currentIndex = index;
});
}
Copy the code
This function takes the index of the selected TAB and calls setState on our state class. This triggers the Build method to receive the state information we pass to it and run it again. In this case, we pass the updated TAB index that changes the body of the scaffold Widget and activates the correct TAB on the navigation bar.
Step 5 Add child widgets
Our application is almost complete. The final step is to create the widgets used in the _children Widgets list and add them to the navigation bar. First create a new file called metag_Widget.dart in the lib directory. This file will serve as a simple StatelessWidget to use the background color.
import 'package:flutter/material.dart';
class PlaceholderWidget extends StatelessWidget {
final Color color;
PlaceholderWidget(this.color);
@override
Widget build(BuildContext context) {
returnContainer( color: color, ); }}Copy the code
Now all we need to do is add the PlaceholderWidget to the navigation bar. At the top of home_Widget.dart, we need to import our widget.
import 'placeholder_widget.dart';
Copy the code
Then, all we need to do is add these widgets to the _children list so that they can be rendered when the new TAB is selected.
class _HomeState extends State<Home> { int _currentIndex = 0; final List<Widget> _children = [ PlaceholderWidget(Colors.white), PlaceholderWidget(Colors.deepOrange), PlaceholderWidget(Colors.green) ]; .Copy the code
That’s it! You should now be able to run the application and switch between tabs. If you want to see the thermal overload characteristics of a Flutter, try changing the BottomNavigationBarItems. It’s worth noting that the color changes passed to the PlaceholderWidgets are not reflected during hot loading because the Flutter retains the state of our StatefulWidget.
conclusion
In this tutorial, we learned how to build a new Flutter application and make the bottom navigation bar work. Cross-platform tools like Flutter are becoming increasingly popular in the mobile space because they shorten development times. Flutter is unique because it does not require the use of the underlying native widgets or WebViews. One of the main disadvantages of current Flutter adoption is the lack of third-party support for its features. However, Flutter is still a promising tool for writing great cross-platform applications without sacrificing performance.
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.