Search code examples
flutterdartflutter-layoutflutter-riverpod

How to reflect the value from FutureProvider when certain UI onPressed?


I'm very new about Flutter and the library reiver_pod. I want show Text("Hello World") on screen, only when floatingActionButton pressed with using FutureProvider but it's always shown even though the button has never been pressed ? How it come and how can I Fix it ?

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 'Hello World';
});


class HomePage extends ConsumerWidget {

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final asyncValue = ref.watch(futureProvider);
    return Scaffold(
      appBar: AppBar(title: const Text('TEST')),
      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) {
            print(data);
            return Text(data.toString());//here
          },
        ),
      ),
    );
  }
}

renewal code as follow:

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'dart:math';

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 StateProvider<bool> pressProvider = StateProvider((ref) => false);

final futureProvider = FutureProvider<dynamic>((ref) async {
  var intValue = Random().nextInt(100);
  await Future.delayed(const Duration(seconds: 1));
  return intValue.toString();
});


class HomePage extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      appBar: AppBar(title: const Text('TEST')),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.refresh),
        onPressed: () {
          ref.read(pressProvider.notifier).update((state) => true);
          ref.refresh(futureProvider);
        },
      ),
      body: Center(
          child: ref.watch(pressProvider)
              ? Consumer(
                  builder: (context, ref, child) {
                    final asyncValue = ref.watch(futureProvider);

                    return asyncValue.when(
                      error: (err, _) => Text(err.toString()),
                      loading: () => const CircularProgressIndicator(),
                      data: (data) {
                        return Text(data.toString()); //here
                      },
                    );
                  },
                )
              : null),
    );
  }
}


Solution

  • You can use a bool to handle tap event like, FutureProvider will handle the UI update case.

    class HomePage extends ConsumerWidget {
      bool isPressed = false;
    
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        final asyncValue = ref.watch(futureProvider);
        return Scaffold(
          appBar: AppBar(title: const Text('TEST')),
          floatingActionButton: FloatingActionButton(
            child: const Icon(Icons.refresh),
            onPressed: () {
              isPressed = true;
              ref.refresh(futureProvider);
            },
          ),
          body: Center(
            child: isPressed
                ? asyncValue.when(
                    error: (err, _) => Text(err.toString()),
                    loading: () => const CircularProgressIndicator(),
                    data: (data) {
                      print(data);
                      return Text(data.toString()); //here
                    },
                  )
                : null,
          ),
        );
      }
    }