Flutter传递对象给有状态的小部件

5

编辑 -- 错误是用户未定义。

   class _CheckInState extends State<CheckIn> {

  double _value = 0;
  String _emotionalStatus = 'Happy';
  bool didStartDrag = false;
  double updatedDragDelta;
  bool didEndDrag = false;

  @override
 Widget build(BuildContext context) {
  return Scaffold(
      appBar: new LBAppBar().getAppBar(),
      drawer: new LBDrawer().getDrawer(),
  body:
  SwipeDetector(

   child:  Container(
    decoration: BoxDecoration(
        gradient: new LinearGradient(
            colors: [Color.fromRGBO(1,89,99, 1.0), Colors.grey],
            begin: Alignment.bottomLeft,
            end: Alignment.topRight
        )
    ),
    child: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[

              Container(
                 margin: EdgeInsets.only(left: 30.0,top: 30.0, bottom: 70.0, right:30.0),
                 child :
               Text(

                'How are you feeling today Sam?', style: new TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 21.0 ))
              ,
              ),
          Text(
            '${_emojis[_value.toInt()]}',
            style: Theme.of(context).textTheme.display3,
          ),

Container(

 margin: EdgeInsets.only(left: 30.0,top: 20.0, bottom: 20.0, right:30.0),
              child: Row(
             mainAxisAlignment: MainAxisAlignment.center,
               children: <Widget> [         
                  Container(
         margin: EdgeInsets.all(10.0),
         child:  Text(

                '$_emotionalStatus', style: new TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 21.0 ))
              ,
                  )

               ]
              )

),


          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15.0),
            child:

            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(_emojis[0], softWrap: true),
                  Expanded(
                    child: Slider(
                      value: _value,
                     // label: _emojis[_value.toInt()],
                      min: 0.0,
                      max: 4.0,
                      divisions: 4,
                      onChangeStart: (double value) {
                        print('Start value is ' + value.toString());                         
                      },
                     onChangeEnd: (double value) {
          print('Finish value is ' + value.toString());
          if (value.toString() == '0.0') {
             _emotionalStatus = 'Happy';
          }
          if (value.toString() == '1.0') {
             _emotionalStatus = 'Optimistic';
          }
          if (value.toString() == '2.0') {
             _emotionalStatus = 'Neutral';
          }
          if (value.toString() == '3.0') {
             _emotionalStatus = 'Pessimistic';
          }
          if (value.toString() == '4.0') {
             _emotionalStatus = 'Sad';
          }
          setState(() {

          });
        },
                      onChanged: (double value) {
                        setState(() {
                          _value = value;
                        });
                      },
                      activeColor: Colors.white,
                      inactiveColor: Colors.white,
                    ),
                  ),
                  Text(_emojis[4], softWrap: true,)
                ],
              ),
            ),
          ),




                  Container(
         margin: EdgeInsets.all(20.0),
        child:OutlineButton(
        child: Text('Tap to Continue'), textColor: Colors.white,
         shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0)),
          onPressed: (){
           Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new CheckInQ(user: user, emoji: _emojis[_value.toInt()], mood: _emotionalStatus))
           );
           }
        )
         )

我们有一个Flutter应用程序,在按钮按下时将用户对象传递给不同的屏幕。当传递给无状态小部件时,这很有效。我尝试在有状态的小部件中实现相同的模式,但它没有起作用。我认为由于我对Flutter还不熟悉,所以我的做法是错误的,有状态的小部件必须以不同的方式处理此对象。
以下是无状态小部件的代码:
class HomeMember extends StatelessWidget {
   User user;

HomeMember({Key key, @required this.user}) : super(key: key);

  @override
  Widget build(BuildContext context){    
  bool isIOS = Theme.of(context).platform == TargetPlatform.iOS;
 return new Scaffold(
     appBar : LBAppBar().getAppBar(),
      //drawer: new LBDrawer().getDrawer(),
     body: Container(
        decoration: BoxDecoration(
        gradient: new LinearGradient(
            colors: [Color.fromRGBO(1,89,99, 1.0), Colors.grey],
            begin: Alignment.bottomLeft,
            end: Alignment.topRight
        )
    ),

  child: Column(
      mainAxisAlignment: MainAxisAlignment.center,    
      children:[
        Row(
                children: [
              Container(
                margin: EdgeInsets.only(left: 20.0,top: 10.0, bottom: 10.0, right:30.0),
                child: Column(
      children: <Widget>[



                Text("Hi ${user.firstName}, Today is " + formatDate(), style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.bold, fontSize: 19.0 )),




],

我尝试使用这种将用户对象传递给有状态小部件的方法,但它并没有起作用。

class CheckIn extends StatefulWidget {

 @override
 _CheckInState createState() => _CheckInState();
 User user; 
CheckIn({Key key, @required this.user}) : super(key: key);
}



class _CheckInState extends State<CheckIn> {

  double _value = 0;
 String _emotionalStatus = 'Happy';
  bool didStartDrag = false;
double updatedDragDelta;
bool didEndDrag = false;

什么出了问题?在 _CheckInState 中只需引用 widget.user - Richard Heap
当我尝试在按钮点击中传递用户时,它会显示“状态小部件中未定义用户”。 - Sam Cromer
State 类的任何地方需要它时,将其称为 widget.user - Richard Heap
1个回答

15

假设我们有一个无状态组件:

class HomeMember extends StatelessWidget {
  final User user;

  HomeMember({Key key, @required this.user}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: Center(
        child: Text("Hi ${user.username}",
      ),
    );
  }
}

等效的有状态小部件将如下所示:


class HomeMemberStateful extends StatefulWidget {
  final User user;
  HomeMemberStateful({Key key, @required this.user}) : super(key: key);

  @override
  _HomeMemberStatefulState createState() => _HomeMemberStatefulState();
}

class _HomeMemberStatefulState extends State<HomeMemberStateful> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: Center(
        child: Text("Hi ${widget.user.username}, this is a stateful widget",
      ),
    );
  }
}
您可以通过在状态类中调用widget.user来访问对象'user'。

绝对的传奇。谢谢你。 - Bisclavret
你将如何从HomeMemberStateful将获取的用户传递给另一个有状态小部件? - Ayush Saxena
比使用RouteSettings更加简洁! - Harmen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接