Home > other >  is there any way to declare provider object globally so that all buidlmethod can use it in flutter
is there any way to declare provider object globally so that all buidlmethod can use it in flutter

Time:11-23

I have just created a screen that has three build methods and each method showing data based on provider data...here I have to declare provider object in each method, is there any other way..

and can't declare at state level as showing error of context..

createing in main build method and passing to all child method..is it good way of code?

here is my code


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');
      }


  }
}

CodePudding user response:

You should try to use some kind of advanced state management solution. Since you are already using provider, try using riverpod. Learn about it here - https://youtu.be/Zp7VKVhirmw or https://riverpod.dev/docs/getting_started/

CodePudding user response:

To resolve the context issue, try to initialize provider inside initState

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