0

When I build the code like below with using FutureProvider, the part //here executed two times, like followings;

  1. flutter: AsyncLoading<dynamic>()
  2. 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()), 
        ),
      ),
    );
  }
}
SugiuraY
  • 311
  • 1
  • 9
  • Your build may be called up to 60 times every second. You should be prepared for that and ensure that build is fast and idempotent, particularly not performing I/O. – Randal Schwartz Sep 23 '22 at 18:21
  • Thank you for your comment, but could not understand. Thats why print executed twice ? – SugiuraY Sep 23 '22 at 23:27

0 Answers0