Wednesday, November 28, 2018

Flutter: Widgets , Stateless and Stateful



Almost every element of your Flutter app is a widget. Widgets are designed to be immutable, since using immutable widgets helps keep the app UI lightweight.

There are two fundamental types of widgets you will use:

    Stateless: widgets that depend only upon their own configuration info, such as a static image in an image view.
    Stateful: widgets that need to maintain dynamic information and do so by interacting with a State object.

Both stateless and stateful widgets redraw in Flutter apps on every frame, the difference being that the stateful widgets delegate their configuration to a State object.

To get started with making your own widgets, create a new class at the bottom of main.dart:

class GHFlutter extends StatefulWidget {
  @override
  createState() => new GHFlutterState();
}

We need to make a StatefulWidget subclass and then overre the createState() method to create its state object. Now add a GHFlutterState class above GHFlutter:

class GHFlutterState extends State {
}

Now we need to fill in the build method

@override
Widget build(BuildContext context) {
  return new Scaffold (
    appBar: new AppBar(
      title: new Text(Strings.appTitle),
    ),
    body: new Text(Strings.appTitle),
  );
}

A Scaffold is a container for material design widgets. It acts as the root of a widget hierarchy. You’ve added an AppBar and a body to the scaffold, and each contains a Text widget.


To use the stateless widget, it should be given the state for the home.

class GHFlutterApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: Strings.appTitle,
      home: new GHFlutter(),
    );
  }
}


No comments:

Post a Comment