如何在Flutter中映射并从List<Object>中获取数据

huangapple go评论101阅读模式
英文:

How to map and get data from List<Object> in Flutter

问题

以下是您要的翻译部分:

我正在使用CarouselSlider包,我使用的项目来自硬编码的数据。我想从List&lt;Object&gt;中映射数据。这是我的对象:

final List&lt;Object&gt; imgListObject = [
  {&quot;image&quot;: &quot;/imageAsset1&quot;, &quot;text&quot;: &#39;Text 1&#39;},
  {&quot;image&quot;: &quot;/imageAsset2&quot;, &quot;text&quot;: &#39;Text 2&#39;},
  {&quot;image&quot;: &quot;/imageAsset3&quot;, &quot;text&quot;: &#39;Text 3&#39;},
];

这是我打算获取数据的方式:

final List&lt;Widget&gt; imageSliders = imgListObject
    .map(
      (data) =&gt; Column(
        children: [
          Image.asset(data[&#39;image&#39;]),
          Text(data[&#39;text&#39;]),
        ],
      ),
    )
    .toList();

我从data[&#39;image&#39;]data[&#39;text&#39;]遇到了这个错误:

运算符&#39;[]&#39;未定义为&#39;Object&#39;类型。

我的完整代码:

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

  @override
  Widget build(BuildContext context) {
    ContentSession contentSession = Provider.of&lt;ContentSession&gt;(context, listen: false);

    final CarouselController _carouselController = CarouselController();

    final List&lt;Object&gt; imgListObject = [
      {&quot;image&quot;: AppGlobalVariables.howItWorksSliderImage1, &quot;text&quot;: &#39;Text 1&#39;},
      {&quot;image&quot;: AppGlobalVariables.howItWorksSliderImage2, &quot;text&quot;: &#39;Text 2&#39;},
      {&quot;image&quot;: AppGlobalVariables.howItWorksSliderImage3, &quot;text&quot;: &#39;Text 3&#39;},
    ];

    final List&lt;Widget&gt; imageSliders = imgListObject
        .map(
          (data) =&gt; Column(
            children: [
              Image.asset(data[&#39;image&#39;]),
              Text(data[&#39;text&#39;]),
            ],
          ),
        )
        .toList();

    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(50),
        child: AppbarMain(),
      ),
      body: Column(
        children: [
          CarouselSlider(
            carouselController: _carouselController,
            options: CarouselOptions(
              viewportFraction: 0.8,
              enableInfiniteScroll: true,
              enlargeCenterPage: true,
              autoPlay: true,
              height: 400,
            ),
            items: imageSliders,
          ),
          SizedBox(
            height: 40,
          ),
          ElevatedButton(
            onPressed: () async =&gt; Navigator.pushNamed(context, landingScreenRoute!),
            child: Text(contentSession.stringsHomeScreen.signin),
          ),
        ],
      ),
    );
  }
}

希望这有助于您获得所需的输出。

英文:

I'm using CarouselSlider package and the items I used is from a hardcoded data. I'd like to get data from mapping it from a List&lt;Object&gt;. Here is my object:

    final List&lt;Object&gt; imgListObject = [
      {&quot;image&quot;: &quot;/imageAsset1&quot;, &quot;text&quot;: &#39;Text 1&#39;},
      {&quot;image&quot;: &quot;/imageAsset2&quot;, &quot;text&quot;: &#39;Text 2&#39;},
      {&quot;image&quot;: &quot;/imageAsset3&quot;, &quot;text&quot;: &#39;Text 3&#39;},
    ];

And this is how I intend to get the data:

    final List&lt;Widget&gt; imageSliders = imgListObject
        .map(
          (data) =&gt; Column(
            children: [
              Image.asset(data[&#39;image&#39;]),
              Text(data[&#39;text&#39;]),
            ],
          ),
        )
        .toList();

I have this error from data[&#39;image&#39;] and data[&#39;text&#39;]:

The operator &#39;[]&#39; isn&#39;t defined for the type &#39;Object&#39;.

My full code:

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

  @override
  Widget build(BuildContext context) {
    ContentSession contentSession = Provider.of&lt;ContentSession&gt;(context, listen: false);

    final CarouselController _carouselController = CarouselController();

    final List&lt;Object&gt; imgListObject = [
      {&quot;image&quot;: AppGlobalVariables.howItWorksSliderImage1, &quot;text&quot;: &#39;Text 1&#39;},
      {&quot;image&quot;: AppGlobalVariables.howItWorksSliderImage2, &quot;text&quot;: &#39;Text 2&#39;},
      {&quot;image&quot;: AppGlobalVariables.howItWorksSliderImage3, &quot;text&quot;: &#39;Text 3&#39;},
    ];

    final List&lt;Widget&gt; imageSliders = imgListObject
        .map(
          (data) =&gt; Column(
            children: [
              Image.asset(data[&#39;image&#39;]),
              Text(data[&#39;text&#39;]),
            ],
          ),
        )
        .toList();

    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(50),
        child: AppbarMain(),
      ),
      body: Column(
        children: [
          CarouselSlider(
            carouselController: _carouselController,
            options: CarouselOptions(
              viewportFraction: 0.8,
              enableInfiniteScroll: true,
              enlargeCenterPage: true,
              autoPlay: true,
              height: 400,
            ),
            items: imageSliders,
          ),
          SizedBox(
            height: 40,
          ),
          ElevatedButton(
            onPressed: () async =&gt; Navigator.pushNamed(context, landingScreenRoute!),
            child: Text(contentSession.stringsHomeScreen.signin),
          ),
        ],
      ),
    );
  }
}

I'm hoping to have this output:
如何在Flutter中映射并从List<Object>中获取数据

答案1

得分: 1

以下是您要翻译的内容:

问题很明显:

final List<Object> imgListObject = [
  {"image": "/imageAsset1", "text": 'Text 1'},
  {"image": "/imageAsset2", "text": 'Text 2'},
  {"image": "/imageAsset3", "text": 'Text 3'},
];

这是一个包含ObjectList,所以当您稍后调用:

Column(
    children: [
        Image.asset(data['image']),
        Text(data['text']),
    ],
)

它无法访问data['image'],因为它认为它是一个Object而不是一个Map

您将需要显式地转换类型。您可以使用as关键字来做到这一点:

final List<Widget> imageSliders = imgListObject.map(
    (item) {
        Map<String, String> data = item as Map<String, String>;
        return Column(
            children: [
                // 使用`!`操作符来断言该值不为空
                Image.asset(data['image']!),
                Text(data['text']!),
            ],
        );
    },
).toList();

或者作为另一种选择,为imgListObject指定正确的类型:

final List<Map<String, String>> imgListObject = [
    {"image": "/imageAsset1", "text": 'Text 1'},
    {"image": "/imageAsset2", "text": 'Text 2'},
    {"image": "/imageAsset3", "text": 'Text 3'},
];

参考链接

英文:

The problem is obvious:

  final List&lt;Object&gt; imgListObject = [
  {&quot;image&quot;: &quot;/imageAsset1&quot;, &quot;text&quot;: &#39;Text 1&#39;},
  {&quot;image&quot;: &quot;/imageAsset2&quot;, &quot;text&quot;: &#39;Text 2&#39;},
  {&quot;image&quot;: &quot;/imageAsset3&quot;, &quot;text&quot;: &#39;Text 3&#39;},
];

is a List of Object's, so when you later call:

Column(
            children: [
              Image.asset(data[&#39;image&#39;]),
              Text(data[&#39;text&#39;]),
            ],

it can't access data[&#39;image&#39;] since it thinks it's an Object not a Map.

You'll have to explicitly cast the type. you can do so using the as keyword:

final List&lt;Widget&gt; imageSliders = imgListObject.map(
      (item) {
        Map&lt;String, String&gt; data = item as Map&lt;String, String&gt;;
        return Column(
          children: [
            // using the `!` operator to assert that the value is not null
            Image.asset(data[&#39;image&#39;]!),
            Text(data[&#39;text&#39;]!),
          ],
        );
      },
    ).toList();

Or as an alternative, specify the correct type for imgListObject:

final List&lt;Map&lt;String, String&gt;&gt; imgListObject = [
      {&quot;image&quot;: &quot;/imageAsset1&quot;, &quot;text&quot;: &#39;Text 1&#39;},
      {&quot;image&quot;: &quot;/imageAsset2&quot;, &quot;text&quot;: &#39;Text 2&#39;},
      {&quot;image&quot;: &quot;/imageAsset3&quot;, &quot;text&quot;: &#39;Text 3&#39;},
    ];

See also

答案2

得分: 1

以下是翻译好的代码部分:

const List<Object> imgListObject = [
  {'image': '/imageAsset1', 'text': 'Text 1'},
  {'image': '/imageAsset2', 'text': 'Text 2'},
  {'image': '/imageAsset3', 'text': 'Text 3'},
];

List<Column> columns() => [
      for (final item in imgListObject)
        Column(
          children: switch (item) {
            {
              'image': final String image,
              'text': final String text,
            } =>
                [
                  Image.asset(image),
                  Text(text),
                ],
            final v => throw Exception('what is $v'),
          },
        ),
    ];
英文:

Here's another way to extract that, with patterns:

const List&lt;Object&gt; imgListObject = [
  {&#39;image&#39;: &#39;/imageAsset1&#39;, &#39;text&#39;: &#39;Text 1&#39;},
  {&#39;image&#39;: &#39;/imageAsset2&#39;, &#39;text&#39;: &#39;Text 2&#39;},
  {&#39;image&#39;: &#39;/imageAsset3&#39;, &#39;text&#39;: &#39;Text 3&#39;},
];

List&lt;Column&gt; columns() =&gt; [
      for (final item in imgListObject)
        Column(
          children: switch (item) {
            {
              &#39;image&#39;: final String image,
              &#39;text&#39;: final String text,
            } =&gt;
              [
                Image.asset(image),
                Text(text),
              ],
            final v =&gt; throw Exception(&#39;what is $v&#39;),
          },
        ),
    ];

huangapple
  • 本文由 发表于 2023年8月5日 03:33:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定