简体   繁体   中英

How to make widget based on List<String> Flutter

I have an array of string: var choices = ['a', 'b', 'c'];

I want to make a text widget by iterating through each strings. I believe the usual way doing this is using map

Column(
children: choices.map((item) {
    return Text(item);
 }).toList()
)

However, i get The element type 'List' can't be assigned to the list type 'Widget'. exception. Is map not working anymore?

Your code is correct and works as expected. I replicated your code on dartpad.dev as follows:

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  final List<String> choices = ["one", "two", "three", "four"];
  @override
  Widget build(BuildContext context) {
    return Column(
        children: choices.map((item) {
      return Text(item);
    }).toList());
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM