Home > Net >  I'm trying to use listView builder
I'm trying to use listView builder

Time:12-18

I keep getting this error when trying to use ListView how do I fix it?

error:

error: The element type 'String' can't be assigned to the list type 'Widget'. (list_element_type_not_assignable at [app_with_text] lib\main.dart:40)

code:

class Msg extends StatelessWidget {
  const Msg({Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {

    // User string(s)
    String user_msg = "user";

    // bot strings
    String friends = "";
    String quotes = "";
    String pfps = "";

    return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[

         ListView(
         children: [friends, quotes, pfps],
         );

          const TextField(
            obscureText: true,
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'Password',
            ),
          )
        ]);
  }
}

CodePudding user response:

The children property of ListView expects a list of widgets. In your code you are passing list of strings. Create text widgets using the strings you have and pass it.

ListView(
  children: [
    Text(friends),
    Text(quotes),
    Text(pfps),
  ],
),

Read more about ListView and it's properties

CodePudding user response:

@Midhun MP answer is ok, but I'm answering based on question title and next issue will occur.

ListView takes widgets on children and ListView.builder works the same way on itemBuilder.

The next issue you will occur unbounded height. To fix this, you can wrap the ListView with Expanded or use shrinkWrap: true,. Also I will suggest moving strings outside of build methods if you make it StateFullWidget

Here is using ListView.builder


class Msg extends StatelessWidget {
  const Msg({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    // User string(s)
    String user_msg = "user";

    // bot strings
    String friends = "A";
    String quotes = "B";
    String pfps = "C";

    final items = [user_msg, friends, quotes, pfps];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        // Expanded( // dont need while using `shrinkWrap:true` , based on your UI
        //   child:
        ListView.builder(
          shrinkWrap: true,
          itemCount: items.length,
          itemBuilder: (context, index) {
            return Text(
              items[index],
            );
          },
        ),
        // ),
        const TextField(
          obscureText: true,
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            labelText: 'Password',
          ),
        )
      ],
    );
  }
}

More about ListView builder

  • Related