【问题标题】:is there any way to declare provider object globally so that all buidlmethod can use it in flutter有什么方法可以全局声明提供者对象,以便所有 buidlmethod 都可以在 flutter 中使用它
【发布时间】:2022-11-23 22:01:09
【问题描述】:

我刚刚创建了一个屏幕,其中包含三个构建方法,每个方法都显示基于提供者数据的数据...这里我必须在每个方法中声明提供者对象, 有没有别的办法。。

并且不能在州级别声明显示上下文错误..

在主构建方法中创建并传递给所有子方法..这是好的代码方式吗?

这是我的代码


class _TempFileState extends State<TempFile> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(children: [
        Expanded(child: headerSection()),
        Expanded(child: categorySection()),
        Expanded(child: showTransaction()),
      ],),
    );
  }

  headerSection() {
    final provider = Provider.of<TransactionProvider>(context);
    return Row(children: [
      Text('Total Expense:' + provider.get_total_expense.toString())
    ],);
  }

  categorySection() {
    final provider = Provider.of<TransactionProvider>(context);
    return Row(children: [
      Text('Available Categories' + provider.number_of_entries.toString())
    ],);
  }

  showTransaction() {
    final provider = Provider.of<TransactionProvider>(context);
    var transaction = provider.showtransactions;

    if(transaction.length>0)
      {
        return ListView.builder(
            itemCount: transaction.length,
            itemBuilder: (context, index) {
              return Text(transaction[index].amount.toString());
            });
      }
    else
      {
        return Text('No Data Found');
      }


  }
}

【问题讨论】:

    标签: flutter


    【解决方案1】:

    您应该尝试使用某种高级状态管理解决方案。由于您已经在使用 provider,请尝试使用 riverpod。在这里了解它 - https://youtu.be/Zp7VKVhirmwhttps://riverpod.dev/docs/getting_started/

    【讨论】:

      【解决方案2】:

      要解决context问题,请尝试在initState内初始化provider

      class _TempFileState extends State<TempFile> {
        late final TransactionProvider provider;
        @override
        void initState() {
          super.initState();
          provider = Provider.of<TransactionProvider>(context);
        }
        ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-09
        • 2020-09-23
        • 2022-01-13
        • 2013-09-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多