iT邦幫忙

0

Flutter 04

  • Stateless Widgets & Hot Reload
    Whenever we make some changes, we need to click hot restart to show the changes on the preview screen. Flutter comes with something called ‘Hot Reload’, that whenever we make changes, result will some on the preview screen immediately.

In order to use Hot Reload, we need to create a stateless widget class on our own. Type ‘stless’ at the bottom of our code and this will show:

class test extends Stateless Widget{
@override
Widget build(BuildContext context){
   return container();
}
} 

Just like the classes we use before (AppBar, Body etc.), what we’re making is our own widget class, that is extending the base StatelessWidget class in flutter application.

  • Stateless Widgets
    The state of widget cannot change over time.
    The layout, the colors or any data we use inside that widget has to be final when we initialize it.
  • Stateful Widgets
    The state of the widget can change over time.
    For example, some kind of counting widget that display the number of files on an app, which is changing all over the time.

In the class we just create, there’s a ‘build’ function in it, where the return type is a Widget it returns a Container widget. Instead of returning only one widget, we want to return a whole widget tree we created at the start. Thus, we copy the Scaffold widget above, which multiple widget nested in it, into the return data.

import 'package:flutter/material.dart';

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

class home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold( //ROOT WIDGET
      appBar: AppBar(
        title: Text(
          'CodeForces',
          style: TextStyle(
            fontSize: 25.0,
            letterSpacing: 2.0,
            color: Colors.white,
            fontFamily: 'BebasNeue',
          ),
        ), //SET THE TITLE TEXT
        centerTitle: true,    //SET THE PROPERTIES, WHERE THE TEXT SHOWED AT THE CENTRE
        backgroundColor: Colors.red,
      ),
      body: Center( //LOCATED IN THE MIDDLE
        child: Text(
            'Hello Programmers!',
            style: TextStyle(
              fontSize : 30.0,
              fontWeight: FontWeight.bold,
              letterSpacing: 2.0,
              color: Colors.grey[850],
              fontFamily: 'BebasNeue',
            )
        ),
      ),
      floatingActionButton: FloatingActionButton( //CREATE A FLOATING BUTTON
        child: Text('click'),
        backgroundColor: Colors.red[600],
      ),
    );
  }
}

Now when we change the code, the build function will detect it to rerun, now when ut rerun flutter will update the review screen.

The @Override in the StatelessWidget is used says that the build function will override the one defined in the classes ancestors. We’re redefining the initialize class.

Flutter Tutorial for Beginners #7 - Stateless Widgets & Hot Reload


尚未有邦友留言

立即登入留言