简体   繁体   English

无状态与有状态重建

[英]Stateless Vs Stateful rebuild

when a stateless widget is inside a stateful widget it will redraw or not?当无状态小部件位于有状态小部件内时,它是否会重绘? now the stateless widget can't be redrawn at run time but stateful can.现在无状态小部件不能在运行时重绘,但有状态的可以。 the question is when the stateless widget is inside a stateful widget it will be redrawn or not?问题是当无状态小部件位于有状态小部件内时,它是否会被重绘?

A statelessWidget which is a child of a statefulWidget will be rebuilt if the statefulWidget rebuilds.如果statefulWidget重建, statelessWidget将被重建,它是statefulWidgetchild级。 Basically, when setState is called in a statefulWidget , the old state is chucked away and the build method runs with the new state.基本上,当在statefulWidget中调用setState时,旧的 state 被丢弃,构建方法与新的 state 一起运行。 So if a statelessWidget it referenced in the statefulWidget 's build method, yes it will be rebuilt.因此,如果statelessWidgetstatefulWidgetbuild方法中引用,是的,它将被重建。

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> {
  @override
  Widget build(BuildContext context) {
    print('Stateful widget built');
    return Scaffold(
      appBar: AppBar(
        title: Text('Example'),
      ),
      body: BodyWidget(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {});
        },
        tooltip: 'Set state',
        child: Icon(Icons.add),
      ),
    );
  }
}

class BodyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print('Stateless widget built');
    return Container(
      child: Text('Stateless widget'),
    );
  }
}

Try this example out, when you hit the Fab, it re setState on the statefulWidget and you will get a print out in the console when each build method is run.试试这个例子,当你点击 Fab 时,它会在setState上重新设置statefulWidget ,当每个构建方法运行时,你会在控制台中打印出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM