简体   繁体   English

Flutter/Dart FutureBuilder - 如何将快照数据存储在变量中并将值传递给其他小部件?

[英]Flutter/Dart FutureBuilder - How to store a snapshot.data in a variable and pass the value to other widget?

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?我是 Flutter 的新手,我无法在 futureBuilder scope 之外的小部件中显示 snapshot.data 值,可以这样做吗? 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 **
//...

you should use provider for that link ,您应该为该链接使用provider

  1. You start your root Build method in the app with:您在应用程序中启动您的根 Build 方法:
@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:现在您可以将所有需要共享的数据放在 MyStateClass() 中,并将底层 Widgets 放在里面:
Consumer<MyStateClass>(builder: (context, state, child) {

      // your code here - return(SomeOtherWidget());
    })
  1. or inside your Build methods:或在您的 Build 方法中:
  @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.现在您可以将 snapshot.data 分配给提供者,并且可以访问项目中的任何位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM