首页 > 解决方案 > 我如何实时查看下拉按钮

问题描述

我的问题是我无法实时看到我选择的实时字符串。例如,如果我从下拉项目中选择一个字符串,那么我看不到它。如果我想看到它,首先我必须返回并再次打开表格。我该如何解决这个问题?(顺便说一句,它有效,提交按钮没有问题。我只是想看看用户选择什么。

我的问题: 在此处输入图像描述

我的代码:

Widget dropdownButton(BuildContext context) {
    String constantValue = "League Of Legends";
    return DropdownButton(
        value: context.read<PostProvider>().postCategory ?? constantValue,
     
        onChanged: (newValue) {
          context.read<PostProvider>().postCategory = newValue;
     
        },
        items: <String>["League Of Legends", "Steam", "Csgo"]
            .map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            onTap: () => context.read<PostProvider>().postCategory,
            value: value,
            child: Text(value),
          );
        }).toList());
  }






String get postCategory => _postCategory;

  set postCategory(String value) {
    _postCategory = value;
    notifyListeners();
  }

PostProvider 还扩展了 changenotifier:

String get postCategory => _postCategory;

  set postCategory(String value) {
    _postCategory = value;
    notifyListeners();
  }

主页:

Scaffold(
        floatingActionButton: CreatePostButton(),
        appBar: AppBar(
          title: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("Home Page"),
              IconButton(
                  onPressed: () {
                    provider.logout();
                  },
                  icon: FaIcon(FontAwesomeIcons.poo))
            ],
          ),
        ),
        body: HomePageWidget())

创建帖子按钮:

class CreatePostButton extends StatelessWidget {
  static final _formKey = GlobalKey<FormState>(debugLabel: '_formKey');
  static final _scaffoldKey = GlobalKey<ScaffoldState>();
  @override
  Widget build(BuildContext context) => Padding(
        padding: const EdgeInsets.only(right: 13.0, bottom: 13.0),
        child: FloatingActionButton(
            child: FaIcon(FontAwesomeIcons.plus),
            onPressed: () {
              showDialog(context: context, child: buildAlertDialog(context));
            }),
      );

  Widget buildAlertDialog(BuildContext context) {
    final provider = Provider.of<PostProvider>(context, listen: false);
    return AlertDialog(
      content: Form(
        key: _formKey,
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Padding(
                  padding: EdgeInsets.all(8.0),
                  child: TextFormField(
                      autocorrect: true,
                      textCapitalization: TextCapitalization.words,
                      enableSuggestions: false,
                      validator: (value) {
                        if (value.isEmpty || value.length <= 4) {
                          return 'Please enter at least 4 characters';
                        } else {
                          return null;
                        }
                      },
                      decoration: InputDecoration(labelText: 'Post Title'),
                      onChanged: (postTitle) {
                        provider.postTitle = postTitle;
                      })),
              Padding(
                  padding: EdgeInsets.all(8.0),
                  child: TextFormField(
                      autocorrect: true,
                      textCapitalization: TextCapitalization.words,
                      enableSuggestions: false,
                      validator: (value) {
                        if (value.isEmpty || value.length <= 25) {
                          return 'Please enter at least 25 characters';
                        } else {
                          return null;
                        }
                      },
                      decoration:
                          InputDecoration(labelText: 'Write a post details'),
                      onChanged: (postDetails) {
                        provider.postDetails = postDetails;
                      })),
              Padding(
                  padding: EdgeInsets.all(8.0),
                  child: TextFormField(
                      enableSuggestions: false,
                      inputFormatters: <TextInputFormatter>[
                        FilteringTextInputFormatter.digitsOnly
                      ],
                      keyboardType: TextInputType.number,
                      validator: (value) {
                        if (value.isEmpty || value.length >= 4) {
                          return 'Please enter a valid value';
                        } else {
                          return null;
                        }
                      },
                      decoration: InputDecoration(labelText: 'Enter the Price'),
                      onChanged: (gamePrice) {
                        provider.gamePrice = gamePrice;
                      })),
              dropdownButton(context),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: RaisedButton(
                    child: Text("Submit"),
                    onPressed: () => submitNewPost(context)),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future submitNewPost(BuildContext context) async {
    final provider = Provider.of<PostProvider>(context, listen: false);
    final isValid = _formKey.currentState.validate();
    FocusScope.of(context).unfocus();
    if (isValid) {
      _formKey.currentState.save();

      final isSuccess = await provider.createNewPost();

      if (isSuccess) {
        Navigator.of(context).pop();
      } else {
        final message = 'An error occurred, please check your inputs!';

        Center(child: Text(message),);
      }
    }
  }

  Widget dropdownButton(BuildContext context) {
    String constantValue = "League Of Legends";
    return DropdownButton(
        value: context.read<PostProvider>().postCategory ?? constantValue,
     
        onChanged: (newValue) {
          context.read<PostProvider>().postCategory = newValue;
     
        },
        items: <String>["League Of Legends", "Steam", "Csgo"]
            .map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            onTap: () => context.read<PostProvider>().postCategory,
            value: value,
            child: Text(value),
          );
        }).toList());
  }
}

标签: flutterproviderstate-management

解决方案


用消费者包装下拉按钮以更新小部件:

    Widget dropdownButton(BuildContext context) {
                String constantValue = "League Of Legends";
                
    
       return Consumer<PostProvider>(builder: (_context, _postprovider, _widget) { 
             return DropdownButton(
                    value: _postprovider.postCategory  ?? constantValue,
                 
                    onChanged: (newValue) {
                      _postprovider.postCategory = newValue;
                 
                    },
                    items: <String>["League Of Legends", "Steam", "Csgo"]
                        .map<DropdownMenuItem<String>>((String value) {
                      return DropdownMenuItem<String>(
                        onTap: () => context.read<PostProvider>().postCategory,
                        value: value ?? constantValue,
                        child: Text(value ?? constantValue),
                      );
                    }).toList());
              });
      }

在这里添加这个:

 Future submitNewPost(BuildContext context) async {
    final provider = Provider.of<PostProvider>(context, listen: false);
    final isValid = _formKey.currentState.validate();
    FocusScope.of(context).unfocus();
    if (isValid) {
       if( provider.postCategory == null || provider.postCategory.isEmpty){
         provider.postCategory = "League Of Legends";
       } 

      _formKey.currentState.save();

      final isSuccess = await provider.createNewPost();

      if (isSuccess) {
        Navigator.of(context).pop();
      } else {
        final message = 'An error occurred, please check your inputs!';

        Center(child: Text(message),);
      }
    }
  }

推荐阅读