Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

the ultimate guide to app development with flutter

a complete and comprehensive guide to learning flutter with explanations, tips, resources, and examples for dart, flutter, firebase, state management and more.

flutter is a powerful and intuitive framework for building beautiful, cross-platform mobile applications that uses the dart programming language.

this essentially means that flutter can be used to write one codebase for an app that runs natively on both ios and android.

with all the hype around flutter and mobile app development, learning flutter is both a valuable skill and a gratifying endeavor in its own right. however, the path to learning flutter is a little unclear due to how new the language is.

  • the language is constantly being updated (to the point where tutorials from just a few months ago are out of date)
  • there are a lack of freely available, well thought out and comprehensive courses or books compared to some other more established frameworks and languages like python

this guide compiles tutorials, tips, examples, and resources to help make the learning process for flutter much easier. you can be a complete beginner, an intermediate or even advanced programmer to use this guide. i hope you find it helpful!

getting started

before we get started with dart and flutter, we first need to set up our programming environment, which is what we will be using to code flutter apps.

the two main ides that provide the most features for dart and flutter are visual studio code (vs code) and android studio. choosing either one is up to you, but i do have a slight preference to vs code because it looks sick…

vim can also be used if you have coc or native lsp and install the dart and flutter extensions.

choosing the right ide is essential to getting all the features that the dart programming language provides us with. once you have your ide / text editor, make sure you install the dart extension and the flutter extension. with these extensions, our ide / text editor will perform extremely detailed error checking, type checking, null safety checks, and formatting to make our lives as developers a lot easier.

once you have your environment set up, let’s move on!

learning dart

dart is a language developed by google that is the backbone to the flutter framework. it is the language you will be using when you code up apps with the flutter framework.

if you have never coded before or have less experience with programming, i recommend you take a look at this excellent tutorial from mike dane on youtube (ps don’t sit through the whole thing all at once! spend some time thinking about programming concepts in your subconscious mind while you take breaks or do other things).

if you have experience with languages like javavscript or java, here are the basics of dart.

outline:

variables

variables in dart are type-checked, which means that every variable must be declared with a specific type, and that type must match with what the variable is assigned throughout your programs.

here are some basic types and examples:

string foo = 'foo';
int bar = 0;
double foobar= 12.454;
bool iscool = true;
list<string> = ['foo', 'bar'];

dictionaries (which map keys to values) are specificed as the ‘map’ type in dart. you have to specify the key type and the value type, like as follows.

map<string, int> grades = {
  'john': 99,
  'doe': 30,
}

you will get an error if you assign an incompatible type to the same variable.

string foo = 'foo';
foo = 2; // error

you can use ‘var’ and ‘dynamic’ to make a variable type dynamic, but it is usually not a good idea to do this, as it could end up in frustrating errors down the line.

additionally, dart has a unique ‘final’ and ‘const’ operator that can be used for declaring variables. ‘final’ is generally used to declare a variable that won’t change once it’s declared. for example, if a user types in their name and we save it to a variable, we know that variable (their name) won’t change, so we can initialize / declare it like so:

final string name;

the ‘const’ keyword is a little more of a specific use case – it makes the variable constant from compile-time only. it will be useful later down the line for the flutter framework, but for now, don’t worry about ‘const.’

functions

functions are declared by specifying the return type, the name of the function, and the parameters within paranetheses. void is used to specify the return type of nothing is returned.

// doesn't return anything but still executes some code
void main() {
  print('hello world');
}

// prints 'hello' but also returns the string 'complete'
string hello(int reps) {
  for (int i = 0; i < reps; i++) {
    print('hello');
  }
  return 'complete';
}

// returns a list of strings (list<string>)
list<string> people() {
  return ['john', 'doe'];
}

asynchronous functions are functions that can execute different commands at the same time – asynchronously.

an example of how this would be useful is in calling apis (basically, trying to retrieve some sort of useful information or data that was programmed by someone else, from the web). if our function calls an api and assigns a variable to the api’s response, but our entire app is waiting for that function to finish executing in order to do something, then it isn’t very efficient. if we make this function asynchronous, the function calling the api can then execute at the same time that the app allows other functions to execute, or while the app does something else.

