Skip to main content

Flutter: Using Scaffold

 

It often makes sense to abstract embedded code as its own widget.

Here it will take the code previously assigned to the home parameter and put it in its own class extended StatelessWidget. Since home expects us to pass it a Widget then we can use an instance of that class.

Before

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Home')
        ),
        body: Text('Body'),
        ),
      );
  }
}

After

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
        );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text('Home')
      ),
      body: Text('Body'),
    );
  }
}

 

The Scaffold class has these optional named properties, and we can use these to construct the layout of our app.

const Scaffold(
{Key key,
PreferredSizeWidget appBar,
Widget body,
Widget floatingActionButton,
FloatingActionButtonLocation floatingActionButtonLocation,
FloatingActionButtonAnimator floatingActionButtonAnimator,
List<Widget> persistentFooterButtons,
Widget drawer,
Widget endDrawer,
Widget bottomNavigationBar,
Widget bottomSheet,
Color backgroundColor,
bool resizeToAvoidBottomPadding,
bool resizeToAvoidBottomInset,
bool primary: true,
DragStartBehavior drawerDragStartBehavior: DragStartBehavior.start,
bool extendBody: false,
bool extendBodyBehindAppBar: false,
Color drawerScrimColor,
double drawerEdgeDragWidth,
bool drawerEnableOpenDragGesture: true,
bool endDrawerEnableOpenDragGesture: true}
)

For example, we can change the background color of app by adding the named parameter backgroundColor and a value of type Color to our code.

This will apply a gray background to the scaffold.

Flutter Scaffold Change Background


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

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
        );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(
          title: Text('Home')
      ),
      body: Text('Body'),
    );
  }
}