0

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),
    );
  }
}

SugiuraY
  • 311
  • 1
  • 9

1 Answers1

1

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,
      ),
    );
  }
}
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • Thanks for your helpful comment ! However, this works only one time as the value in `isPressed` never change into `false` i guess. May I ask how can I work it more than twice ? – SugiuraY Sep 25 '22 at 14:37
  • You like to hide again ? – Md. Yeasin Sheikh Sep 25 '22 at 14:39
  • No, It's like show CircularProgressIndicator() again. Actually, my code in FutureProvider is more complicated like different value should be returned every time. like `final futureProvider = FutureProvider((ref) async { final random = Random().nextInt(100); await Future.delayed(const Duration(seconds: 3)); return random.toString(); });` – SugiuraY Sep 25 '22 at 14:48
  • Therefore, Im not intend to hide again, but do the same process continuously. – SugiuraY Sep 25 '22 at 14:51
  • I noted renewal code above, and it works but could you please advise me If I should put it in this way or not. – SugiuraY Sep 25 '22 at 15:28
  • Added `ref.refresh()` to reload FutureProvider. – SugiuraY Sep 25 '22 at 15:54
  • yes you can do that too, or use consumer widget to have ref on top level/consumerWidget, if the value of `isPressed` is true reload else refresh the provider – Md. Yeasin Sheikh Sep 25 '22 at 16:50