within an asynchronous function, if we ever need our function to wait for some line of code to finish before we continue, we simply precede the code with the keyword, ‘await’.

for asynchronous functions in dart, add the ‘async’ keyword between the parentheses and the curly braces, and enclose the return type in ‘future<[return type]>’.

future<string> retrievedata() async {
  response = await someapicall(); // assuming the api call returns a string
  return response;
}

conditionals

if statements are simply written as follows:

bool somecondition = true;

if (somecondition) {
  print('somecondition is true');
} else {
  print('somecondition is false');
}

loops

for loops are very important in all programming languages, and there are a few ways to implement them in dart.

list words = ['hello', 'world', '!'];

// 1st way
// declare an int i, increment it by 1 until it is no longer 
// less than words.length (3 in this case)
for (int i = 0; i < words.length; i++) {
  print(words[i]);
} 

// 2nd way
// for each element in word, dart will take that element (in this case, a string, word)
// and will allow you to execute code using that element (here, we just print it out)
// the rocket notation (=>) allows us to write only a single statement to execute
// on the right side. otherwise, we would do (word) { print('hey!'); print(word); }
words.foreach((word) => print(word));

// 3rd way
// very similar to the 2nd way but a different syntax
for (string word in words) {
  print(word);
}

pretty cool!

classes, objects, and constructors

classes can be created and used like this. notice how the type of the object that is instantiated is declared, and how the object is instantiated.

class car {
  string name;
  int price;
  bool ismadebyelonmusk;
}

void main() {
  car tesla = car();
  tesla.name = 'model s';
  tesla.price = 50000;
  tesla.ismadebyelonmusk = true;
}

here’s an example of how constructors and methods work.

class car {
  car(string name, int price, bool ismadebyelonmusk) {
    this.name = name;
    this.price = price;
    this.ismadebyelonmusk = ismadebyelonmusk;
  }
  string name;
  int price;
  bool ismadebyelonmusk;
  
  bool isexpensive() {
    if (this.price > 30000) {
      return true;
    } else {
      return false;
    }
  }
}

void main() {
  // instantiate the class by using its constructor
  car tesla = car('model s', 50000, true);
  // returns true by using the car class's method, isexpensive, because tesla.price = 50,000
  bool iscarexpensive = tesla.isexpensive();
}

more resources

as always, make sure you review these concepts often to get familiar with them. here are some more resources to help you cement these into your brain that i found very useful when i was learning.

learning flutter ui

now that you know some of the basics of the dart programming language, let’s take a look at the flutter framework – first, we’ll install a programing environment for flutter.

installation

the installation process can be a bit tricky for some users depending on the os, but it isn’t too bad. follow these resources to install flutter and the necessary tools for your os (in addition to flutter, you will also need an emulator / virtual phone in order to test your apps).

windows

macos

linux

once finished, run this command in the terminal to make sure your environment is all ready to go.

$ flutter doctor

create a flutter project with the following command.

$ flutter create <project_name>

the folder structure will look something like this. we will be putting all of our code in the ‘lib’ folder, and i’ll explain the other folders later in the guide. for now, just follow along with the code in the guide and don’t worry about project setup just yet.

good job! now that we have our environment set up, let’s take a look at how apps are laid out in the flutter framework.

widgets

flutter apps are built using things called widgets. if you are familiar with a frontend javascript framework, these are akin to components, but many come already built by the framework. widgets are also quite similar to html elements like ‘p’ (for paragraph), ‘h1’ (for header 1), etc.

widgets are essentially the basic elements or building blocks of an app that flutter has created for us. they are instantiated with specific properties or parameters that flutter is expecting from you. for example, to display text on the app screen, we use a widget called the text widget, comparable to the html ‘p’ element, that is instantiated by passing in a string. here’s what it looks like, in code and on an app.

// displays the text on the app screen
text('some string here');

there’s also a prebuilt button widget from the flutter library called the elevatedbutton (just a material theme button) which takes in an onpressed property (the code to be executed after the button is pressed) and a child property (the text widget that displays the text of the button). another one is the textfield, which handles input text.

layout

widgets are also used for things more complicated than just displaying text or pressing buttons. the way flutter lays out things in the app is also done through widgets. for example, the container widget, which is akin to the ‘div’ in html, will give us the ability to wrap another child widget in a container, in order to add padding, margins, colors, or something else. the inner widget is usually called the ‘child’ widget, and the container would be the ‘parent’ widget of the ‘child’ widget. makes sense, right?

container(
  child: text('hello!' )
),

some more important layout widgets are the row and column widgets. these widgets allow you to stack widgets horizontally or vertically on the screen. they are instantiated by passing in a list of children widgets. here’s how they work.

row(
  children: [
    // in the app, child widgets of a row are laid out left to right like so
    text('left text'),
    text('middle text'),
    text('right text'),
  ],
)

column(
  children: [
    // child widgets of a column are laid out top to bottom like so
    text('top text'),
    text('middle text'),
    text('bottom text'),
  ],
)

left: row, right: column


some layout widgets are wrapped around every other widget we put onto the screen. for example, the scaffold widget is usually used to lay out or ‘scaffold’ the screen for us, and it is used like this:

scaffold(
  body: container(
    child: text('hi!'),
  ),
)

left: with scaffold, right: without scaffold


another useful widget is the listview.builder widget. the listview.builder widget takes in two main arguments – the itemcount (how many list items to build), and the itembuilder (which will return what is actually built). here’s what it looks like.

list<string> people = ['john', 'doe', 'jane'];

listview.builder(
  itemcount: people.length, // 3
  // index is the current index that the builder is iterating on. think of it like the 
  // 'i' in the for loop,  for (int i = 0; i < whatever; i++) 
  itembuilder: (context, index) {
    return container(
      child: text(people[index]),
    );
  },
)

we will see later how these look in screenshots.

properties / parameters

each widget built by flutter can be passed a number of properties or parameters. as we saw earlier, the container widget takes in a ‘child’ property, and it can also take in a ‘color’ property to define the background color of the container.

each widget will have a number of parameters specific to that widget that you can learn about by reading the flutter documentation or by using the intellisense of your ide / text editor. for example, in vs code, you can press ctrl+space or hover after typing in a widget to see what properties it can use.

usually, you can also pass in all of your styles to the widget through the parameter.

many of these parameters only accept very specific types or objects. the ‘child’ property of the container widget will only accept another flutter widget. the ‘color’ property will only accept objects predefined by flutter (like colors.black, colors.blue, etc) or objects instantiated in a certain way (color(0xffffffff), one way to do it using hex codes).

in the text widget, we can style the text by passing in a ‘textstyle’ object instantiated with our styles, passed into the ‘style’ property of the text widget.

text(
  'text to display',
  style: textstyle(
    // font color
    color: colors.purple,
    // font size
    fontsize: 16.0,
    // font weight
    fontweight: fontweight.bold,
  ),
)

for styling in a container widget, we use the ‘decoration’ property and pass in a ‘boxdecoration’ object that is instantiated with our styles.

container(
  // styling the container
  decoration: boxdecoration(
    // you can define the background color in this object instead
    color: colors.blue,
    // border radius - valid arguments must be of class borderradius
    borderradius: borderradius.circular(20.0),
  ),
  height: 50.0,
  width: 50.0,
  // margin of the container - argument must be of class edgeinsets
  margin: edgeinsets.all(8.0),
  // child element (using the center widget centers the text widget)
  child: center(
    text('hello!')
  ),
)

in column widgets, you might need to vertically align your objects to the center of the page. here’s how you could do that using the column widget’s ‘mainaxisalignment’ property (main axis of the column is vertical). you can also align text horizontally in a column widget using the ‘crossaxisalignment’ property.

column(
  // argument passed in must use the mainaxisalignment object 
  // can you start to see the practices and conventions flutter everywhere?
  mainaxisalignment: mainaxisalignment.center,
  children: [
    text('top text'),
    text('center text'), 
    text('bottom text'),
  ],
)

