【问题标题】:Flutter FutureBuilder show Progress indicatorFlutter FutureBuilder 显示进度指示器
【发布时间】:2020-02-10 07:38:28
【问题描述】:

我有一个按钮,它在按下时会在 DB 中插入一些东西并将用户重定向到另一个页面。我正在尝试实现 FutureBuilder,它应该显示CircularProgressIndicator,直到一切都完成。

这是我的功能:

Future<bool> insertPhoneNumber(String phoneNumber) async {
    String token = await getToken();

    if (token.isNotEmpty) {
      var body = jsonEncode({'token': token, 'userID': user.getUserID(), 'phoneNumber': phoneNumber});

      print(body.toString());

      var res = await http.post((baseUrl + "/insertPhoneNumber/" + user.getUserID()),
          body: body,
          headers: {
            "Accept": "application/json",
            "content-type": "application/json"
          });

      if (res.statusCode == 200) {
        print("Insert Phone Number is OK");
        notifyListeners();
        return true;
      } else {
        print("Insert Phone Number not OK");
        notifyListeners();
        return false;
      }
    } else {
      print("Insert Phone Number failed due to unexisting token");
    }
  }

这是一个触发数据库交互的按钮:

RaisedButton(
                  color: Color.fromRGBO(105, 79, 150, 1),
                  onPressed: () {
                    var user = Provider.of<UserRepository>(context);
                    String completePhoneNumber = _selectedDialogCountry.phoneCode + phoneNumberController.text;
                    FutureBuilder(
                      future: user.insertPhoneNumber(completePhoneNumber),
                      builder: (BuildContext context, AsyncSnapshot snapshot) {
                        if (snapshot.connectionState != ConnectionState.done) {
                          return CircularProgressIndicator(
                              backgroundColor: Colors.blue);
                        } else {
                          return Dashboard();
                        }
                      },
                    );
                  },
                  textColor: Colors.white,
                  child: Text("SAVE"),
                )

它更新了数据库,但没有其他任何事情发生。没有进度指示器,也没有重定向到Dashboard

编辑

这是我的完整构建方法:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          padding: EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              AutoSizeText(
                'What is your phone number?',
                style: TextStyle(fontSize: 30),
                maxLines: 1,
              ),
              Row(
                children: <Widget>[
                  SizedBox(
                    width: 9.0,
                    child: Icon(Icons.arrow_downward),
                  ),
                  SizedBox(width: 8.0),
                  SizedBox(
                      width: 120.0,
                      height: 65.0,
                      child: Card(
                        child: ListTile(
                          onTap: _openCountryPickerDialog,
                          title: _buildDialogItem(_selectedDialogCountry),
                        ),
                      )),
                  Expanded(
                    child: TextField(
                        autofocus: true,
                        keyboardType: TextInputType.number,
                        decoration:
                            InputDecoration(border: OutlineInputBorder())),
                  ),
                ],
              ),
              SizedBox(
                width: 100,
                child: RaisedButton(
                  color: Color.fromRGBO(105, 79, 150, 1),
                  onPressed: () {
                    print("Test");
                  },
                  textColor: Colors.white,
                  child: Text("SAVE"),
                ),
              )
            ],
          )),
    );
  }

【问题讨论】:

  • 你能展示你提到的 RaisedButton() 定义的完整类吗?您是否尝试在 AsyncSnapshot 上使用 hasError() 来解决异步函数可能出现的问题?
  • 我已经编辑了我的问题并发布了完整的build 方法。这是简单的类PhoneNumberbuildPhoneNumberState 类中。
  • 嗨。你找到解决办法了吗?我也有类似的问题。

标签: asynchronous flutter dart


【解决方案1】:

它不起作用,因为FutureBuilder 未附加到小部件树。 一旦未来不处于完成状态,它只是创建一个实例Dashboard。你不应该在这里使用FutureBuilder,而是你可以根据一些变量设置子小部件,当未来完成时,你调用@987654324 @ 在那个变量上更新状态,然后用新的状态值重建小部件

类似的东西

var isLoading = false;

void insertNumber(){
 var user = Provider.of<UserRepository>(context);
 String completePhoneNumber = _selectedDialogCountry.phoneCode + phoneNumberController.text;
 setState(() => isLoading=true);
 user.insertPhoneNumber(completePhoneNumber).then((result){
  setState(() => isLoading=false);
 })
}

Widget build(BuildContext context){
 return RaisedButton(
                  color: Color.fromRGBO(105, 79, 150, 1),
                  onPressed: () {
                    var user = Provider.of<UserRepository>(context);
                    String completePhoneNumber = _selectedDialogCountry.phoneCode + phoneNumberController.text;
                    FutureBuilder(
                      future: user.insertPhoneNumber(completePhoneNumber),
                      builder: (BuildContext context, AsyncSnapshot snapshot) {
                        if (snapshot.connectionState != ConnectionState.done) {
                          return CircularProgressIndicator(
                              backgroundColor: Colors.blue);
                        } else {
                          return Dashboard();
                        }
                      },
                    );
                  },
                  textColor: Colors.white,
                  child: isLoading? CircularProgressIndicator(): Text("Save"),
                );
}

对于您的用例,您将需要两个以上的状态来实现您正在寻找的 UI。例如 DEFAULT,LOADING,ERROR,SUCCESS

【讨论】:

  • 为什么他的代码没有附加到小部件树上。你不能从他的代码示例中看到 RaisedButton 是否在 build() 方法中,可以吗?
  • 由于FutureBuilderWidget,它应该是某个父级Widget 上的一个子级,以便成为小部件树的一部分。这里您只是创建FutureBuilder 的一个实例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 2011-09-29
  • 2021-02-15
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多