Flutter StatefulWidget层次结构

时间:2018-09-09 22:39:36

标签: flutter

我想象这是设计使然,但是当从StatefulWidget导航到新页面时,原始页面是在渲染第二个页面时重建的。这是来自https://flutter.io/cookbook/navigation/navigation-basics/的示例代码,我刚刚添加了print语句来显示活动并将第一页转换为有状态。

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: 'Navigation Basics',
    home: FirstScreen(),
  ));
}

class FirstScreen extends StatefulWidget {
  @override
  FirstScreenState createState() {
    return new FirstScreenState();
  }
}

class FirstScreenState extends State<FirstScreen> {
  @override
  Widget build(BuildContext context) {
    print('Building Screen 1');
    return Scaffold(
      appBar: AppBar(
        title: Text('First Screen'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Launch screen'),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SecondScreen()),
            );
          },
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext   context) {
    print('Building Screen 2');
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Screen"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Go back!'),
        ),
      ),
    );
  }
}

此输出显示在呈现第二页时,第一页也会被重建:

I/flutter (20929): Building Screen 2
I/flutter (20929): Building Screen 1

我有一个这种情况的实例,其中屏幕1使用FutureBuilder。我不想每次重新构建Screen 2时都重新加载所有数据。不禁觉得我缺少一些基本的东西,因为这似乎是不合逻辑的。

0 个答案:

没有答案