left: without mainaxisalignment.center, right: with mainaxisalignment.center (as in the code example above)


other properties of column include crossaxisalignment, mainaxissize, and more. chances are, if you feel like you need to do something to style your widget, you just need to google the properties of that widget, or google how to accomplish what you need to find which property to use.

the amount of properties and classes you need might seem a bit daunting to learn about, but over time it will become intuitive for you (plus, google is your best friend)!

formatting

now, you might be wondering, what the heck are all these commas and new lines everywhere? the reason i’ve laid out the code like this is because of how your ide will format your code for you. it does this by detecting trialing commas and adding corresponding new lines.

adhering to the formatter will make your code much more readable both for yourself and for others. here’s a simple example.


// weird code you might write totally without a formatter
// not very good, is it?
column(children:[
  container
  (child: text
  (
    'hi!'
  )),
  text(
    'hi'
  )
]
)

// code you might write with the formatter, but without adhering to the formatting guidelines
column(children: [
  container(color: color(0xffffff), child: text('hey there'), margin: edgeinsets.all(5.0), padding: edgeinsets.all(5.0)),
  text('hi')])

// code you write with the formatter, that adheres to the formatter
column(
  children: [
    container(
      color: color(0xffffff),
      child: text('hey there'),
      margin: edgeinsets.all(5.0),// add a trailing comma to the last parameter (margin)
    ), // add a trailing comma to the widget
    text('hi'), // add a trailing comma to the last child of the column
  ], // add a trialing comma to the children parameter
)

would you agree with me in saying that the last example is the easiest to read and the easiest to code with (disregarding the comments)?

simply just add a trailing comma to your widgets and their parameters, hit save, and the formatter will do the rest for you. over time, you’ll get better and better at it.

stateless widgets

stateless widgets are essentially widgets that don’t change – they are static. one example of a stateless widget would be a page that displays the names of the states in the us in a list. let’s take a look at a more simple example by creating a stateless widget that simply returns a white container. here’s the syntax for defining a stateless widget.

class listofstates extends statelesswidget {
  // this is the constructor, but don't worry about it right now
  const listofstates({key? key}) : super(key: key);

  // @override is good practice to tell us that the following method (in this case,
  // the build method) is being overriden from the default build method
  @override
  // this build function returns a widget
  widget build(buildcontext context) {
    return container(color: color(0xffffffff));
  }
}

good news – most ides contain snippets to automatically create stateless widgets for you! just type in stless into your ide and press tab or enter to generate all the code necessary.

if you would like to add parameters for your stateless widget (for example, making a ‘message’ parameter to pass into a stateless widget that displays that message), we need to use constructors in the same way that classes are constructed. here’s how.

class displaymessage extends statelesswidget {
  // add it to the constructor here after the key, as 'required this.<parameter>'
  displaymessage({ key? key, required this.message }) : super(key: key);

  // initialize it as a 'final' variable (it won't change)
  final string message

  @override
  widget build(buildcontext context) {
    return container(
      child: text(message),
    );
  }
}

this widget would then be instantiated in another parent widget like so:

scaffold(
  body: column(
    children: [
      ...
      // instantiating the stateless widget we just created (which is in another file) 
      // with string, the message we want to display
      displaymessage(message: 'hello there!'),
      ...
    ],
  ),
)

stateful widgets

stateful widgets are widgets that can react to certain changes and then be rebuilt. this is useful if we want our app to be interactive. for example, let’s say we want to have a counter in our app. whenever the user presses a ‘+’ button, we want the app to display an increase in a variable we define, ‘count’. here’s how.

note: whenever we want our stateful widget to react to any changes (which requires flutter to rebuild the page), we use the setstate(() {}) method.

class displaycount extends statefulwidget {
  const displaycount({key? key}) : super(key: key); 

  @override
  _displaycountstate createstate() => _displaycountstate();
}

class _displaycountstate extends state<displaycount> {

  // defining a variable, count, inside our widget
  int count = 0;    

