0

i want to for loop a button i'm using this code but it show an error , i'm stuck here for 1 day thank you
I want to use for loop because this data is dynamic.

     showDialog(
        barrierDismissible: true,
        context: context,
        builder: (BuildContext context) {
          // return object of type Dialog
          return CupertinoAlertDialog(
            title: Text('Add Location'),
            actions: <Widget>[

              for (var q = 1;q<=2;q++){

              FlatButton(
                child: new Text("Location A"),
                onPressed: () {
                  Navigator.of(context).pop();
                  locationA = 'Location A';
                },
              ),
            }

            ],
          );
        },
      );```


6
  • Why don't you just make two buttons? You don't have to do a loop if you're only making two. Commented Dec 10, 2019 at 1:50
  • That data/button is dynamic Commented Dec 10, 2019 at 1:51
  • Still don't understand why you need a for loop. First off, there should be NO logic in your build method whatsoever because it can be called at any time for any reason. Keep the logic in a separate method. Commented Dec 10, 2019 at 1:52
  • Is this in a Stateless or Stateful widget? Commented Dec 10, 2019 at 1:54
  • Im using Stateful widget Commented Dec 10, 2019 at 1:55

1 Answer 1

1

I have created a simple method that hopefully fits your needs. The method returns a list that uses a loop to add items to the list. In the end, it returns the populated list.

showDialog(
    barrierDismissible: true,
    context: context,
    builder: (BuildContext context) {
      // return object of type Dialog
      return CupertinoAlertDialog(
        title: Text('Add Location'),
        actions: _getList(), // try with or without the ()'s
      );
    },
);

// the  method
List<Widget> _getList() {
  List<Widget> temp = [];
  for (var q = 1; q<=2; q++) {
    temp.add(
      FlatButton(
        child: new Text("Location A"),
        onPressed: () {
          Navigator.of(context).pop();
          locationA = 'Location A';
        },
      );
    );
  }
  return temp;
}
Sign up to request clarification or add additional context in comments.

3 Comments

it's a good idea but its showing type 'List<dynamic>' is not a subtype of type 'Widget'
It's work but every time i select a location it will pop to my login page :D
Well I don't know how you're implementing it. I was just giving you an example of how you could do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.