Change background color of ListTile upon selection and custom height of tiles flutter
Asked Answered
P

1

0

I've made a GridView, but now I have some ListTiles in this GridView that I need to be selected Upon selection, I want the background color to change.

And I am also facing one more issue, I want to custom the heights of these ListTile, but I am not getting any success to do so. I am gonna attach the picture the output that I am getting and the output that I want.

What I am getting:

enter image description here

What I want:

enter image description here

Here is the code:

class _SelectLanguageNewState extends State<SelectLanguageNew> {


List<Results> listResponseData;
bool _color;

@override
void initState() {
// TODO: implement initState
super.initState();
getLang();
_color = false;

}

Future getLang() async {

await getLanguage().then((GetLanguageResponse getlanguage)
{
  if(getlanguage.isSuccess)
    {
      setState(() {
        listResponseData = getlanguage.responseData.listResults;
      });
    }




});
}


@override
Widget build(BuildContext context) {

var size = MediaQuery.of(context).size;

final double itemHeight = (size.height - kToolbarHeight - 24) / 2;
final double itemWidth = size.width / 2;


void _onTileClicked(int index){
  debugPrint("You tapped on item $index");
}



// Get grid tiles
List<Widget> _getTiles() {
  final List<Widget> tiles = <Widget>[];
  for (int i = 0; i < listResponseData.length; i++) {
    tiles.add(ListTileTheme(

      selectedColor: Colors.blue,
      child: new InkWell(
        child: new Card(
          elevation: 5.0,
          child: new Container(
            color: _color ? Colors.black : Colors.grey,
            alignment: Alignment.center,
            child: new Text(listResponseData[i].nativeText,
            style: TextStyle(color: Colors.white),),
          ),
        ),
        onTap: () {

          setState(() {
            _color = !_color;

          });

         /* showDialog(
            barrierDismissible: false,
            context: context,
            child: new CupertinoAlertDialog(

              content: new Container(
                  width: 40.0,
                  child: new CircularProgressIndicator()),
              actions: <Widget>[
                new FlatButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: new Text("OK"))
              ],
            ),
          );*/
        },
      ),
    ));
  }
  return tiles;
}









return Scaffold(
  bottomNavigationBar: BottomAppBar(
    child: Container(
      height: 50.0,
      child: InkWell(
        onTap: ()=> print('pressed'),
        child: Center(
          child: Text('Next', style: TextStyle(color: Colors.white,

          ),

          ),
        ),
      ),
    ),
    color: Colors.blue,
  ),

  body: new Container(
    child: listResponseData == null || listResponseData.isEmpty ? new Container(
      child: new Text('Loading data......'),
    ) : new GridView.count(

      shrinkWrap: true,
      scrollDirection: Axis.vertical,
      childAspectRatio:1.0,
      crossAxisCount: MediaQuery.of(context).size.width <= 400.0 ? 3 : MediaQuery.of(context).size.width >= 1000.0 ? 5 : 2,

      // Create a grid with 2 columns. If you change the scrollDirection to
      // horizontal, this would produce 2 rows.

      crossAxisSpacing: 5.0,
      // Generate 100 Widgets that display their index in the List

      children: _getTiles() ,

     ),
   ),

  );
  }
 }
Penology answered 31/1, 2019 at 9:21 Comment(0)
R
1

Screenshot

enter image description here

Complete solution:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(scaffoldBackgroundColor: Colors.black, brightness: Brightness.dark),
      home: Scaffold(
        appBar: AppBar(title: Text("Choose Language")),
        body: HomePage(),
      ),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _languageIndex = -1;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Stack(
        alignment: Alignment.bottomCenter,
        children: <Widget>[
          GridView.count(
            crossAxisCount: 2,
            crossAxisSpacing: 10,
            mainAxisSpacing: 10,
            childAspectRatio: 2.4,
            children: <Widget>[
              GestureDetector(
                child: _buildWidget("English", 0),
                onTap: () => setState(() => _languageIndex = 0),
              ),
              GestureDetector(
                child: _buildWidget("Española", 1),
                onTap: () => setState(() => _languageIndex = 1),
              ),
              GestureDetector(
                child: _buildWidget("Française", 2),
                onTap: () => setState(() => _languageIndex = 2),
              ),
              GestureDetector(
                child: _buildWidget("Gaeilge", 3),
                onTap: () => setState(() => _languageIndex = 3),
              ),
              GestureDetector(
                child: _buildWidget("العربية", 4),
                onTap: () => setState(() => _languageIndex = 4),
              ),
              GestureDetector(
                child: _buildWidget("جغتای", 5),
                onTap: () => setState(() => _languageIndex = 5),
              ),
              GestureDetector(
                child: _buildWidget("ગુજરાતી", 6),
                onTap: () => setState(() => _languageIndex = 6),
              ),
              GestureDetector(
                child: _buildWidget("हिन्दी", 7),
                onTap: () => setState(() => _languageIndex = 7),
              ),
              GestureDetector(
                child: _buildWidget("日本語", 8),
                onTap: () => setState(() => _languageIndex = 8),
              ),
              GestureDetector(
                child: _buildWidget("коми", 9),
                onTap: () => setState(() => _languageIndex = 9),
              ),
              GestureDetector(
                child: _buildWidget("ਲਹਿੰਦੀ", 10),
                onTap: () => setState(() => _languageIndex = 10),
              ),
              GestureDetector(
                child: _buildWidget("Schwyzerdütsch", 11),
                onTap: () => setState(() => _languageIndex = 11),
              ),
            ],
          ),
          SizedBox(
            width: double.maxFinite,
            height: 44,
            child: RaisedButton(
              child: Text("SUBMIT"),
              onPressed: () {
                print("languageIndex = ${_languageIndex}");
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildWidget(String language, int index) {
    bool isSelected = _languageIndex == index;
    return Container(
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6),
        border: Border.all(color: isSelected ? Colors.blue[300].withOpacity(0.8) : Colors.grey[700]),
        color: Colors.grey[900],
      ),
      child: Text(
        language,
        style: TextStyle(fontSize: 16, color: isSelected ? Colors.blue[400] : null),
      ),
    );
  }
}

You can watch which language user selected by using the _languageIndex.

Reforest answered 31/1, 2019 at 9:26 Comment(2)
thanks for the custom height solution its working fine, can you please also help me to change the color of selected tab.Penology
You need to use GestureDetector's onTap()Reforest

© 2022 - 2024 — McMap. All rights reserved.