Categories
Programming

My Explanation of Classes, Methods & Conditionals in Dart

Destini app
This is my Destini

I created my very first app with my understanding of Classes, Methods, & Conditionals in Dart called Destini. I did not create this by scratch however, I completed a challenge from the course I’ve been taking with Angela Yu on Udemy. The objective is to create a choose your own adventure story. Depending on the choices the user makes as they read along with the story, the story data that appears on the screen changes along with it. 

Recalling information you learn from tutorials and utilizing them in real life is difficult to say the least, but not impossible.

I took this step by step and eventually got through it, checking in on the solutions as I went along to see if I was getting it right. I’m pretty sure that is practically how every app gets done, Googling things to get the solutions from stackoverflow.com or something, so I’m not being hard on myself for not recalling everything I’ve learned. 

First of all I’ll run through the steps so that I can better understand what I created, because even though I followed these steps I need to better clarify what it is I’m actually doing. If you’re a new reader I’ll tell you now that I’m learning how to program so that I can build out apps of my own and I’m writing out what I’m learning in blog posts so that I better understand what it is that I’m learning.

Step 1: Download the project file using version control. That’s where you copy and paste the GitHub repository into Android Studio and it copies everything onto your computer so that you can access all the files when you ‘Get Dependencies’ when you load the project from your system. 

The project file had set up the Scaffold, but I had to put in the background image. Which after looking it up was not hard.

