我通过创建一个懒惰的查询类来解决这个问题。
import 'package:flutter/cupertino.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
class LazyQuery<TParsed> extends StatefulWidget {
const LazyQuery ({
final Key? key,
required this.options,
required this.builder,
});
final QueryOptions<TParsed> options;
final QueryBuilder<TParsed> builder;
@override
State<LazyQuery> createState() => _LazyQueryState();
}
class _LazyQueryState extends State<LazyQuery> {
bool initialFetch = false;
final QueryResult<String> result= QueryResult.unexecuted;
get fetchMore => null;
Future<QueryResult<Object?>> refetch(){
setState(() {
initialFetch =true;
});
return Future(() =>QueryResult.unexecuted);
}
@override
Widget build(BuildContext context) {
if(initialFetch) {
return Query(options: widget.options, builder: widget.builder);
} else {
return widget.builder(
result ,
fetchMore: fetchMore,
refetch: refetch,
); ;
}
}
}
使用方法
LazyQuery(
options: QueryOptions(
variables: {
"email":email,
"password":password,
},
fetchPolicy: FetchPolicy.networkOnly,
document: loginQuery ),
builder: (QueryResult result, {fetchMore, refetch}) {
if (result.data != null) {
moveToHome(result.data?["login"]);
}
return result.isLoading
? const LoadingIndicator(
indicatorType: Indicator.ballPulseSync, // Required, The loading type of the widget
colors: [Colors.green],
)
: Column(
children: [
Row( mainAxisAlignment:MainAxisAlignment.end,
children: [TextButton(onPressed:(){
}, child: const Text("Forget password"))],),
const SizedBox(height: 16,),
Center(
child: ElevatedButton(onPressed: () async {
refetch!();
}, child: const Text("Login")),
),
],
);
}
),