0

I'm new to Flutter, and I can't achieve display the snapshot.data value in a widget outside from futureBuilder scope, It's possible to do this? if not, what is the better way to do this?

//...
  var result = '0.00';
  
  Row(children: [
    const Text('RESULT: '),
    FutureBuilder(
        future: Obj.mapaProvider(widget
            .property1
            .toString()),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            result = snapshot.data.toString();
            return Text(
             result,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
              ),
            );
          } else {
            return const Text("WITHOUT RESULT");
          }
        }),                
  ]),
const Divider(
height: 20,
thickness: 5,
),
// In this widget need the new value of result variable from futurebuilder snapshot.data
OtherWidget(result), // PERHAPS SHOWS 0,00 **
//...
JOTARM
  • 1

1 Answers1

1

you should use provider for that link,

  1. You start your root Build method in the app with:
@override
  Widget build(BuildContext context) {
    return MultiProvider(  // Multi means you can have more providers if you need
      providers: [
        ChangeNotifierProvider(builder: (context) => MyStateClass()),
      ],
      child: MaterialApp(....
  1. Now you can place all the data you need to share in the MyStateClass() and place underlying Widgets inside:
Consumer<MyStateClass>(builder: (context, state, child) {

      // your code here - return(SomeOtherWidget());
    })
  1. or inside your Build methods:
  @override
  Widget build(BuildContext context) {
   MyStateClass state = Provider.of<MyStateClass>(context);
   // ... TODO  ... return (Widget)

now you can assign snapshot.data to provider and can access anywhere in your project.

Ruchit
  • 2,137
  • 1
  • 9
  • 24
  • Thank you @Ruchit, but I don't understand att all, how can I do to implement this solution, could you explain with more details? I appreciate your comments. – JOTARM Jan 06 '22 at 01:33