  @override
  widget build(buildcontext context) {
    return column(
      children: [
        // display the count as a string
        text(count.tostring()),

        elevatedbutton(
          // the text displayed on the button
          child: text('click me to add +'),

          // the code that will execute when the button is pressed
          onpressed: () {
            // setstate is called to signal to flutter to rebuild the widget
            // count is incremented by 1, so the widget will be rebuilt with 
            // a new value displayed in the text widget above
            setstate(() {
                count += 1;
            });
          },
        ),
      ],
    );
  }
}

we also have access to ide snippets for stateful widgets too. just type in stful.

constructors in stateful widgets are the same, but they are only declared in the displaycount widget and not the _displaycountstate widget. in the _displaycountstate widget where you will be putting your code, you can refer to the variable as (widget.[variable]).

class displaycount extends statefulwidget {
  const displaycount({key? key, required this.message}) : super(key: key); 

  final string message;

  @override
  _displaycountstate createstate() => _displaycountstate();
}

class _displaycountstate extends state<displaycount> {
  ...
  @override
  widget build(buildcontext context) {
    return column(
      children: [
        // refer to the 'message' attribute defined above as widget.message
        text(widget.message),
        ...
      ],
    );
  }
  ...
}

stateful widgets are instantiated in the same way as stateless widgets are.

stateful widgets are very useful for dealing with anything related to business logic, interactive features, and listening to streams of data on the backend, as we’ll see later.

null safety

in recent versions of flutter, null safety was introduced in order to greatly help developers in dealing with notorious null errors.

essentially, if something like a string is declared and is supposed to be assigned a valid value like ‘hi!’, in the case that it somehow is assigned a null value (basically, assigned a value of nothing), then all sorts of problems start to happen – some parts might start missing text, functionalities, etc.

flutter’s null safety helps developers fix these issues by using powerful ide features that force developers to be more strict with null checking. this means that developers have to account for the situations in which the variables they declare might take on null values.

in null safety, there are 3 important symbols to know about. the ‘?’ symbol, the ‘!’ symbol, and the ‘??’ symbol.

‘?’

if we declare a variable that we think might somehow take on a null value, we add the ‘?’ operator to the end of the type declaration to remind us and the ide to include strict null checking on that variable. here’s an example.

// initializing a string wih a nullable type and assigning it to the 
// return value of this function, fetchsomedataorsomething()
string? response = await fetchsomedataorsomething(); 
// in the case that the function returned something null and response has a null value,
// it is now safely accounted for with this conditional statement
if (response != null) {
  print(response);
} else {
  print('error');
}

‘!’

if we declare a nullable type for a variable but we know for certain that it won’t be null, we use the ‘!’ operator at the end of the variable name. note: try to avoid using this because it bypasses all the null safety checks performed by the ide.

// fetchsomedata() returns type bool
bool? response = fetchsomedata(); 
// declaring that response will always be a valid value and not null
if (response! == true) { 
  print('function has returned true');
} else {
  print('function has returned false');
}

‘??’

when we are assigning a value to a variable, we can check whether it is null or not and assign a value from there. if the value it is assigned is null, we can add the ‘??’ operator and add a default value on the right, in case it is null.

string? response = fetchsomething();
// if response is not null, the 'something' variable will take on the value of response'
// if response is null, the 'something' variable with take on the value on the right side
string something = response ?? 'defaultvalue';

learning firebase

since flutter was developed by google and firebase was also developed by google (which was made specifically for app developers), flutter and firebase work very well with each other as frontend and backend tools.

the main backend of most projects will be using a database, which firebase provides with its cloud firestore database. the basic structure of firestore databases is quite simple, but is very different from conventional, realtime databases like with sql. instead, firestore is a no-sql database.

this series is extremely good on getting familiar with the structure of firebase, so please take a look. episodes 1, 2, and 4 are particularly important.

get to know cloud firestore

essentially, a firebase firestore database is created by making top-level ‘collections’ which can be things like ‘users’, ‘messages’, ‘products’, etc. these collections can have documents in them.

documents are specific instances of its parent collection, which can be assigned a number of ‘fields’ with corresponding values. for example, here’s how the macbook pro document in the products collection might look:

left side: collections, middle: documents of the collection, right: fields in this document

