Home > OS >  How do I assign an index to list of buttons in the listview?
How do I assign an index to list of buttons in the listview?

Time:10-12

Widget inEngTaskBody(BuildContext context) {

return ListView(
scrollDirection: Axis.vertical,
children: <Widget>[

  Center(
    child: Text(
      'General Condition',
      style: TextStyle(
        decoration: TextDecoration.underline,
        fontSize: 25,
      ),
    ), //Text
  ), // Center

  OutlinedButton(
    child: Text(inEngTaskList().genCond[0]),
    onPressed: () {},
  ), //GCbutton1
  SizedBox(height: 10),

  OutlinedButton(
    child: Text(inEngTaskList().genCond[1]),
    onPressed: () {},
  ), //GCbutton2
  SizedBox(height: 10),

  OutlinedButton(
    child: Text(inEngTaskList().genCond[2]),
    onPressed: () {},
  ), //GCbutton3
  SizedBox(height: 10),

How do I assign each button an index? Was thinking of using the scrolltoindex() function. I have seen many examples using listview.builder, however, I am making a customized list view. I do not intend to use builder as each button will have a specific task upon onpressed(). Many of the examples are of non-button listview.

Appreciate the help thank you.

This code is to be assigned to the

body: inEngTask(context)

in my main.dart.

CodePudding user response:

you can use ListView.builder instead of ListView(children:...) version as follow:

ListView.builder(
  padding: const EdgeInsets.all(8),
  itemCount: NumberOfButtons, // for example 3
  itemBuilder: (BuildContext context, int index) {
    return OutlinedButton(
    child: Text(inEngTaskList().genCond[index]),
    onPressed: () {},
  ), 
  }
);

see this for more examples.

CodePudding user response:

I'm not sure you wanted auto-scroll listview or a just listview built by index. The below is the listview made by index.

ListView.builder(
  itemCount: inEngTaskList().length,
  itemBuilder: (context, index) {
  final String text = inEngTaskList().genCond[index] as String;

  return Column(
    children: [
      const Center(
      child: Text(
        'General Condition',
        style: TextStyle(
        decoration: TextDecoration.underline,
        fontSize: 25,
        ),
       ), //Text
      ), // Center

      OutlinedButton(
        child: Text(text),
        onPressed: () {},
      ),
      const SizedBox(height: 10),

      ],
    );
   },
  );

  • Related