Tag: flutter widgets

  • Flutter Add Image

    Flutter is an open source framework by Google for building beautiful, natively compiled, multi-platform applications from a single code base. Flutter allows you to build apps for mobile, web, dekstop, and embedded devices – all from a single codebase.

    Referring to the official documentation we can easily add image in a flutter app using the following syntax. 

    Image.asset('image_name')

    Steps – Flutter Add Image

    1. Create a new folder in the root of your flutter proejct. We’ll create assets folder and then will create images folder. In this way, we can later create other folders like fonts in our assets folder.
    Flutter Create Assets/Images Folder
    1.  Copy your desired image in the newly created images folder.
    2. pubspec.yaml is an important file located at the root of the project which is  used to identify the assets used in an app. We have to manipulate this file to use images in a flutter app.
      # To add assets to your application, add an assets section, like this:
       assets:
         - assets/images/flutter.png

    Note: Please take care of indentation.

    • [2 white spaces before assets:]
    • [4 white spaces before – assets/images/flutter.png]

    Also, If you want to use more than one image then don’t write image name after folder name.

    1. Insert flutter add image code in your app.
    Image.asset("assets/images/flutter.png"),

    Code

    import 'package:flutter/material.dart';
    
    void main() => runApp(
          MaterialApp(
            home: Scaffold(
              appBar: AppBar(title: const Text("Flutter Add Image")),
              body: Center(
                child: Image.asset("assets/images/flutter.png"),
              ),
            ),
          ),
        );

    Output

    Output Flutter Add Image

    Add Image from Internet

    To add image from the internet or network we need to use Image.network instead of Image.asset and pass the image URL in the parameter. (Official Documentation)

    Image.network("https://picsum.photos/250?image=9"),

    Happy coding!

  • Minimal Flutter App

    Minimal Flutter app is the simplest possible app that calls the runApp( ) function with a widget.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(
        const Center(
          child: Text(
            "Minimal Flutter App.",
            textDirection: TextDirection.ltr,
          ),
        ),
      );
    }
    

    In the main function, we are calling runApp( ) function where we are passing two widgets directly irrespective of Stateless or Stateful behavior. We have wrapped the Text( ) widget in Center Widget. In other words, the Center( ) widget has only one child that is a Text( ) widget. This widget takes up the whole screen and we need to provide the text direction as we are not using MaterialApp() widget at the moment.
    Tip: Remember everything in Flutter is a widget.

    Output

    Minimal Flutter App – Output
  • Flutter StatefulWidget

    State is data/information used by your App or widgets in our App. State can be things like username or in our case, index of the question we want to show.

    App State can be Authenticated Users

    Widget State can be Current User Input or which question is currently selected.

    StatefulWidget has some internal state which is the core about this widget.

    We’ll inherit/extend MyApp class from StatefulWidget instead of StatelessWidget and will override createState() method. Then we’ll create another class that will hold all the previous code.

    class MyAppState extends State<MyApp>
    and in answerQuestion() function we have now used setState() function that takes an anonymous function where we increment questionIndex variable. Here is the complete code snippet.

     

    //File Name: main.dart
    import 'package:flutter/material.dart';
    
    /*
    * The arrow function allows us to create a simplified function consisting of a single expression.
    * We can omit the curly brackets and the return keyword
    */
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatefulWidget {
      /*
       * createState() is a method that takes no arguments but returns a State object
       * which is connected to a StatefulWidget
       */
      @override
      State<StatefulWidget> createState() {
        return MyAppState();
      } //createState()
    } //StatefulWidget
    
    class MyAppState extends State<MyApp>{
      var questionIndex = 0;
    
      void answerQuestion() {
        setState( () {
          questionIndex++;
        } );
        print(questionIndex);
      }
    
      @override
      Widget build(BuildContext context) {
        var questions = [
          'What\'s your favorite color?',
          'What\'s your favorite animal?'
        ];
        return MaterialApp(
          /*
          * A Scaffold Widget provides a framework which implements the basic material design visual
          * layout structure of the flutter app.
           */
          home: Scaffold(
            appBar: AppBar(
              title: Text('First Flutter App'),
            ),
            body: Column(
              children: <Widget>[
                Text(questions[questionIndex]),
                ElevatedButton(
                  child: Text('Answer1'),
                  //onPressed takes a function
                  onPressed: answerQuestion,
                ),
                ElevatedButton(
                  child: Text('Answer2'),
                  onPressed: () => print('Answer2 chosen!'),
                ),
                ElevatedButton(
                  child: Text('Answer3'),
                  onPressed: () {
                    //...multiline function body
                    print('Answer3 chosen');
                  },
                ), //ElevatedButton()
              ], //<Widget>[]
            ), //Column()
          ), //Scaffold()
        ); //MaterialApp()
      } //build()
    } //MyApp()
    

     

    What Flutter actually does when setState() is executed?

    setState() is a function that forces Flutter to re-render user interface, however not the entire user interface but instead part of it that requires updations, question text in our case. setState() updates the widget by calling its build method again.

    StatefulWidget Output

    Pressing the Answer1 button will now change the question, thus we are maintaining the state which in this case is the questionIndex of questions list.

    Output Second Question

    If we press Answer1 button second time, we’ll get an error and our app will crash because our questions list contains only two list items. We’ll solve this problem somewhere later. 

    Output App Crashed

    At the moment the point of this blog post was to break the ice to understand the concept of Flutter StatefulWidget.
    If you have any question, please ask in the comments section.

    Happy Coding!

  • Different Types of Flutter Widgets

    Container Widget: There is also a very important widget that ships with Flutter, the Container() widget which kind of belongs in to both categories as you will learn once we use it because it by default is invisible but you can also give it some styling so that you can see it.

    Visible & Invisible Flutter Widgets
    Visible & Invisible Flutter Widgets

    Container Widget: There is also a very important widget that ships with Flutter, the Container() widget which kind of belongs in to both categories as you will learn once we use it because it by default is invisible but you can also give it some styling so that you can see it.