note: i’m accessing a cloud firestore database through the firebase console on a dummy project i created

the thing about no-sql databases is that you can create documents in the same collection without the same fields!! for example, the ‘pencil’ document might be missing the ‘rating’ field, but there wouldn’t be any errors.

some other important things to know about firebase are billing and security rules.

billing in firestore is charged not by the size of the database, but by the number of reads and writes to the database. for example, if you create an electronics product (in the form of a document) and you add it to the database, it counts as one write. if you wanted to update the price of the product, it would also count as 1 write.

if you needed to load all the ‘food’ collection’s products, firebase would charge you 1 read per every document in the collection.

however, firebase is quite generous with its limits. but, if you would like to take your app to production (put it into the real world), it’s best to be wary of how billing works in order to optimize your database calls.

check the firebase pricing page to learn about the limits for the free tier.

more really good resources:

connecting firebase with flutter

now that we know about the most important part of firebase (the firestore database), how do we get access to that data in flutter?

streambuilder

we can use a streambuilder for this purpose. a ‘stream’ is essentially just a stream of data that we are constantly watching for changes in. one end of the stream is the firestore database. the other end of the stream is our app.

thus, when something changes in the firestore database (say, a new product is added), that change goes down the data stream and gets noticed by our flutter app. once that change is noticed, the streambuilder widget rebuilds itself in order to incorporate that change (the new product now appears on our app).

here’s the syntax:

streambuilder(
  // gets an instance of a firestore database and retrieves 'snapshots' of the macbook pro document
  stream: firebasefirestore.instance.collection('products').doc('macbook pro').snapshots(),
  // builder defines what will be built on the app using this 'snapshot' data (the stream data)
  // firestore collections are of type querysnapshot
  // firestore documents are of type documentsnapshot
  // both are referred to as asyncsnapshots because they are asynchronous snapshots
  builder: (buildcontext context, asyncsnapshot<documentsnapshot> snapshot) {
    // check that there is data in the stream and that it has finished loading
    if (snapshot.hasdata) {
      return container(
        // snapshot.data gives you access to all the fields in the document
        // get the values of the fields by using square brackets and the 
        // name of the field, like so
        child: text(snapshot.data['name'])
      ),
    }, else {
      // if there's no data yet, show a loading sign
      return circularprogressindicator();
    }
  },
)

it might look complicated, but it really isn’t. on one side you are accessing a stream of data, whether it be a collection or document, and you are building a widget that has access to that data through the ‘snapshot’ variable. if there are any changes that the streambuilder detects on firestore’s end, the widget will be rebuilt.

futurebuilder

streambuilders are great, but what about if you didn’t need to listen to changes on firestore’s end? what if you just wanted to retrieve some information, say the price of the macbook, and be done with it (you might know that the values won’t change)?

we can do that with a futurebuilder.

futurebuilders take in an asynchronous function as a parameter, and a builder to build something once that function has finished executing (similar to the streambuilder). in our example, our asynchronous function or ‘future’ (as the futurebuilder calls it) would be retrieving the price of the macbook, and our builder would be the widgets displaying that price.

// defining an async function that returns an int
future<int> retrievemacbookprice() async {
  // ps here's how to retrieve a single document from firestore - 
  // in our case, the macbook document
  var document = await firebasefirestore.instance.collection('products').doc('macbook pro').get();
  // the data you get back (the document and its fields) will be a dictionary that maps 
  // keys (type string) to values (type dynamic)
  map<string, dynamic> macbookdata = document.data();

  int macbookprice = macbookdata['price'];
}

futurebuilder(
  // builder will only build after this 'future' function is done executing
  future: retrievemacbookprice(),
  // the 'snapshot' here refers to what is returned from the future!
  builder: (buildcontext context, asyncsnapshot<int> snapshot) {
    if (snapshot.hasdata) {
      // data from the snapshot is accessed like so
      int price = snaphot.data['price']
      return container(
        // convert int to string
        child: text(price.tostring()),
      );
    } else {
      // if there's no data yet, show a loading sign
      return circularprogressindicator();
    }
  }
)

