gpt4 book ai didi

flutter - 在等待 API 响应时显示加载指示器

转载 作者:行者123 更新时间:2023-12-03 13:30:50 27 4
gpt4 key购买 nike

所以我有一个注册页面并且注册功能运行良好。
现在我所需要的只是按下“注册”按钮后的加载指示器。
我已经混合了所有我能想到的关键词在谷歌中搜索,我已经尝试了所有但没有任何效果。

以下是我尝试过的事情:

使用 FutureBuilder :

RaisedButton(
onPressed: () async {
FutureBuilder<http.Response>(
future: registerUser(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text("SUCCESS");
}
if (snapshot.hasError) {
return Text("ERROR");
}
return new Center(
child: new CircularProgressIndicator());
},
);
},
color: Color(colorPrimary),
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0)),
child: Text("SignUp"),
)

在这个方法中,方法被调用,但指标没有显示

使用图书馆 progress_hud :
这个我认为是有效的,但即使我把它放在 Center 中小部件,
它仍然会到达屏幕底部,显示 overlapping with pixels错误。

还有其他更好的解决方案吗?或者我应该找到一种方法来解决这个重叠的错误?

谢谢你的帮助!

最佳答案

请使用包 modal_progress_hud https://pub.dev/packages/modal_progress_hud
ModalProgressHUD 必须作为第一个 child 在脚手架主体下
我的工作代码片段

 @override
Widget build(BuildContext context) {
return Scaffold(
body: ModalProgressHUD(
inAsyncCall: _isLoading,
child: SingleChildScrollView(
child: Container(
...

完整示例代码
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LoginPage(
onSignIn: () => print('login successful!'),
),
);
}
}

class LoginPage extends StatefulWidget {
final VoidCallback _onSignIn;

LoginPage({@required onSignIn})
: assert(onSignIn != null),
_onSignIn = onSignIn;

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

class _LoginPageState extends State<LoginPage> {
// maintains validators and state of form fields
final GlobalKey<FormState> _loginFormKey = GlobalKey<FormState>();

// manage state of modal progress HUD widget
bool _isInAsyncCall = false;

bool _isInvalidAsyncUser = false; // managed after response from server
bool _isInvalidAsyncPass = false; // managed after response from server

String _username;
String _password;
bool _isLoggedIn = false;

// validate user name
String _validateUserName(String userName) {
if (userName.length < 8) {
return 'Username must be at least 8 characters';
}

if (_isInvalidAsyncUser) {
// disable message until after next async call
_isInvalidAsyncUser = false;
return 'Incorrect user name';
}

return null;
}

// validate password
String _validatePassword(String password) {
if (password.length < 8) {
return 'Password must be at least 8 characters';
}

if (_isInvalidAsyncPass) {
// disable message until after next async call
_isInvalidAsyncPass = false;
return 'Incorrect password';
}

return null;
}

void _submit() {
if (_loginFormKey.currentState.validate()) {
_loginFormKey.currentState.save();

// dismiss keyboard during async call
FocusScope.of(context).requestFocus(new FocusNode());

// start the modal progress HUD
setState(() {
_isInAsyncCall = true;
});

// Simulate a service call
Future.delayed(Duration(seconds: 1), () {
final _accountUsername = 'username1';
final _accountPassword = 'password1';
setState(() {
if (_username == _accountUsername) {
_isInvalidAsyncUser = false;
if (_password == _accountPassword) {
// username and password are correct
_isInvalidAsyncPass = false;
_isLoggedIn = true;
} else
// username is correct, but password is incorrect
_isInvalidAsyncPass = true;
} else {
// incorrect username and have not checked password result
_isInvalidAsyncUser = true;
// no such user, so no need to trigger async password validator
_isInvalidAsyncPass = false;
}
// stop the modal progress HUD
_isInAsyncCall = false;
});
if (_isLoggedIn)
// do something
widget._onSignIn();
});
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Modal Progress HUD Demo'),
backgroundColor: Colors.blue,
),
// display modal progress HUD (heads-up display, or indicator)
// when in async call
body: ModalProgressHUD(
child: SingleChildScrollView(
child: Container(
padding: const EdgeInsets.all(16.0),
child: buildLoginForm(context),
),
),
inAsyncCall: _isInAsyncCall,
// demo of some additional parameters
opacity: 0.5,
progressIndicator: CircularProgressIndicator(),
),
);
}

Widget buildLoginForm(BuildContext context) {
final TextTheme textTheme = Theme.of(context).textTheme;
// run the validators on reload to process async results
_loginFormKey.currentState?.validate();
return Form(
key: this._loginFormKey,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
key: Key('username'),
decoration: InputDecoration(
hintText: 'enter username', labelText: 'User Name'),
style: TextStyle(fontSize: 20.0, color: textTheme.button.color),
validator: _validateUserName,
onSaved: (value) => _username = value,
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
key: Key('password'),
obscureText: true,
decoration: InputDecoration(
hintText: 'enter password', labelText: 'Password'),
style: TextStyle(fontSize: 20.0, color: textTheme.button.color),
validator: _validatePassword,
onSaved: (value) => _password = value,
),
),
Padding(
padding: const EdgeInsets.all(32.0),
child: RaisedButton(
onPressed: _submit,
child: Text('Login'),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: _isLoggedIn
? Text(
'Login successful!',
key: Key('loggedIn'),
style: TextStyle(fontSize: 20.0),
)
: Text(
'Not logged in',
key: Key('notLoggedIn'),
style: TextStyle(fontSize: 20.0),
),
),
],
),
);
}
}

enter image description here

关于flutter - 在等待 API 响应时显示加载指示器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58093029/

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