Skip to content

Widgets in Flutter 1

Abhinav Agrawal edited this page Jan 23, 2021 · 2 revisions

Basic Widgets in Flutter

This week, we will discuss Widgets in Flutter and how to create an app that uses basic Widgets.

What is a Widget?

Everything you use or interact with or even see on an app is a Widget.
The only requirement of a Widget is that is must return other Widgets. However, there are a few exceptions to this rule, i.e., low-level Widgets like the Text Widget, which usually returns a primitive data. Widgets may be a bit complex to grasp at first, but with a little time and practice, you will be able to create and add other widgets with no difficulty.

When we build an app, we return a MaterialApp Widget, which will enclose other Widgets of the app.

Widget build(BuildContext context) {      //Here you return a Widget from the build function and the parameter it receives is a BuildContext object
    return MaterialApp(
      title: 'Flutter Demo',              // title here takes in a String input, hence "title : 'Flutter Demo'"
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(                     // home takes in a Widget, for which we send a Scaffold Widget. Note: Scaffold holds all contents you'll be showing on your app
        appBar: AppBar(                   // appBar is a Scaffold parameter which usually is provided with a Widget called AppBar. AppBar in the top bar you see in most apps which contain the menu and the search options
          title: Text('Hello from Flutter'),     // title again takes a Widget for which we provide a Text Widget. This provides for the title on the AppBar
        ),
        body: Center(                     // body contains the main content of your App which also takes in Widget 
          child: Container(
             child: Text('My First App')
          )
        )
      )
    );
  }

You can always use the keyboard shortcut Ctrl + Space to see the required parameters for the Widget in VSCode

Stateless and Stateful Widgets

All the Widgets in Flutter can be classified into two types based on the state of the Widget itself.

  • Stateless Widgets
  • Stateful Widgets

Stateless Widgets

Stateless Widgets are simple Widgets which do not change their state, i.e., their state is constant. Do not confuse "stateless" to mean "having no state at all". Stateless Widgets have a state, but it does not change. To create one, we need:

  • A name for the new class
  • To extend our class from StatelessWidget.
  • Implement the build() method, that will receive one argument of type BuildContext and return a result of type Widget.

Click here to read more about creating Stateless Widgets.

Stateful Widgets

Stateful Widgets are Widgets in which the Widget state can change when a particular event is triggered. Updating a Stateful Widget properties will trigger life cycle hooks and render its content using the new state.
This is the basic structure of a Stateful Widget

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Container(color: Colors.blue);
  }
}

Here we have declared our main class called MyApp which extends the StatefulWidget class. That means now we have to define the generic method called createState() in that class which will return one another class which extends the generic class State.

Click here to know more about creating Stateful Widgets in Flutter

Analyzing The Widgets of the Flutter Counter App:

When you use the flutter create <app-name> command, FLutter creates an app with a prewritten code for a basic counter up app in main.dart. Let us see what the Widgets used in the app are.

Import Statement

This is where we import all the packages and files necessary for our Flutter app.

import 'package:flutter/material.dart';

Main Function

This is the starting point of our app, i.e., this is the point or function from where all our code will execute

void main() {
  runApp(MyApp());
}

Root Widget

This is root widget of your application, Title property of the home page is being set as Flutter Demo Home Page and under Theme we have colour scheme as blue.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(   
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

Home page

This is the Homepage that will contain the body and other widgets in our application.

Here MyHomepage is a Stateful Widget, which means the State of the homepage can be changed at any time during the lifetime of our application, here we change the state when we click the button and increase the counter.

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

Let's look at different components on the homepage and see what they are doing.

The onPressed property will call the function which will increment our counter, and we add an icon on the button, by giving the icon to the child.

floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),

This function will increment the counter and setState will update the value of the counter so that our application will reflect the changes.

int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

We will use the Text Widget to display the value of the counter, that will be updated every time we click the button.

children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],

We encourage you guys to play around with the code, make some changes and see what happens.

Check out this tutorial to learn more.

Widget Tree

If all of this class-nesting is confusing, perhaps this visual of the Widget tree will help. This is what your current counter application looks like.

Widget Tree

Sources to refer to:

Flutter Widget Catalog:

Provides all the details about widgets available for UI development. It can be referred here.

Cookbook:

This cookbook contains recipes that demonstrate how to solve common problems while writing Flutter apps. Each recipe is self-contained and can be used as a reference to help you build up an application.

Videos:

Clone this wiki locally