When I build the code like below with using FutureProvider
, the part //here
executed two times, like followings;
flutter: AsyncLoading<dynamic>()
flutter: AsyncData<dynamic>(value: World)
I could not understand why this happens, and basically meanings of watch(), in FutureProvider context.
Based on doc, watch()
says like
it's continuously watching changing in value of provider and when it is happened, UI might rebuild automatically.
What is meanings of changing especially in FutureProvider (Is it Future.delayed(const Duration(seconds: 3))
itself shown the sample below ?), and is it related to the two times execution problem, mentioned above?
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'FutureProvider',
theme: ThemeData(
textTheme: const TextTheme(bodyText2: TextStyle(fontSize: 50)),
),
home: HomePage(),
);
}
}
final futureProvider = FutureProvider<dynamic>((ref) async {
await Future.delayed(const Duration(seconds: 3));
return 'World';
});
class HomePage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final asyncValue = ref.watch(futureProvider);
print(asyncValue);//here
return Scaffold(
appBar: AppBar(title: const Text('Hello World')),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.refresh),
onPressed: () {
ref.refresh(futureProvider);
},
),
body: Center(
child: asyncValue.when(
error: (err, _) => Text(err.toString()),
loading: () => const CircularProgressIndicator(),
data: (data) => Text(data.toString()),
),
),
);
}
}