无法使用提供程序获取对象的最新状态

时间:2019-11-20 16:25:59

标签: flutter flutter-provider

我正在尝试从Home类获取name变量的最新状态,但是我得到的是null而不是值 Tenzin Nyidon 。如您所见,我在 MyHomePage 的构建方法中初始化了name变量,并设置了 notifyListeners()方法(通知所有侦听器 )在导航按钮的 onPress 中。

main.dart:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<MyHomePage>(builder: (_) => MyHomePage(),)
      ],
          child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(

          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(),
      ),
    );
  }
}



class MyHomePage extends StatelessWidget with ChangeNotifier {

   String name; 

 @override
  Widget build(BuildContext context) {
    //* Here I intialized the name variabel 
    name = "Tenzin Nyidon";
    return Scaffold(
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(name),
                RaisedButton(
                  child: Text("Navigate"),
                  onPressed: (){
                    //* notify all listener
                    notifyListeners();
                    Navigator.of(context).push(

                      MaterialPageRoute(
                        builder: (_){
                          return Home();
                        }
                      )

                    );                  
                    },
                )
              ],
            ),
      ),
    );
  }
}

home.dart:

class Home extends StatelessWidget {

   @override
  Widget build(BuildContext context) {
    var provider = Provider.of<MyHomePage>(context);
    return Scaffold(
      body: Center(
        //! I am getting a null value here
        child: Text("name from the main.dart: ${provider.name}"),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

尝试不使用无状态窗口小部件创建提供程序,因为它无法更新其状态。

您还必须创建一个方法来处理更改,然后调用changeNotifier();

例如:

class MyProvider extends ChangeNotifier {

  String name;

  void changeName(String newValue){
     name = newValue;
   }
}

,然后致电提供者:

更改值:

Provider.of<MyProvider>(context).changeName(newValue);

要阅读它:

Provider.of<MyProvider>(context).name;