在Flutter中访问对象数据

时间:2019-09-29 17:44:40

标签: flutter dart

我是Flutter的新手,正在尝试完成一些基础知识。我想从代码中多个位置的对象访问数据。

我很可能在oo代码中混淆范围或变量类型。到目前为止,我只使用使用javascript或php进行基本编码,而从不使用过多的对象和东西。

请在下面查看我的示例代码:

class _APPS extends State<APP>
    with SingleTickerProviderStateMixin {

  final pages = {
    "events": {
      "title": "Events",
      "icon": Icon(Icons.event),
      "page": EventsSite(),
    },
    "news": {
      "title": "News",
      "icon": Icon(Icons.message),
      "page": NewsSite(),
    },
    "favorites": {
      "title": "Favorites",
      "icon": Icon(Icons.favorite),
      "page": EventsSite(),
    },
    "profile": {
      "title": "Profile",
      "icon": Icon(Icons.account_circle),
      "page": EventsSite(),
    },
  };

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Builder(
        builder: (context) => Scaffold(
          body: PageView(
            controller: _pageController,
            //physics: NeverScrollableScrollPhysics(),
            onPageChanged: _onPageChanged,
            children: [
              pages[0]['page'], <=== Here is what i'm trying to do
              NewsSite(),
              Icon(Icons.directions_bike),
            ],
          ),
          bottomNavigationBar: BottomNavigationBar(
            type: BottomNavigationBarType.fixed,
            showUnselectedLabels: false,
            backgroundColor: _colorBackgroundBright,
            unselectedItemColor: Colors.white,
            selectedItemColor: _colorHighlight,
            selectedLabelStyle: TextStyle(fontSize: 10.0),
            iconSize: 20,
            currentIndex: _selectedIndex,
            onTap: _onItemTapped,
            items: const <BottomNavigationBarItem>[
              BottomNavigationBarItem(
                icon: Icon(pages['Events']['icon']), <=== Here is what i'm trying to do
                title: Text(pages[0]['title']), <=== Here is what i'm trying to do
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.message),
                title: Text('News'),
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.favorite),
                title: Text('Favorites'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Screenshot with my intent and the error

1 个答案:

答案 0 :(得分:0)

您需要正确访问Map

您要指定正确的,而不是pages[0]pages['Events']

pages['events']

地图键区分大小写,因为它们使用equals operator


创建Map时无法访问const。因此,请从const处删除const <BottomNavigationBarItem>[

<BottomNavigationBarItem>[
  ...
]

此外,对于图标,您需要使用pages['events']['icon']