我是新手,他想知道什么是更好的方式来添加CircularProgressIndicator我的布局.例如,我的登录视图.此视图具有用户名,密码和登录按钮.我确实想要创建一个叠加布局(带Opacity),在加载时,显示我在NativeScript中使用的进度指示器,但我对如何操作感到困惑,如果这是更好的方法.例如,在NativeScript中,我在主布局中添加IndicatorActivity并将busy设置为true或false,因此它在加载时覆盖所有视图组件.
编辑:
我能够达到这个结果:
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _loading = false;
void _onLoading() {
setState(() {
_loading = true;
new Future.delayed(new Duration(seconds: 3), _login);
});
}
Future _login() async{
setState((){
_loading = false;
});
}
@override
Widget build(BuildContext context) {
var body = new Column(
children: <Widget>[
new Container(
height: 40.0,
padding: const EdgeInsets.all(10.0),
margin: const EdgeInsets.fromLTRB(15.0, 150.0, 15.0, 0.0),
decoration: new BoxDecoration(
color: Colors.white,
),
child: new TextField(
decoration: new InputDecoration.collapsed(hintText: "username"),
),
),
new Container(
height: 40.0,
padding: const EdgeInsets.all(10.0),
margin: const EdgeInsets.all(15.0),
decoration: new BoxDecoration(
color: Colors.white,
),
child: new TextField(
decoration: new InputDecoration.collapsed(hintText: "password"),
),
),
],
);
var bodyProgress = new Container(
child: new Stack(
children: <Widget>[
body,
new Container(
alignment: AlignmentDirectional.center,
decoration: new BoxDecoration(
color: Colors.white70,
),
child: new Container(
decoration: new BoxDecoration(
color: Colors.blue[200],
borderRadius: new BorderRadius.circular(10.0)
),
width: 300.0,
height: 200.0,
alignment: AlignmentDirectional.center,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Center(
child: new SizedBox(
height: 50.0,
width: 50.0,
child: new CircularProgressIndicator(
value: null,
strokeWidth: 7.0,
),
),
),
new Container(
margin: const EdgeInsets.only(top: 25.0),
child: new Center(
child: new Text(
"loading.. wait...",
style: new TextStyle(
color: Colors.white
),
),
),
),
],
),
),
),
],
),
);
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Container(
decoration: new BoxDecoration(
color: Colors.blue[200]
),
child: _loading ? bodyProgress : body
),
floatingActionButton: new FloatingActionButton(
onPressed: _onLoading,
tooltip: 'Loading',
child: new Icon(Icons.check),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)

