gpt4 book ai didi

dart - 使用 MaterialApp 路由在屏幕旋转时调用 Widget 的 didUpdateWidget 方法

转载 作者:IT王子 更新时间:2023-10-29 07:23:16 24 4
gpt4 key购买 nike

当我在 MaterialApp 中使用 routes 时,每当我旋转屏幕/打开键盘等

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
routes: {
'/': (_) => MyHomePage(title: 'Flutter Demo Home Page'),
},
initialRoute: '/',
);
}
}

另一方面,当我使用home参数时,旋转屏幕/打开键盘时不会调用didUpdateWidget

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

我遇到的问题是我正在使用 Bloc pattern sample作为指南,因此每当调用 didUpdateWidget 时,我的 Bloc 就会被处理并重新创建。这意味着我失去了我在 Bloc 中的所有应用程序状态,例如选择了什么。

@override
void didUpdateWidget(ProductSquare oldWidget) {
super.didUpdateWidget(oldWidget);
_disposeBloc();
_createBloc();
}

为什么使用 routeshome 的行为会有所不同?我怎样才能使 routes 表现得像 home 并且在屏幕旋转时不调用 didUpdateWidget 从而不会不必要地重新创建 bloc?

没有 Bloc 的完整应用示例,每当我旋转屏幕时都会重建。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
routes: {
'/': (_) => MyHomePage(title: 'Flutter Demo Home Page'),
},
initialRoute: '/',
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

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

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

@override
void didUpdateWidget(MyHomePage oldWidget) {
super.didUpdateWidget(oldWidget);

print('didUpdateWidget');
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
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),
),
);
}
}

最佳答案

The issue I have is that I am using the Bloc pattern sample as a guide so my Bloc is disposed and recreated whenever the didUpdateWidget is called. This means I lose all my app's state that is in the Bloc, e.g. what is selected.

这就是问题所在。不要那样做,这是反模式。

您制作的任何小部件都应牢记,理论上它们可以更新数千次而不会发生任何变化。您应该在执行副作用之前验证某些内容已更改。

因此,您的 didUpdateWidget 应该如下所示:

@override
void didUpdateWidget(ProductSquare oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.product != oldWidget.product) {
_disposeBloc();
_createBloc();
}
}

关于dart - 使用 MaterialApp 路由在屏幕旋转时调用 Widget 的 didUpdateWidget 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54451380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com