Home > Mobile >  Flutter: Data exchange between widgets
Flutter: Data exchange between widgets

Time:09-16

I'm building a Flutter application that has several main navigation screens:

class TestApp extends StatelessWidget {
  const TestApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) => MultiProvider(
          providers: [
            ChangeNotifierProvider(
                create: (context) => AccountModel()),
          ],
          child: MaterialApp(
            title: 'Flutter Demo',
            theme: ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: _MyHomePage(),
          ));
}

class _MyHomePageState extends State<_MyHomePage> {
  var _pageIndex = 0;

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text("Test"),
        ),
        body: IndexedStack(
          index: _pageIndex,
          children: [
            AccountsWidget(),
            TransactionsWidget()
          ],
        ),
        bottomNavigationBar: BottomNavigationBar(
          items: [
            BottomNavigationBarItem(label: "Accounts"),
            BottomNavigationBarItem(label: "Transactions"),
          ],
          currentIndex: _pageIndex,
          onTap: (index) => {
            setState(() {
              _pageIndex = index;
            })
          },
        ),
      );
  }

I want to be able to pass data from one widget (Transactions) to another (Accounts) in order to select matching item in the list. Accounts widget is implemented as following:

class _AccountsState extends State<AccountsWidget> {
  @override
  Widget build(BuildContext context) =>
      Consumer<AccountsModel>(builder: (context, accounts, child) => Column(
          children: [
            Expanded(
                child: ListView.builder(
                    controller: listCtrl,
                    itemCount: accounts.items.length,
                    itemBuilder: (BuildContext context, int index) => Card(
                        color:
                            accounts.items[index] == accounts.selectedAccount
                                ? Colors.blue
                                : Colors.white,
                        child: ListTile(
                            title: Text(accounts.items[index].toString()))
                    )
                )
            ),
          ],
      );
  );
}

AccountModel has a selectedAccount property that should be set in Transactions widget. However I can't figure out how to access proper instance of AccountModel.

My question is - how to properly organize data exchange between different widgets? My understanding is that models should be the access point to all data but I see no global way to access models. I could wrap Transactions widget into Consumer<AccountModel> but in case of further models I'd need to add more and more wrapping and I don't think it's a good architecture.

CodePudding user response:

You need to create get methods in AccountModel and whichever class wanted to access it under your TestApp widget can access it using Provider.of<AccountModel>.somegetmethod(). All your data should be stored in instances of AccountModel class and should be accessed using get methods.

Adding it here so this question can be closed.

  • Related