【问题标题】:Flutter setState not updating the widgetFlutter setState 不更新小部件
【发布时间】:2019-09-10 19:52:12
【问题描述】:

我是反应开发人员尝试颤振。

我有如下状态小部件

// progress_indicators: ^0.1.2
import 'package:progress_indicators/progress_indicators.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  var _isLoading = false;

  @override
  void initState() {
    super.initState();
    setState(() { _isLoading = false; });
  }

  @overide 
  Widget build(BuildContext context) {
    body: Container(
      child: Column(
        children: <Widget>[
          Form(),
          _isLoading ? JumpingDotsProgressIndicator(
              fontSize: 60.0,
           ): Padding(padding: EdgeInsets.only(top:0))
        ]
      )
    )
  }

  onLogin() async {
    final response = await loginUser(_userController.text.trim(), _passController.text.trim());
    setState(() { _isLoading = true; });
    if(response == true) {
      print("User Logging take them to activity");
    } else {
      setState(() { _isLoading = false; });
      bottomModel(response['message']);
    }
  }
}

JumpingDotsProgressIndicator 是来自progress_indicators 的方法,它为我提供了一个简单的加载程序。

我想在我的loginUser 方法发生时显示加载器。 loginUser 是我的 NodeJS 服务器的一个简单的 post req。

当单击位于Form() 中的按钮时,也会调用onLogin。 一切正常,但即使我正在设置状态,加载程序也没有显示。

条件渲染我做错了什么?

我还有一个问题

_isLoading ? JumpingDotsProgressIndicator(
  fontSize: 60.0,
): Padding(padding: EdgeInsets.only(top:0))

这里我给0 填充,它就像一个空小部件,所以我也尝试添加null 代替Padding(padding: EdgeInsets.only(top:0)),然后在模拟器中它显示Assertion failed

有人能解释一下原因吗?

感谢您的建议!

【问题讨论】:

  • 我不知道你在哪里调用 onLogin() 函数。它是一个按钮,您可以在 onPressed 上调用 onLogin() 尝试将 setState() 也添加到此被压迫对象中,而不是添加到 onLogin() 函数中
  • 回答您的第二个问题:您不能将 null 添加为小部件。我通常使用像Container()这样的空容器
  • @Neli 在表单内我有一个按钮,我有onPressed: onLogin

标签: flutter dart


【解决方案1】:

您好,请尝试从initState() 中删除setState(() { _isLoading = false; });,否则每次构建新小部件时,因为状态已更改,它会在您看到预期行为之前将_isLoading 设置为false。用你的代码简而言之,你的状态永远不会是真的。

【讨论】:

    猜你喜欢
    • 2020-08-18
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2021-05-01
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多