首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >颤振StatefulWidget没有被重建

颤振StatefulWidget没有被重建
EN

Stack Overflow用户
提问于 2021-05-30 20:10:49
回答 1查看 639关注 0票数 0

我在这段代码中遇到了一些问题。我将我的小部件"ComponentsHistoriqueDeployment“移动到带有initState()的状态小部件中,以解决每次小部件重新构建时焦点上的一些问题。因此,数据实际上是第一次获取的,但是当我在搜索栏"Sélectionnez le composant“中或通过更改datePicker时,它不会改变。

我不明白为什么..。

这是家长:

代码语言:javascript
复制
class HistoriquePage extends StatefulWidget {
  final String pageName;
  final String namespace;

  const HistoriquePage({Key? key, required this.pageName, required this.namespace}) : super(key: key);

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

class _HistoriquePageState extends State<HistoriquePage> {
  final _debounce = Debounce();
  DateTimeRange? dateRange;
  String searchedValue = "";
  Post? user;

  void _sendSearch(String value) {
    _debounce.run(() {
      setState(() {
        searchedValue = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) => GestureDetector(
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.pageName),
        ),
        body: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                child: DateRangeField(
                    enabled: true,
                    firstDate: new DateTime(2020),
                    helpText: 'Sélectionnez un interval de dates',
                    fieldStartLabelText: 'Date de début',
                    fieldEndLabelText: 'Date de fin',
                    fieldStartHintText: 'Début',
                    fieldEndHintText: 'Fin',
                    dateFormat: DateFormat('dd/MM/yyyy'),
                    saveText: 'OK',
                    decoration: InputDecoration(
                      prefixIcon: Icon(Icons.date_range, color: Theme.of(context).primaryColor),
                      hintText: 'Sélectionnez un intervalle de dates',
                      hintStyle: Theme.of(context).textTheme.headline6,
                      border: OutlineInputBorder(),
                    ),
                    onChanged: (value) {
                      setState(() {
                        dateRange = value!;
                      });
                    }),
              ),
              Container(
                padding: EdgeInsets.all(16),
                child: TextField(
                    decoration: InputDecoration(
                        prefixIcon: Icon(Icons.search, color: Theme.of(context).primaryColor),
                        border: OutlineInputBorder(),
                        labelText: 'Sélectionnez le composant',
                        labelStyle: Theme.of(context).textTheme.headline6),
                    onChanged: _sendSearch),
              ),
              Container(height: MediaQuery.of(context).size.height - 150, child: ComponentsHistoriqueDeployment(searchedValue, dateRange: dateRange))
            ],
          ),
        ),
      ));
}

以及应该重建的小部件:

代码语言:javascript
复制
class ComponentsHistoriqueDeployment extends StatefulWidget {
  ComponentsHistoriqueDeployment(this.searchedValue, {this.dateRange, Key? key}) : super(key: key);

  final String searchedValue;
  final DateTimeRange? dateRange;

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

class ComponentsHistoriqueDeploymentState extends State<ComponentsHistoriqueDeployment> {
  List<User>? listOfGroups;

  @override
  void initState() {
    getGroupsList();
    super.initState();
  }

  getGroupsList() async {
    listOfGroups = await HistoriqueService.fetchHistorique(widget.searchedValue, dateRange: widget.dateRange);
    setState(() {
      listOfGroups = listOfGroups;
    });
  }

  @override
  Widget build(BuildContext context) {
    return listOfGroups == null
        ? Center(child: CircularProgressIndicator())
        : ListView.separated(
            separatorBuilder: (BuildContext context, int index) => const Divider(),
            itemCount: listOfGroups!.length,
            itemBuilder: (context, index) {
              return Card(
                child: Column(children: [
                  Padding(
                    padding: const EdgeInsets.only(top: 8),
                    child: Badge(
                      toAnimate: true,
                      animationDuration: Duration(seconds: 2),
                      shape: BadgeShape.square,
                      badgeColor: Theme.of(context).primaryColor,
                      borderRadius: BorderRadius.circular(8),
                      badgeContent: Text(listOfGroups![index].name, style: TextStyle(color: Specific.getWhite, fontSize: 16)),
                    ),
                  ),
                  _displayMoreInformationOnComponent(listOfGroups, index, context)
                ]),
              );
            });
  }

  Widget _displayMoreInformationOnComponent(result, index, context) {
    return Container(
      child: ListTile(
        title: Text('Tag: ' + result[index].username),
        subtitle: Text('Date: ' + result[index].address.street),
        leading: Icon(Icons.label),
        trailing: Wrap(
          spacing: 20,
          children: <Widget>[
            IconButton(
              icon: Icon(Icons.help),
              onPressed: () => Dialogs.bottomMaterialDialog(
                  msgStyle: TextStyle(color: Theme.of(context).textTheme.bodyText2?.color),
                  msg: 'Tag: ' +
                      result[index].name +
                      '\nStatus: ' +
                      result[index].name +
                      '\nDernier déploiement: ' +
                      result[index].name +
                      '\nType de route: ' +
                      result[index].name +
                      '\nDernier commit par: ' +
                      result[index].name +
                      '\n',
                  title: result[index].name,
                  color: Specific.getOrange,
                  context: context,
                  actions: [
                    IconsButton(
                      text: "OK",
                      iconData: Icons.check_circle,
                      color: Colors.green,
                      textStyle: TextStyle(color: Specific.getWhite),
                      iconColor: Specific.getWhite,
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                  ]),
            ),
          ],
        ),
      ),
    );
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-30 20:55:12

这是预期的行为:在小部件初始化期间只调用一次initState()。即使属性更改了它们的值,也不会重新创建State对象,因此不会调用getGroupsList()

在本例中,我建议您做的是将getGroupsList()移到_HistoriquePageState小部件上,并在搜索值或日期范围更改时调用它。然后,不是将searchedValuedateRange属性传递给ComponentsHistoriqueDeployment,而是传递listOfGroups值。

通过这种方式,您可以确保每次调用getGroupsList()以及更新UI。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67765396

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档