Skip to content

[Flutter] Use StatefulWidget to change and re-render the page and components

When we started to learn to use Flutter for Application development, we occasionally wonder: Should we use StatefulWidget or StatelessWidget now?

In fact, the effects of the StatefulWidget and StatelessWidget are completely different.

  • StatelessWidget: After the page is created, it will not be changed.
  • StatefulWidget: The components on the page will interact with the user, and the component style may change.

Today I will record about the sample code we open the Android Studio IDE (Intellij IDEA: How to recover accidentally deleted files): Click button and add the number in the page's center. It is actually used StatefulWidget to change the page.

Like this

If you are interesting for Flutter learning, you can refer their official tutorial: https://flutter.dev/docs/reference/tutorials


StatefulWidget

I have deleted some unnecessary code, such as AppBar and name pass programs, so the sample program is relatively simple.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}



We define the entry point (main()) here. And we use StatelessWidget, so it will never change.

And then we define MyHomePage().

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}



Here we are going to use StatefulWidget. We use the "createState()" function to instantiate the page we will write next. After that, if we need to redraw the page, use the "setState()" function to redraw the page.

Next, we are finally going to make the main interface of our App: a "text showing the number of times the button has been clicked" and a "button".

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }



Output:

這張圖片的 alt 屬性值為空,它的檔案名稱為 01-6.png
This is what it looks like after 9 clicks.

Don't forget, we should use the _counter variable to store the number of clicks at the beginning. The variables with the bottom line "_" are all private variables.

Then we define a function _incrementCounter() to increase _counter and put it in the event triggered by clicking the button below.

In this way, our simple DEMO of "click the button to change the number in the center of the screen" is complete!


You can also change the component color

Next, let's change the component properties except for clicking the numbers, right?

Draw the gourd in the same way as the DEMO above, we will change the changed object to "Color" and assign the text in the screen.

import 'dart:math';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Color _color = Color.fromARGB(255, 0, 0, 200);

  void _colorChange() {
    setState(() {
      _color = Color.fromARGB(255, Random().nextInt(256), Random().nextInt(256), Random().nextInt(256));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
              style: TextStyle(color: _color),
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _colorChange,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}



Output:

Tags:

Leave a Reply