class _StoryPageState extends State<StoryPage> {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      body: Container(

        decoration: BoxDecoration(

            image: DecorationImage(

                image: AssetImage(‘images/background.png’),fit:BoxFit.cover


You use the property decoration: and declare BoxDecoration( image: DecorationImage( and finally image: AssetImage(‘images/filename.png, fit:BoxFit.cover.

After setting that up I needed to create a story.dart file with a class that held some objects. That class is called Story:

class Story { // creation of class

  String storyTitle; // creating object variable holding a String called storyTitle

  String choice1; // creating object variable string for the users first choice called choice1

  String choice2; // creating object variable for the users second choice called choice2

  Story({this.storyTitle, this.choice1, this.choice2}){ // creating a method that holds the objects above using this.storyTitle refers to the above variables

    storyTitle = storyTitle; // the method declares storyTitle to equal the variable passed in the input of the method

    choice1 = choice1; // the method declares choice1 to equal the variable passed in the input of the method

    choice2 = choice2; // the method declares choice2 to equal the variable passed in the input of the method

  }

}

This is sort of confusing at first glance so I tried to break it down with a // comment next to each object and method to explain it as best as I could. I am going to import this story.dart file into the story_brain.dart file I’m going to create next. You will see how it communicates with this other file next. I practically created this to be like the working mechanism that will pass data into the main.dart file appropriately, you’ll see. 


Now let’s take a look at the final story_brain.dart file, since I write these blogs after I’m done the challenge it’s easier to just explain to you what I can. Read the // comments next to the emboldened text to follow along.

import ‘story.dart’; // importing story.dart or the story class to work wit the data. 

class StoryBrain// creating the BRAIN of the app, where all the data is stored. 

  int _storyNumber = 0;  // this variable will load the first story in storyData (below) in the List on the screen, and then be updated as the user chooses. 

  List<Story> _storyData = [  // creating a List with a <widget> referencing the <Story> class and calling it _storydata, this holds all my data for the app that will load on the screen

    Story(

        storyTitle: // using storyTitle from the Story class we created in story.dart 

        ‘Your car has blown a tire on a winding road in the middle of nowhere with no cell phone reception. You decide to hitchhike. A rusty pickup truck rumbles to a stop next to you. A man with a wide brimmed hat with soulless eyes opens the passenger door for you and asks: “Need a ride, boy?”.’,

        choice1: ‘I\’ll hop in. Thanks for the help!’, // using choice1 from the Story class we created in story.dart

        choice2: ‘Better ask him if he\’s a murderer first.’),  // using choice2 from the Story class we created in story.dart

    Story(

        storyTitle: ‘He nods slowly, unphased by the question.’,

        choice1: ‘At least he\’s honest. I\’ll climb in.’,

        choice2: ‘Wait, I know how to change a tire.’),

    Story(

        storyTitle:

        ‘As you begin to drive, the stranger starts talking about his relationship with his mother. He gets angrier and angrier by the minute. He asks you to open the glovebox. Inside you find a bloody knife, two severed fingers, and a cassette tape of Elton John. He reaches for the glove box.’,

        choice1: ‘I love Elton John! Hand him the cassette tape.’,

        choice2: ‘It\’s him or me! You take the knife and stab him.’),

    Story(

        storyTitle:

        ‘What? Such a cop out! Did you know traffic accidents are the second leading cause of accidental death for most adult age groups?’,

        choice1: ‘Restart’,

        choice2: ”),

    Story(

        storyTitle:

        ‘As you smash through the guardrail and careen towards the jagged rocks below you reflect on the dubious wisdom of stabbing someone while they are driving a car you are in.’,

        choice1: ‘Restart’,

        choice2: ”),

    Story(

        storyTitle:

        ‘You bond with the murderer while crooning verses of “Can you feel the love tonight”. He drops you off at the next town. Before you go he asks you if you know any good places to dump bodies. You reply: “Try the pier”.’,

        choice1: ‘Restart’,

        choice2: ”)

  ];

String getStory(){ // this function is called in main.dart to load the next storyTitle in the List above. 

  return _storyData[_storyNumber].storyTitle;

}

  String getChoice1() { // this function is called in main.dart to load the next choice1 in the List above.

    return _storyData[_storyNumber].choice1;

  }

  String getChoice2()// this function is called in main.dart to load the next choice2 in the List above.

  return _storyData[_storyNumber].choice2;

  }

  void nextStory({int choiceNumber}){ // this function determines what story loads in the _storydata List. Passing {int choiceNumber} into the function allows us to pass an integer into the function when calling it. Like so: storyBrain.nextStory(choiceNumber: 2);

This tells the function in main.dart what choice has been selected, and what to do if we pass a 1 or a 2 into that choiceNumber variable 

    if (choiceNumber == 1 && _storyNumber == 0) { 

      _storyNumber = 2; // if user chooses choice 1 and it’s _storyNumber is 0 then change _storyNumber to 2

  } else if (choiceNumber == 2 && _storyNumber == 0) {

  _storyNumber = 1; // else if user chose choice2 and the _storyNumber is equal to 0 then change _storyNumber to 1

  } else if (choiceNumber == 1 && _storyNumber == 1) {

  _storyNumber = 2; // depending on what user choice above and ran either of those conditional statements do the following and then the following else if statements that follow the story line..

  } else if (choiceNumber == 2 && _storyNumber == 1) {

  _storyNumber = 3;

  } else if (choiceNumber == 1 && _storyNumber == 2) {

  _storyNumber = 5;

  } else if (choiceNumber == 2 && _storyNumber == 2) {

  _storyNumber = 4;

  } else if (_storyNumber == 3 || _storyNumber == 4 || _storyNumber == 5) {

      restart(); // then when user reaches the end run a function called restart() we create below

    }

  }

  bool buttonShouldBeVisible() { // hiding the bottom button on the last _storyNumber in the List

    //You could also just check if (_storyNumber < 3)

    if (_storyNumber == 0 || _storyNumber == 1 || _storyNumber == 2) {

      return true; // if _story number is equal to 0 or 1 or 2 return true, or keep the button visible

    } else {

      return false; // if it’s not less then 3 then keep the button

    }

  }

  void restart(){ // set the storyNumber back to the beginning by loading the 0 index of the List

  _storyNumber = 0;

  }

}

This is what my completed story_brain.dart file looks like and the explanations of how each of these corresponds to the main.dart file that displays the widget trees of the app. 


Screenshot of Destini App

Let’s take a look at main.dart to see what’s going on in there. I can not stress enough how important this is for me to write about, I’m having a moment of clarity right now. 


Here is main.dart:

Again, follow the // comments to understand how I’m breaking this apart for you to understand

import ‘package:destini_challenge_starting/story_brain.dart’;

import ‘package:flutter/material.dart’;

import ‘story_brain.dart’; 

// importing the story class from story_brain and story.dart

void main() => runApp(Destini()); 

// main return your runApp function and input my app Destini()

class Destini extends StatelessWidget { 

  Widget build(BuildContext context) {

    return MaterialApp(

      theme: ThemeData.dark(), // this tells the app what color it should be

      home: StoryPage(), // this is going to hold the part of our app that a will change appearance in the StatefulWidget below

    );

  }

}

StoryBrain storyBrain = StoryBrain();

// this can be confusing, but we’re calling our class with the first StoryBrain and we are creating an object in our main.dart called storyBrain and its going to hold or equal the StoryBrain(); class data. This tells the main.dart to interact with all objects in that class in the file story_brain.dart

class StoryPage extends StatefulWidget {

  _StoryPageState createState() => _StoryPageState();

// this is where the app will change it’s appearance using this StatefulWidget allows changes to happen on screen

class _StoryPageState extends State<StoryPage> {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      body: Container(

        decoration: BoxDecoration(

            image: DecorationImage(

                image: AssetImage(‘images/background.png’),fit:BoxFit.cover

            )

        ), // container holding a background image in our assets folder

        padding: EdgeInsets.symmetric(vertical: 50.0, horizontal: 15.0),

        constraints: BoxConstraints.expand(),

        child: SafeArea( // keep things within the SafeArea

          child: Column(

            crossAxisAlignment: CrossAxisAlignment.stretch,

            children: <Widget>[

              Expanded(

                flex: 12,

                child: Center(

                  child: Text(

                    storyBrain.getStory(), // this loads the story into the center of the screen, notice it’s within a widget tree starting with the SafeArea, a Column, and the children in that column within an Expanded, that holds centered text. 

                    style: TextStyle( // this is changing the style of the text loaded from getStory();

                      fontSize: 25.0,

                    ),

                  ),

                ),

              ),

              Expanded( // beginning of our button

                flex: 2, // I need to understand how flex works a bit better, sorry.

                child: FlatButton( // our first button that tells us the user chose choice1

                  onPressed: () { // button action

                   setState(() {// this allows the button text to change, gotta use setState if something is changing on the button

                      storyBrain.nextStory(choiceNumber: 1);  // calling storyBrain, run the nextStory method we made, and so you know which choice it was they made, we input (choiceNumber: 1); 

                    });

                  },

                  color: Colors.red, // color of the button

                  child: Text(

                    storyBrain.getChoice1(), // calls the method in storyBrain to getChoice1 String data.

                    style: TextStyle(

                      fontSize: 20.0,

                    ),

                  ),

                ),

              ),

              SizedBox(

                height: 20.0, // this is the spacing between the two buttons

              ),

              Expanded( // button 2

                flex: 2

                child: Visibility( we use this to hide the button on the last storyTitle

                  visible: storyBrain.buttonShouldBeVisible(), // we created a function in storyBrain to check to see if the button should be visible or not

                  child: FlatButton(

                    onPressed: () {

                           setState(() {

                        storyBrain.nextStory(choiceNumber: 2); // I’m calling it to load the nextStory based on the choice made by the user with the input (choiceNumber: 2)

                      });

                    },

                    color: Colors.blue,

                    child: Text(

                      storyBrain.getChoice2(), // this get’s the String data for choice2

                      style: TextStyle(

                        fontSize: 20.0,

                      ), …


That’s what main.dart is like. I’m confident in my understanding of it after I did this diagnosis of the Dart files. It’s important for me to do these blog posts for myself rather than a motivation to do it to provide for you. Honestly I don’t think anyone is reading this far unless you’re a beginner programmer that also reads lengthy blogs on the subject, that’s a micro niche, I’m sure your out there. Hi! Thanks for reading. 

I hope you got some good insight out of this, I did. If you have any questions or comments or you think I might have got something wrong in my explanations leave a comment below or reach out to me on Instagram @kyleknob. 

Categories
Programming

Programming Until You Get Headaches

I been following along with my instructor Angela Yu on Udemy and I have been enjoying how clear and concise she is, however I really wish there was more explanation about the syntax of the Dart programming language. Like why use semi-colons instead of commas, why use curly braces here and not there etc. Maybe these are things I will look into when I find time, but it’s really testing my memory skills, and that is the sole reason I decided to get Lion’s Mane mushroom. Lion’s Mane is a medicinal mushroom that helps with memory amongst other things, and when taken with a small micro dose of psilocybin I find that installing those memories is much more easier. I do recommend you micro dose, there are amazing benefits, however I am not your personal advisor and if you are susceptible to intense anxiety, paranoia or psychosis you might not want to experiment with it and instead take more notes. 

Function Inputs or Arguments

To remind you, you create a function with a void keyword:

void nameFunc(){} — in this function’s empty parentheses () you can add data like you would a variable. For instance:

void greet(String personToGreet){} —  this creates the opportunity to use personToGreet in your function like so:

print(‘Hello $personToGreet’) — now if you’re going to call on this function you would need to add it to your void main(){} like so:

void main (){

greet(‘Kyle’);

}

This main part of your function will look between your parentheses in your greet() function you created:

void greet(String personToGreet){ 

print(‘Hello $personToGreet’);

}

This is how you pass data when you CALL on the function greet(‘Kyle’);

I’m not entirely sure how I’m going to use this in the future, but I’m sure there is a reason why she had told us about this. In this module I’m building out the Xylophone app, installing a package I found on the Dart packages website called Audio Players, importing it into my main.dart file and calling on it in my pubspec.yaml file to load sound files from my local assets folder. 

Building out this app was a small tutorial on how to pass an integer into the function that plays the sound when the button is clicked. 

void playSound(int soundNumber){

  final player = AudioCache();

  player.play(‘note$soundNumber.wav’);

}

When I press the button it calls on this function that is ran with:

playSound(1) or playSound(2) — replacing the number of my sound file in my assets folder to play a different note when another button is clicked. 

Making Use of 3 Types of Functions

Functions that start with void() have NO output, but can assume an argument between the parentheses that is a variable. If you don’t need an input it’s a function that just runs a series of steps. If you add an input then you can use that input variable in your function. The third type of function has an output and you call this by the data type you wish to output with this function. In the case of the Xylophone app we use a function to output an Expanded widget and use the inputs of the buildKey() function to specify the color of the Expanded() widget and the sound file to play when clicked, with a variable titled soundNumber, like so: 

Expanded buildKey({Color color, int soundNumber}){

  return Expanded(

    child: FlatButton(

      color: color,

      onPressed: () {

        playSound(soundNumber);

      },

    ),

  );

}

I emboldened the parameters that cannot be given a unique name to illustrate how this function is built. Expanded is the widget we are returning so we need build the function starting with Expanded and follow that with the name of the function we will later call, in this case buildKey(), but notice how inside these parentheses we add curly braces: buildKey({Color color, int soundNumber}) — the data type we are going to change is the Color property, and the data type of int that will be specified in the previous variable called soundNumber.

The curly braces are necessary only when we are creating a function that needs to specify the name of the data we wish to change. For instance we are going to need to specify the color when we call on the buildKey method like so: 

buildKey(color: Colors.red, soundNumber: 1),

buildKey(color: Colors.yellow, soundNumber: 2),

buildKey(color: Colors.blue, soundNumber: 3),

buildKey(color: Colors.purple, soundNumber: 4),

buildKey(color: Colors.orange, soundNumber: 5),

buildKey(color: Colors.teal, soundNumber: 6),

buildKey(color: Colors.pink, soundNumber: 7),

We are basically telling this buildKey function to return the Expanded widget, that has a child of a FlatButton, who’s color will be defined when we use the function (hence the Color color input when creating it), and when you press that button it’s going to run the function playSound we previously created that takes an input of an integer data type we called soundNumber. So that when we use buildKey(color: — we are telling it to look for the variable called color in the function color: color — built into the input of the function buildKey({Color color — the property of Colors.red, blue, green etc. will be specified by us when we call the function buildKey(color: Colors.red, soundNumber: 1) —  we then specify the soundNumber variable with an integer of 1 or 2 etc.

There’s a lot to wrap your mind around, but when you dissect the creation of the function it becomes logical, computers aren’t really a mystery, they just run off of logic and use keywords to know what you’re trying to tell it. So look at these functions, tinker around with the inputs, try to understand the syntax and why it’s written the way it is. We’re practically trying to imagine if we were a computer how this would translate to us in a clear way. It takes practice. 

import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';

void main() => runApp(XylophoneApp());

class XylophoneApp extends StatelessWidget {

  void playSound(int soundNumber){
    final player = AudioCache();
    player.play('note$soundNumber.wav');
  }

  Expanded buildKey({Color color, int soundNumber}){
    return Expanded(
      child: FlatButton(
        color: color,
        onPressed: () {
          playSound(soundNumber);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              buildKey(color: Colors.red, soundNumber: 1),
              buildKey(color: Colors.yellow, soundNumber: 2),
              buildKey(color: Colors.blue, soundNumber: 3),
              buildKey(color: Colors.purple, soundNumber: 4),
              buildKey(color: Colors.orange, soundNumber: 5),
              buildKey(color: Colors.teal, soundNumber: 6),
              buildKey(color: Colors.pink, soundNumber: 7),
            ],
          ),
        ),
      ),
    );
  }
}

Headaches Be Gone

Don’t let the headache of learning control your attitude around learning, I must remember to have fun at this every step of the way and take breaks if I catch myself getting too serious. Remember to laugh at your own incompetence, you will learn, but you will learn at your own pace. If you have any questions or comments leave them down below or reach out to me on Instagram @kyleknob

Categories
Programming

Function’ Flutter Confusion!

I thought I knew a thing or two about functionality and how Dart code works until I took a weekend off of coding and came back to it. Once I tried to code using my memory of Cards and ListTiles I realized I needed more practice. 

Practice Practice Practice

Coding isn’t as fun as playing guitar or skateboarding or something like that, since there’s no immediate reward. Well I suppose there is, it’s just not as immediate. What I’m trying to say is that when I’m coding it’s about the repetitiveness of it that will help me remember it, just like writing a song or doing a kickflip. My brain wants to speed through everything, but it’s the time and the work I put into it, just like everything else, that will allow me to become a better programmer.

Stateless and Stateful Widgets

I had an epiphany a moment ago when I coded a Magic 8 Ball app in Angela’s class about how Stateless and Stateful widgets interact. It looks as though the Stateless widget is where the Material App, AppBar, Scaffold and body: are held, but until now I didn’t realize that the body property holds the name of the Stateful widget. In the case of this Magic 8 Ball app, the body: property holds body: Ball(), the name of the Stateful widget and class I define to make the app function, or change state.

Class or Widget or Both?

It seems to me that the name of the widget is defined by using a class. I name my Stateful widget Ball and it changes the name of the state as well, for example:

class Ball extends StatefulWidget {

  @override

  _BallState createState() => _BallState();

}

class _BallState extends State<Ball> {

  int ballNumber = 1;

  @override

  Widget build(BuildContext context) {

    return Center(

It’s in between the class _BallState extends State<Ball> { curly braces that I define my programs variables and functions. Here, I created a variable called ballNumber and I set it to 1.

I am returning the rest of my apps body in the return Center(), portion of this Stateful widget. Which is loaded in my Stateless widget by just calling on the name of the Stateful class I titled Ball:

class BallPage extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      backgroundColor: Colors.lightBlue,

      appBar: AppBar(

        backgroundColor: Colors.blue,

        title: Text(‘Ask Me Anything’),

      ),

      body: Ball(),

    );

  }

}

Should I stop programming?

The name of this Stateless widget is called BallPage, and a lot like how I call on my Stateful widget in my body property I do the same with my Stateless widget in the runApp==> Material App widget, like so:

void main() => runApp(

      MaterialApp(

        home: BallPage(),

      ),

    );

I’m telling Dart, run this app that’s built with your MaterialApp framework and the contents of this app can be found in the following Stateless widget titled, BallPage. With your home: property you will find home: BallPage(), which makes sense when you analyze how each widget inherits the code preceding it. 

So remember that the Stateless widget holds the body of your Stateful widget, and the Material App needs to load both of those by calling on the name of the Stateless widget you define with the home: property. Make sense? Maybe re-read that a few more times. It’s computer language, you begin to realize how meticulous computer languages are. 

Stateless widgets hold no functionality and Stateful widgets do. Your Stateless widget needs to know about your Stateful widget with the body: property and your Stateful widget needs to return the Center or Container widget tree of the functional app you’re creating, got it?

import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(
      MaterialApp(
        home: BallPage(),
      ),
    );

class BallPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.lightBlue,
      appBar: AppBar(
        backgroundColor: Colors.blue,
        title: Text('Ask Me Anything'),
      ),
      body: Ball(),
    );
  }
}

class Ball extends StatefulWidget {
  @override
  _BallState createState() => _BallState();
}

class _BallState extends State<Ball> {

  int ballNumber = 1;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: FlatButton(
          onPressed: () {
            setState(() {
              ballNumber = Random().nextInt(5) + 1;
            });
            print(ballNumber);
          },
          child: Image.asset('images/ball$ballNumber.png'),
         ),
    );
  }
}

If you have any questions leave a comment below or reach out to me on instagram @kyleknob

Categories
Programming

Flutter Functionality & Me

I’ve learned a lot since my last entry, and it is all making very good sense. Since my last module with Angela I’ve become a bit more adapted to writing in Dart. I’m feeling pretty good about it. I suspect this is what I miss about being a student in conventional school. You’re introduced to something you want to know more about, you’re told to study that subject, you make notes that you can understand as you study, and you go over that for an hour a night until the test, you pass the test because it’s all so familiar, you get a good grade, you’re excited to tell your parents, and experience for the first time the pride in learning new things. 

Before I look at my notes, I’m going to try to remember some of the new things that I think are important for you to remember.

  1. Start new functions with void. Like —  void nameFunc () { //do something}; — remember the syntax, () and {};
  2. Variables can be called by it’s data type instead of calling out var use the data type to call it out — int = 12; — string = ‘Hello’; — remember the syntax = and close with ; 
  3. Card widgets are formatted for a Icon leading horizontal box, use can make children [ ] within the widget that hold ListTile (), — ListTile widgets are followed by leading: property for Icons.icon, a title: property for Text(‘Some Text.’ style: TextStyle(fontFamily’Sans’),), — and a trailing: image or icon — wrap it all in a Padding() widget for some padding
  4. Images can be called using child: Image.Asset(‘images/name.png’)— with string interpolation you can use the $myVarName to pass in the data of the var — Image.Asset(‘images/$myVarName.png’),
  5. Stateful widgets are for functionality, stateless are for displaying content only — in the class page state method you want to call out your vars and functions — in the build method is where you hot reload your app and return a widget to begin the widget tree ie. return Center (),
  6. An Expanded() widget in a Row() is meant to take up the entire width of the Row — Use Expanded widget instead of container to fit to width of any size device
  7. FlatButton(), is used to wrap an object in a button. It needs to include onPressed(){ } to tell it what to do when you press the button. This is where you can check to see if it’s working with a print (‘Hello’), statement — you can’t really update the state of the button without putting setSate((){} inside of onPressed(){ } — setState tells the app to update what’s on the page when button is pressed.
  8. Import ‘dart:math’; at the very beginning of your code to use the math library, I used this so far to call a Random function to my variables — varName = Random().nextint(max) + 1; randomizes the image in the images/ asset folder according to a number from 1 – 6, so I replace the max with a 6 and + 1 because it counts from zero

I only looked at my notes when I started to forget around number 6, but writing down notes and writing it out for you in a blog really helps cement the knowledge in my brain. If I keep this up I’ll be a pretty resourceful developer. I’m excited to learn more, but I’m going to study the layout of this code some more and I hope that you’re excited to learn more as well, us beginners need to help each other. I’m happy to share this journey with you. 

If you have any questions or comments leave them below, otherwise reach out to me on Instagram @kyleknob. 

import 'package:flutter/material.dart';
import 'dart:math';

void main() {
  return runApp(
    MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.red,
        appBar: AppBar(
          title: Text('Dicee'),
          backgroundColor: Colors.red,
        ),
        body: DicePage(),
      ),
    ),
  );
}

class DicePage extends StatefulWidget {
  @override
  _DicePageState createState() => _DicePageState();
}

class _DicePageState extends State<DicePage> {

  int leftDiceNumber = 1;
  int rightDiceNumber = 2;

  void diceChange (){
    setState(() {
      leftDiceNumber = Random().nextInt(6) + 1;
      rightDiceNumber = Random().nextInt(6) + 1;
    });

  }

  @override
  Widget build(BuildContext context) {


    return Center(
      child: Row(
        children: [
          Expanded(
            child: FlatButton(
              onPressed: (){

                  diceChange();



              },
              child: Image.asset('images/dice$leftDiceNumber.png'
              ),
            ),
          ),
          Expanded(
            child: FlatButton(
              onPressed: (){

                  diceChange();

              },
              child: Image.asset('images/dice$rightDiceNumber.png'
              ),
            ),
          ),
        ],
      ),
    );
  }
}
Categories
Programming

Understanding Google Flutter & Dart Programming

Each app begins with the runApp() function. It calls on the MaterailApp() Google designer framework that loads in all of the components to build an app with flutter. Using the home: property I call on the Scaffold() widget. Inside those parentheses I continue the widget tree with MaterialApp() as the father and home: Scaffold() within that.

Here I can add a backgroundColor defining it using Colors.nameofcolor you can find colors at material.io or just pick a basic color like Colors.red. Following the widget tree, beneath my background color of the entire app I use the property appBar: to call on the AppBar() widget within those parentheses I call out a title: property to use a Text() widget. Inside those parentheses I use a single quote ‘ to write my text string, in this case (‘This is a mushroom’). To call out the background color of the appBar I call it out just like I did for the Scaffold’s background. 

Now to add stuff to the body beneath the AppBar() I must remember to be outside of the AppBar closing parentheses ). Here I call on the body: property and I want the Center() widget for it to be centered in my Scaffold(). I must make it a child of the Center() widget by calling out child: property. Here I want an Image() widget. In these parentheses I tell the child: Image( that I want an image: that is a AssetImage() or a NetworkImage().

If it’s an AssetImage() I must open the pubspec.YAML file and under the assets portion of this YAML file I call out a folder I created in my flutter document called images. So pubspec.yaml looks something like:

Flutter:

  Assets:

    – images/nameofimage.png or simply leave it images/

Everything in this YAML file is read using double spaces, that’s important. So now that I called out an image in my Center() widget I can say I’ve successfully understand how the Scaffold() widget works and how things are placed in the body of the app. It’s a little tricky at first but the more I look over the code and try it from scratch over and over again, the more the syntax of dart starts to make sense. I would say this shouldn’t be too complicated once we get into interactivity by adding buttons and lists and so on, but if I continue to take my learning one step at a time, and then taking the time to understand it by writing it out to for you (my reader) I will eventually understand the concepts enough to code freely and solve issues as I run into them.

import 'package:flutter/material.dart';

//main is the start of all flutter apps
void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.black45,
        appBar: AppBar(
          backgroundColor: Colors.red,
          title: Text('This is a Mushroom'),
        ),
        body: Center(
          child: Image(
            image: AssetImage('images/cordycepts.png')
          ),
        ),
      ),
    ),
  );
}
Categories
Programming

How To Use Flutter Layout

To use hot reload with Flutter you got to put your MaterialApp in a StatelessWidget{}, you can type out stateless and select StatelessWidget. This creates a class for your app, so change the class to MyApp or the name of your app, and change the code it provides you to return the MaterialApp() widget. 

Now that you set that up, you can build your Scaffold() widget tree. So within your parentheses of your MaterialApp() use the property home: and add Scaffold() like this: home: Scaffold(), Remember to use the comma after every end parentheses so Flutter can appropriately format the code. You can change the backgroundColor: property using Colors.white, but what’s important is to remember to use the body: property to call out the SafeArea() widget. Inside this SafeArea() is where you will start adding a child Column() widget, or Row() widget.

For instance, you can call out child: Column() to start another widget tree within that Column() parent, however to add multiple Container() widgets within the child: Column(), you will need to use the children: property with square brackets. I’m not sure why we use square brackets, but we do. Within those brackets is where we call out our containers and add properties to them like size, color and text.

Use mainAxisAlignment: property to align them in your Column() thus in your SafeArea(). MainAxisAlignment.spaceevenly will space your Container()’s evenly on your screen, there’s a lot more MainAxisAlignment and CrossAxisAlignment spacing techniques you can try, Flutter helps with that when you start typing it recommends what you might be trying to do. 

The power of Flutter and its MaterialApp framework is proving to be tricky, but not impossible to understand. I’m taking my time with my lesson with Angela on Udemy to fully understand what I’m coding, and I’m taking this effort to explain to you to further cement my knowledge of the Dart language in my brain. I’m making a conscious effort not to try to speed through these lessons and it’s paying off. I tried taking her class on Swift development and was trying to learn at some unreasonable pace that eventually when it got too difficult I gave up. If you’re like me and you can spot out your weaknesses, then do what you can to approach confronting them carefully. It is easy to be disappointed, but it takes real patience and practice to learn new things, and it’s real important to have a passion project you want to create to keep the fire going. I want to learn Flutter to build out my iOSs app readySketch, so that I can bring it to Android, expand it’s capabilities, gamify it a little more and learn to monetize it. I’m a long way from getting there, but everyday I make an effort to learn Flutter I’m one day closer than before. 

I hope this helps inspire you to keep learning and go easy on yourself. Our little human minds need time to absorb new languages. Remember you’re on the right path, and app development is one of the most exciting areas to gain knowledge in. Go after it, just pace yourself. I’m only on module 2. Feel free to reach out to me by leaving a comment below or on instagram @kyleknob

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.teal,
        body: SafeArea(
          child: Container(
            height: 100.0,
              width: 100.0,
            margin: EdgeInsets.only(left:30),
            padding: EdgeInsets.all(20),
            child: Text('Goofy'),
            color: Colors.white
          ),
        ),
      ),
    );
  }
}