我仍然在适应国家的想法.使用颤动时,此代码是否在预期范围内?
谢谢!
Rém*_*let 41
在颤动中,有几种方法可以处理异步操作.
一种懒惰的方式可以使用模态.这将阻止用户输入,从而防止任何不必要的操作.这需要对代码进行很少的更改.只需将您修改_onLoading为以下内容:
void _onLoading() {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return Dialog(
child: new Row(
mainAxisSize: MainAxisSize.min,
children: [
new CircularProgressIndicator(),
new Text("Loading"),
],
),
);
},
);
new Future.delayed(new Duration(seconds: 3), () {
Navigator.pop(context); //pop dialog
_login();
});
}
Run Code Online (Sandbox Code Playgroud)
最理想的方法是使用FutureBuilder和有状态的小部件.这是你开始的.诀窍在于boolean loading = false,您可以直接使用a ,而不是在您的州Future<MyUser> user
然后将其作为参数传递给它FutureBuilder,它将为您提供一些信息,例如"hasData"或MyUser完成时的实例.
这将导致类似这样的事情:
@immutable
class MyUser {
final String name;
MyUser(this.name);
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<MyUser> user;
void _logIn() {
setState(() {
user = new Future.delayed(const Duration(seconds: 3), () {
return new MyUser("Toto");
});
});
}
Widget _buildForm(AsyncSnapshot<MyUser> snapshot) {
var floatBtn = new RaisedButton(
onPressed:
snapshot.connectionState == ConnectionState.none ? _logIn : null,
child: new Icon(Icons.save),
);
var action =
snapshot.connectionState != ConnectionState.none && !snapshot.hasData
? new Stack(
alignment: FractionalOffset.center,
children: <Widget>[
floatBtn,
new CircularProgressIndicator(
backgroundColor: Colors.red,
),
],
)
: floatBtn;
return new ListView(
padding: const EdgeInsets.all(15.0),
children: <Widget>[
new ListTile(
title: new TextField(),
),
new ListTile(
title: new TextField(obscureText: true),
),
new Center(child: action)
],
);
}
@override
Widget build(BuildContext context) {
return new FutureBuilder(
future: user,
builder: (context, AsyncSnapshot<MyUser> snapshot) {
if (snapshot.hasData) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Hello ${snapshot.data.name}"),
),
);
} else {
return new Scaffold(
appBar: new AppBar(
title: new Text("Connection"),
),
body: _buildForm(snapshot),
);
}
},
);
}
}
Run Code Online (Sandbox Code Playgroud)
Ham*_*tah 25
第 1 步:创建对话框
showAlertDialog(BuildContext context){
AlertDialog alert=AlertDialog(
content: new Row(
children: [
CircularProgressIndicator(),
Container(margin: EdgeInsets.only(left: 5),child:Text("Loading" )),
],),
);
showDialog(barrierDismissible: false,
context:context,
builder:(BuildContext context){
return alert;
},
);
}
Run Code Online (Sandbox Code Playgroud)
第 2 步:调用它
showAlertDialog(context);
await firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
Navigator.pop(context);
Run Code Online (Sandbox Code Playgroud)
使用对话框和登录表单的示例
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class DynamicLayout extends StatefulWidget{
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return new MyWidget();
}
}
showAlertDialog(BuildContext context){
AlertDialog alert=AlertDialog(
content: new Row(
children: [
CircularProgressIndicator(),
Container(margin: EdgeInsets.only(left: 5),child:Text("Loading" )),
],),
);
showDialog(barrierDismissible: false,
context:context,
builder:(BuildContext context){
return alert;
},
);
}
class MyWidget extends State<DynamicLayout>{
Color color = Colors.indigoAccent;
String title='app';
GlobalKey<FormState> globalKey=GlobalKey<FormState>();
String email,password;
login() async{
var currentState= globalKey.currentState;
if(currentState.validate()){
currentState.save();
FirebaseAuth firebaseAuth=FirebaseAuth.instance;
try {
showAlertDialog(context);
AuthResult authResult=await firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
FirebaseUser user=authResult.user;
Navigator.pop(context);
}catch(e){
print(e);
}
}else{
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar:AppBar(
title: Text("$title"),
) ,
body: Container(child: Form(
key: globalKey,
child: Container(
padding: EdgeInsets.all(10),
child: Column(children: <Widget>[
TextFormField(decoration: InputDecoration(icon: Icon(Icons.email),labelText: 'Email'),
// ignore: missing_return
validator:(val){
if(val.isEmpty)
return 'Please Enter Your Email';
},
onSaved:(val){
email=val;
},
),
TextFormField(decoration: InputDecoration(icon: Icon(Icons.lock),labelText: 'Password'),
obscureText: true,
// ignore: missing_return
validator:(val){
if(val.isEmpty)
return 'Please Enter Your Password';
},
onSaved:(val){
password=val;
},
),
RaisedButton(color: Colors.lightBlue,textColor: Colors.white,child: Text('Login'),
onPressed:login),
],)
,),)
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
azi*_*iza 24
对我来说,这样做的一个简洁方法是SnackBar在签名过程中显示底部,这是我的意思的一个例子:
以下是如何设置SnackBar.
为您定义全局密钥 Scaffold
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
Run Code Online (Sandbox Code Playgroud)
将其添加到您的Scaffold key属性中
return new Scaffold(
key: _scaffoldKey,
.......
Run Code Online (Sandbox Code Playgroud)
我的SignIn按钮onPressed回调:
onPressed: () {
_scaffoldKey.currentState.showSnackBar(
new SnackBar(duration: new Duration(seconds: 4), content:
new Row(
children: <Widget>[
new CircularProgressIndicator(),
new Text(" Signing-In...")
],
),
));
_handleSignIn()
.whenComplete(() =>
Navigator.of(context).pushNamed("/Home")
);
}
Run Code Online (Sandbox Code Playgroud)
这实际上取决于你想要如何构建你的布局,我不确定你的想法.
编辑
你可能想要这样,我用Stack来实现这个结果,只是显示或隐藏我的指标 onPressed
class TestSignInView extends StatefulWidget {
@override
_TestSignInViewState createState() => new _TestSignInViewState();
}
class _TestSignInViewState extends State<TestSignInView> {
bool _load = false;
@override
Widget build(BuildContext context) {
Widget loadingIndicator =_load? new Container(
color: Colors.grey[300],
width: 70.0,
height: 70.0,
child: new Padding(padding: const EdgeInsets.all(5.0),child: new Center(child: new CircularProgressIndicator())),
):new Container();
return new Scaffold(
backgroundColor: Colors.white,
body: new Stack(children: <Widget>[new Padding(
padding: const EdgeInsets.symmetric(vertical: 50.0, horizontal: 20.0),
child: new ListView(
children: <Widget>[
new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center
,children: <Widget>[
new TextField(),
new TextField(),
new FlatButton(color:Colors.blue,child: new Text('Sign In'),
onPressed: () {
setState((){
_load=true;
});
//Navigator.of(context).push(new MaterialPageRoute(builder: (_)=>new HomeTest()));
}
),
],),],
),),
new Align(child: loadingIndicator,alignment: FractionalOffset.center,),
],));
}
}
Run Code Online (Sandbox Code Playgroud)
Shy*_*hil 18
1.没有插件
class IndiSampleState extends State<ProgHudPage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Demo'),
),
body: Center(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async {
showDialog(
context: context,
builder: (BuildContext context) {
return Center(child: CircularProgressIndicator(),);
});
await loginAction();
Navigator.pop(context);
},
),
));
}
Future<bool> loginAction() async {
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
2.带插件
检查这个插件progress_hud
在pubspec.yaml文件中添加依赖项
dev_dependencies:
progress_hud:
Run Code Online (Sandbox Code Playgroud)
导入包
import 'package:progress_hud/progress_hud.dart';
Run Code Online (Sandbox Code Playgroud)
下面给出示例代码以显示和隐藏指标
class ProgHudPage extends StatefulWidget {
@override
_ProgHudPageState createState() => _ProgHudPageState();
}
class _ProgHudPageState extends State<ProgHudPage> {
ProgressHUD _progressHUD;
@override
void initState() {
_progressHUD = new ProgressHUD(
backgroundColor: Colors.black12,
color: Colors.white,
containerColor: Colors.blue,
borderRadius: 5.0,
loading: false,
text: 'Loading...',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('ProgressHUD Demo'),
),
body: new Stack(
children: <Widget>[
_progressHUD,
new Positioned(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async{
_progressHUD.state.show();
await loginAction();
_progressHUD.state.dismiss();
},
),
bottom: 30.0,
right: 10.0)
],
));
}
Future<bool> loginAction()async{
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
Har*_*llu 14
创建一个bool isLoading并将其设置为false.随着三元运营商的帮助下,当登录按钮,用户点击设定的状态isLoading来true.您将获得循环加载指示器来代替登录按钮
isLoading ? new PrimaryButton(
key: new Key('login'),
text: 'Login',
height: 44.0,
onPressed: setState((){isLoading = true;}))
: Center(
child: CircularProgressIndicator(),
),
Run Code Online (Sandbox Code Playgroud)
同时您可以运行登录过程和登录用户.如果用户凭据是错误的,那么你再会setState的isLoading到false,这样负载指示灯将成为无形和登录按钮可见的用户.顺便说一下,代码中使用的primaryButton是我的自定义按钮.你可以做同样的用OnPressed在button.
Par*_*iya 11
我建议使用这个插件flutter_easyloading
flutter_easyloading 是 Flutter App 的干净轻量级加载小部件,易于使用,无需上下文,支持 iOS 和 Android
将此添加到您的包pubspec.yaml文件中:
dependencies:
flutter_easyloading: ^2.0.0
Run Code Online (Sandbox Code Playgroud)
现在在您的 Dart 代码中,您可以使用:
import 'package:flutter_easyloading/flutter_easyloading.dart';
Run Code Online (Sandbox Code Playgroud)
要使用首先,FlutterEasyLoading在MaterialApp/ 中初始化CupertinoApp
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter EasyLoading',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter EasyLoading'),
builder: EasyLoading.init(),
);
}
}
Run Code Online (Sandbox Code Playgroud)
EasyLoading 是一个单例,因此您可以在任何地方自定义加载样式,如下所示:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import './custom_animation.dart';
void main() {
runApp(MyApp());
configLoading();
}
void configLoading() {
EasyLoading.instance
..displayDuration = const Duration(milliseconds: 2000)
..indicatorType = EasyLoadingIndicatorType.fadingCircle
..loadingStyle = EasyLoadingStyle.dark
..indicatorSize = 45.0
..radius = 10.0
..progressColor = Colors.yellow
..backgroundColor = Colors.green
..indicatorColor = Colors.yellow
..textColor = Colors.yellow
..maskColor = Colors.blue.withOpacity(0.5)
..userInteractions = true
..customAnimation = CustomAnimation();
}
Run Code Online (Sandbox Code Playgroud)
然后,根据您的要求使用
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:dio/dio.dart';
class TestPage extends StatefulWidget {
@override
_TestPageState createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
@override
void initState() {
super.initState();
// EasyLoading.show();
}
@override
void deactivate() {
EasyLoading.dismiss();
super.deactivate();
}
void loadData() async {
try {
EasyLoading.show();
Response response = await Dio().get('https://github.com');
print(response);
EasyLoading.dismiss();
} catch (e) {
EasyLoading.showError(e.toString());
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter EasyLoading'),
),
body: Center(
child: FlatButton(
textColor: Colors.blue,
child: Text('loadData'),
onPressed: () {
loadData();
// await Future.delayed(Duration(seconds: 2));
// EasyLoading.show(status: 'loading...');
// await Future.delayed(Duration(seconds: 5));
// EasyLoading.dismiss();
},
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
我采用了以下方法,该方法使用了一个简单的模式进度指示器控件,该控件包装了您希望在异步调用期间进行模式化的所有内容。
软件包中的示例还介绍了如何在进行异步调用以验证表单时处理表单验证(有关此问题的详细信息,请参见flutter / issues / 9688)。例如,在不离开表单的情况下,该异步表单验证方法可用于在注册时针对数据库中的现有名称来验证新用户名。
https://pub.dartlang.org/packages/modal_progress_hud
这是软件包随附的示例的演示(带有源代码):
示例可以适应其他模式进度指示器的行为(例如不同的动画,模式中的其他文本等)。
| 归档时间: |
|
| 查看次数: |
77044 次 |
| 最近记录: |