Home > Mobile >  I have confusion about Dart code in Flutter Framework
I have confusion about Dart code in Flutter Framework

Time:01-02

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My First App'),
        ),
        body: Text('This is my default text'),
      ),
    );
  }
}

I have recently started learning the Flutter framework , and it's hell lot on confusing for me , can u please explain the sections of this code above like , what is that BuildContext , the MaterialApp (is it a contructor or a class, ? ), and it's parameters , I tried learning from their docs , but their is just too much its confusing to me , all i know from this code written in this class is that , build method returns a widget , and scaffold is some sort of predefined code which helps with the layout , something like bootstrap helps with CSS

CodePudding user response:

Let's look at it one line at a time.

class MyApp extends StatelessWidget {

In this line you are declaring a class MyApp which extends the Stateless widget class. That means that MyApp will have the functionality of a Stateless widget and the bits of code that you are adding to it.

  Widget build(BuildContext context) {

Here you are defining the build method. A Widget needs a build method, that's how flutter knows how to build the widget and show it. The build method receives a BuildContext parameter which is a handle to the location of a widget in the widget tree.

    return MaterialApp(

The build method returns a MaterialApp widget. In fact, MaterialApp() is the constructor of the MaterialApp widget.

      home: Scaffold(
        appBar: AppBar(
          title: Text('My First App'),
        ),
        body: Text('This is my default text'),

The constructor of MaterialApp has a home and a body parameter. Here you are passing a Scaffold widget to the Home parameter. The Scaffold widget constructor (Scaffold()) has an appBar parameter, that receives a Widget (in this case, the Widget is AppBar). And the AppBar constructor has a title parameter, which receives a Text widget. And the body parameter also receives a Text widget.

      ),
    );
  }
}

CodePudding user response:

Very often, starting to learn new languages and frameworks, we have questions that we cannot answer. This is fine. But what is not fine is not reading the documentation. Flutter has really good documentation, by contacting her you can very quickly answer all your questions. Start with this and good luck on your way.

https://docs.flutter.dev/get-started/codelab

  • Related