whew, that was a lot! but guess what… now that you know about how firebase, futurebuilders, and streambuilders work, you are very far in your journey to creating robust apps in flutter.

state management

state management is a very important concept in flutter that goes like this:

say you want to make an app that keeps track of your user’s profile and information. after they log in with their username and password, you want to display their username in every page of the app as a greeting (for example, to say ‘hello, [name]!’). how would you do this? how do you pass around the user’s values of ‘username’ and ‘password’ throughout the whole app?

you could pass the username as a parameter for all the stateless and stateful widgets that make up the different pages. but in reality, you want something that holds that username value that you can access across all screens / pages.

this can be done using a ‘provider’ widget, a built in state management solution.

a provider is called a ‘provider’ because it is a parent widget that ‘provides’ a value to pass down to the child widget, so that the child widget has access to everything from the value / entity. in our example, if we had a ‘cart’ class that we wanted to access in child widgets, it would look something like this:

provider(
  create: (context) => cartmodel(),
  child: myapp(),
)

thus, in the myapp child widget, we would have access to the cartmodel and all of its methods and such. you can instantiate the cartmodel class to access the data in two ways:

// 1st way
provider.of<cartmodel>(context).removeallitems();

// 2nd way
// context.watch listens for changes in cartmodel - if data changes, the parent will rebuild
// whatever is necessary
context.watch<cartmodel>().removeallitems();
// context.read returns cartmodel / the model of interest without listening to changes in 
// the data
context.read<cartmodel>().removeallitems();

this calls provider to look at the model that is of type cartmodel, and calls the method removeallitems(). in the 2nd way, the object of type cartmodel (whatever is between < >) is instantianted by parentheses -> context.read< >().

what if we wanted to access another piece of data that requires state management – say, the user’s preferences for their color theme in the app? we could create a class called ‘userpreferences’, but how would we have access to it on top of the cartmodel class?

one way to do it would be to nest providers.

provider(
  create: (context) => cartmodel(),
  child: provider(
    create: (context) => userpreferences(),
    child: myapp(),
  ),
)

so we would have access to both the userpreferences model and cartmodel in myapp. but you can probably tell that this gets unwieldly, fast, right? that’s where multiprovider comes into play.

the ‘multiprovider’ widget allows us to define multiple ‘providers’ at the very top of the app (main.dart), where all the child widgets have access to each of the providers.

multiprovider(
  providers: [
    provider<cartmodel>(create: (_) => cartmodel()),
    provider<userpreferences>(create: (_) => userpreferences()),
  ],
  child: myapp(),
)

what a natural progression!

that’s the basics of state management. take a look at the extra resources listed below to get more familiar with these concepts and syntax.

best practices

best practices are always important to keep in mind when developing any large projects in flutter.

folder structure

to maintain a large project, make sure your folder structure is correctly organized.

here’s how folders are usually structured:

as we saw before, lib is where you will put all your flutter code. flutter then converts its code into android and ios code to make native apps, which can be found in the android and ios folders. any images, svgs, or pictures you use should be placed in an ‘assets’ folder, which you have to create.

in the lib folder, you should split code up into screens, models, services, widgets, and constants. main.dart will be your wrapper file.

constants is used for placing constants.dart, which usually defines themedata and color schemes for your app, to make it easier for your app to conform to a certain style. for example, i usually define kprimarycolor and ksecondarycolor in the constants.dart file. you can also use a theme.dart file to create themedata objects.

models are the classes you want to create to make it easier to work with data in flutter. for example, you might want to create a user class that has properties of ‘username’, ‘nickname’, ‘age’, etc. in the models folder, create and name your file based on what you would like your class to be called. if i wanted to make…

class user {
  string usernamename;
  string nickname;
  int age;
}

then i would name the file user.dart (if it is two words, simply use an underscore instead of a space -> food_item.dart).

screens is the folder where you will place most of your code – the ui code for all of your screens. to create a new screen, create a folder and name it the screen, and place your code in that subfolder. this way, all your screens will be different folders in the ‘screens’ folder. in your specific screen folder, name the main file (name_of_screen).dart.

