banner
RustyNail

RustyNail

coder. 【blog】https://rustynail.me 【nostr】wss://ts.relays.world/ wss://relays.world/nostr

Stateful widget in Flutter

Flutter's stateful widget#

In Flutter, widgets are divided into two types: stateless and stateful. However, they have one thing in common, which is that they are both immutable.

In StatelessWidget, the build method is overridden to return the interface, etc.

Demo#

A simple demo about StatefulWidget ----> Link

Preview#

preview

class MyApp extends StatelessWidget{

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'NoWay',
      home: new ContentWidget()
    );
  }
}

State#

Because widgets are immutable, if you want to dynamically change the interface, for example, if you need to update ListView after adding data, you need to use State to save and manipulate the state of the widget (StatefulWidget).


class ContentWidget extends StatefulWidget{

  @override
  State<StatefulWidget> createState() {
    return new ContentWidgetState();
  }
}

By overriding createState, you can obtain the State object of the widget.

class ContentWidgetState extends State<ContentWidget> {
  @override
  void initState() {
    
  }
  @override
  Widget build(BuildContext context) {
    return null;
  }
}

The view of StatefulWidget is described in the state.

More importantly, widget updates. For example, after clicking a button and adding data to the data of the listView, you need to update the view.


class StateA extends State<ContentWidget>{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      appBar: new AppBar(
        actions: [
          new IconButton(
            new Icon(Icons.add),
            onPressed: (){ addData() },
          )
        ]
      ),
    );
  }
	// add data to a list
  void addData() {
     setState(() {
        // do your job here 
    });
  }
}

In this case, you need to call setState( (){} ) to notify the interface to update.

It is best to call the interface update asynchronously, otherwise it seems to cause an error.

Future<String> fs =  Some places to get, such as files, networks, etc.;
fs.then((str){
  setState(() {
   // do your job here        
  });
});
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.