if your screen has many components to it, create a components folder in the screen’s directory.

services is used for putting all the classes that contain any business logic. these follow the same folder conventions as the models folder.

widgets is used for putting all widgets you custom created that you use for multiple screens. for example, if you created your own button widget that you want to use on both the login and sign_in screens, just put that button file into the widgets folder.

separate business logic from frontend

business logic is essentially any code that doesn’t directly have to do with the layout of the app. for example, if you had a login screen, the ui would be the column, textfield, and elevatedbutton widgets. the business logic would be how the user would sign in to the backend server you are using (for example, firebase).

it is generally a good idea to keep these separated so you don’t mix backend / dealing with data and frontend, which can lead to messy and confusing code. if i wanted to look into the code for the product_details screen, why would i want to see how the product is dealt with on the backend? it’s cleaner to separate the two paradigms.

what this means for us is that we should place as much of the business logic / backend code in the ‘services’ folder as we can, and not in the ‘screens’ folder. i usually do this by defining an ‘apiservices’ class that has a number of methods that deals with the business logic.

abstract as much as possible (make more widgets)

in flutter, it is in your best interest to extract as much code as you can. what this means is that whenever you have a part of the widget tree that is dedicated to a single use case, extract it into its own widget and put it somewhere else. here’s an example.

// products_screen.dart

scaffold(
  // column widget to lay out everything on the page vertically
  body: column(
    children: [
      // nested column widget dedicated to displaying electronics
      column(
        children: [
          container(child: text('electronics')),
          text('macbook pro'),
          text('iphone'),
          text('galaxy buds'),
        ],
      ),
      // nested column widget dedicated to displaying food
      column(
        children: [
          container(child: text('food items')),
          text('jelly beans'),
          text('peanut butter'),
          text('apples'),
        ],
      ),
    ],
  ),
)

this would be putting the ‘food items’ section and ‘electronics’ section into a single widget tree, which gets messy and confusing if the project grows bigger. as best practices, here’s what it would look like instead.

// screens/products/products_screen.dart

scaffold(
  body: column(
    children: [
      // extracted widgets (put the widgets into their own file in the 'components' directory of this screen's directory)
      electronicssection(),
      fooditemssection(),
    ],
  ),
)

// screens/products/components/electronics_section.dart

class electronicssection extends statelesswidget {
  const electronicssection({ key? key }) : super(key: key);

  // same widgets, just put into the build function as a returned value
  @override
  widget build(buildcontext context) {
    return column(
      children: [
        container(child: text('electronics')),
        text('macbook pro'),
        text('iphone'),
        text('galaxy buds'),
      ],
    );
  }
}


// screens/products/components/food_items_section.dart

class fooditemssection extends statelesswidget {
  const fooditemssection({ key? key }) : super(key: key);

  // same widgets, just put into the build function as a returned value
  @override
  widget build(buildcontext context) {
    return column(
      children: [
        container(child: text('food items')),
        text('jelly beans'),
        text('peanut butter'),
        text('apples'),
      ],
    );
  }
}


the result is much cleaner and much easier to debug and code with.

testing

creating unit tests for your flutter app are a very convenient way to make sure adding new features doesn’t break your code.

tests are written to automate the process of checking certain functionalities in your app. for example, you can write a unit test to make sure the login screen and business logic is working correctly, which you might run everytime you make changes to other parts of your app.

take a look at these resources to learn about testing in flutter.

helpful resources

now that you know the basic syntax of flutter and how it works, you need to put this knowledge into practice! i recommend following along with flutter app build tutorials to see just how advanced coders develop apps, and then try to code an app with only ui components by yourself (you can look on dribbble for ui inspiration). good luck!

these are all the compiled resources, listed from more beginner-friendly to more advanced.

dart

flutter

flutter app tutorials

firebase

state management

if this feels a little bit overwhelming, don’t feel discouraged. many times i was stuck, but once i understood a new concept i quickly made tons of progress. it’s never too late. be glad that you are here in the first place!

i hope you enjoyed this comprehensive guide!


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

Comments are closed.